diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..58aa143104c9ca02739a1b47fa9bf037d3a8b83a --- /dev/null +++ b/.dockerignore @@ -0,0 +1,16 @@ +.git +.gitignore +.env +.venv +venv +__pycache__ +*.py[cod] +*.egg-info +.pytest_cache +.ruff_cache +.mypy_cache +build +dist +docs +logs +tests diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..71fc064b7e909d8013bff33aeff14eba81f2e933 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,57 @@ +FROM python:3.12-slim-bookworm + +ARG APP_UID=1000 +ARG APP_GID=1000 + +LABEL org.opencontainers.image.title="SRHarness" \ + org.opencontainers.image.description="A harness for agentic symbolic regression" \ + org.opencontainers.image.url="https://github.com/yuzhTHU/SRHarness" \ + org.opencontainers.image.source="https://github.com/yuzhTHU/SRHarness" \ + org.opencontainers.image.licenses="MIT" + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + MPLCONFIGDIR=/tmp/matplotlib \ + XDG_CACHE_HOME=/tmp/cache + +RUN groupadd --gid "${APP_GID}" srharness \ + && useradd --uid "${APP_UID}" --gid "${APP_GID}" --create-home --shell /usr/sbin/nologin srharness + +WORKDIR /app + +COPY pyproject.toml README.md LICENSE ./ + +RUN --mount=type=cache,target=/root/.cache/pip python - <<'PY' +import subprocess +import sys +import tomllib +from pathlib import Path + +project = tomllib.loads(Path("pyproject.toml").read_text())["project"] +requirements = [ + *project["dependencies"], + *project["optional-dependencies"]["tools"], +] +subprocess.check_call([sys.executable, "-m", "pip", "install", *requirements]) +PY + +COPY src ./src + +RUN --mount=type=cache,target=/root/.cache/pip python -m pip install --no-deps . \ + && python -m pip check + +RUN install -d -o "${APP_UID}" -g "${APP_GID}" \ + /data \ + /usr/local/lib/python3.12/site-packages/sr_harness/skills/custom + +USER srharness +WORKDIR /data + +EXPOSE 8000 + +HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \ + CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=3).close()" + +ENTRYPOINT ["sr-harness"] +CMD ["run", "--save-path", "/data", "--workspace-dir", "/data", "--isolate-users", "--host", "0.0.0.0", "--port", "8000"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6fe7518a8a2d0c4d9e6bd6ad3d0a31a6c9e40c49 --- /dev/null +++ b/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) 2026-present, YuMeow. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index ddbb513b4282eaf86a518df496d3b9e873e19f4d..b41740ca056be4833f91346b3663f1b81f02e316 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,128 @@ --- title: SRHarness -emoji: 📚 -colorFrom: red -colorTo: indigo +emoji: 🔬 +colorFrom: blue +colorTo: green sdk: docker +app_port: 8000 pinned: false +license: mit +short_description: Agentic symbolic regression workbench --- -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference +# SRHarness: A Harness for Agentic Symbolic Regression + +[English](README.md) | [简体中文](README.zh.md) + +[![GitHub](https://img.shields.io/github/stars/yuzhTHU/SRHarness?style=flat&logo=github&label=GitHub)](https://github.com/yuzhTHU/SRHarness) +[![PyPI](https://img.shields.io/pypi/v/sr-harness?logo=pypi&logoColor=white)](https://pypi.org/project/sr-harness/) +[![Docker](https://img.shields.io/docker/v/yumeoww/sr-harness?sort=semver&logo=docker&logoColor=white&label=Docker)](https://hub.docker.com/r/yumeoww/sr-harness) +[![Documentation](https://img.shields.io/badge/docs-GitHub%20Pages-4e968b?logo=materialformkdocs&logoColor=white)](https://yuzhthu.github.io/SRHarness/) +[![Live WebUI](https://img.shields.io/badge/WebUI-live-4e968b?logo=googlechrome&logoColor=white)](http://sim1.fiblab.tech:30000/) +[![arXiv](https://img.shields.io/badge/arXiv-2609.35501-b31b1b?logo=arxiv&logoColor=white)](https://arxiv.org/abs/2609.35501) +[![Documentation build](https://github.com/yuzhTHU/SRHarness/actions/workflows/docs.yml/badge.svg?branch=dev)](https://github.com/yuzhTHU/SRHarness/actions/workflows/docs.yml) +[![Python](https://img.shields.io/badge/python-%E2%89%A53.12-3776AB?logo=python&logoColor=white)](https://pypi.org/project/sr-harness/) +[![License](https://img.shields.io/github/license/yuzhTHU/SRHarness)](LICENSE) + +SRHarness is a domain-specific runtime for **agentic symbolic regression**. It lets language-model agents prepare scientific data, invoke composable analysis and fitting tools, retain evaluated hypotheses, and refine interpretable formulas over long search trajectories. Its interactive workbench also supports persistent conversations, editable task configuration, and task-specific formula evaluation through custom Evaluators. + + +## Highlights + +- **Composable scientific actions:** analysis, fitting, evaluation, code execution, and formula submission use a shared tool interface. +- **Persistent scientific state:** candidates, metrics, complexity, diagnostics, provenance, and Pareto rankings survive beyond one model response. +- **Managed search trajectories:** the `R-C-L-K` lifecycle coordinates restarts, branches, refinement depth, and local sampling. +- **Interactive research workflow:** the WebUI connects data preparation, task configuration, Evaluator construction, symbolic search, human guidance, and persistent workspaces. +- **Extensible symbolic modeling:** SRHarness Engine supports ordinary expressions as well as indexed graph and hypergraph formulas. + +## Results + +The [paper](https://arxiv.org/abs/2609.35501) evaluates SRHarness on LLM-SRBench under matched language-model backbones. LSR-Transform measures symbolic recovery on transformed scientific equations, while LSR-Transform-Anon removes scientific descriptions and variable semantics to test whether the search process remains effective without domain-specific textual cues. The table reports symbolic accuracy (SA): + +| Method / backbone | LSR-Transform | LSR-Transform-Anon | +|---|---:|---:| +| SRHarness + DeepSeek-v4-flash-0731 | **93.69%** | **72.97%** | +| SR-Scientist + DeepSeek-v4-flash-0731 | 62.16% | 39.64% | +| Codex + DeepSeek-v4-flash-0731 | — | 20.72% | + +With the same DeepSeek-v4-flash-0731 backbone, SRHarness substantially improves symbolic recovery over SR-Scientist on both settings. Its accuracy remains comparatively high after descriptions and variable semantics are removed, and it also outperforms Codex on the anonymized benchmark. These results indicate that the structured runtime—scientific actions, persistent hypothesis state, and trajectory management—contributes materially beyond the choice of language model alone. See the paper for the complete evaluation protocol, numerical-generalization results, complexity and resource analyses, and ablation studies. + +## Installation + +SRHarness requires Python 3.12 or newer. + +```bash +pip install sr-harness +``` + +See the [installation guide](https://yuzhthu.github.io/SRHarness/install/) for provider configuration, source installation, development environments, and optional integrations. + +### Hugging Face Spaces + +The repository can be deployed directly as a Docker Space. See the +[Hugging Face deployment guide](deploy/huggingface/README.md) for creation, +secrets, persistence, and security guidance. + +## Quick Start + +### Discover a known equation: `sr-harness synthetic` + +Set `OPENROUTER_API_KEY`, then use `synthetic` to generate data from a known equation and test whether SRAgent can recover it: + +```bash +sr-harness synthetic \ + --equation 'y = 1 + x1 ** 2 + 2 * x1 * x2' \ + --n-samples 200 \ + --x-low -2 \ + --x-high 2 \ + --seed 42 \ + --llm-provider openrouter \ + --llm-model deepseek/deepseek-v4-flash-0731 \ + --save-path ./logs/quick-start \ + -R 1 -C 1 -L 10 -K 1 +``` + +If you use another provider, configure its API key and change `--llm-provider` and `--llm-model` accordingly. + +### Interactive workbench: `sr-harness run` + +Use `run` for the complete interactive research workflow. It starts the WebUI for data preparation, task and evaluator configuration, symbolic-regression search, and human guidance: + +```bash +sr-harness run \ + --host 127.0.0.1 \ + --port 8000 \ + --workspace-dir ./workspaces \ + --save-path ./logs/webui +``` + +Then open . The workspace registry and conversation workspaces are stored under `./workspaces`, while session snapshots and run records are stored under `./logs/webui`. A hosted instance is also available at . + +## Documentation + +- [Overview](https://yuzhthu.github.io/SRHarness/) +- [Quick Start](https://yuzhthu.github.io/SRHarness/quick-start/) +- [Installation and provider configuration](https://yuzhthu.github.io/SRHarness/install/) +- [Commands and runtime options](https://yuzhthu.github.io/SRHarness/sr-harness/) +- [SRHarness Agent Workflow](https://yuzhthu.github.io/SRHarness/agent/) +- [Tools and tool-call Parsers](https://yuzhthu.github.io/SRHarness/core-abstractions/) +- [Structured data and `context.data`](https://yuzhthu.github.io/SRHarness/context-data/) +- [Formula evaluation and custom Evaluators](https://yuzhthu.github.io/SRHarness/evaluator/) +- [SRHarness WebUI](https://yuzhthu.github.io/SRHarness/web-ui/) +- [SRHarness Engine](https://yuzhthu.github.io/SRHarness/engine/) +- [API reference](https://yuzhthu.github.io/SRHarness/reference/) + +## Citation + +```bibtex +@article{yu2026srharness, + title = {SRHarness: A Harness for Agentic Symbolic Regression}, + author = {Yu, Zihan and Zhou, Shixuan and Huang, Hao and Ding, Jingtao and Li, Yong}, + journal = {arXiv preprint arXiv:2609.35501}, + year = {2026} +} +``` + +## License + +SRHarness is released under the [MIT License](LICENSE). diff --git a/deploy/huggingface/README.md b/deploy/huggingface/README.md new file mode 100644 index 0000000000000000000000000000000000000000..bfbff2b10e14586c7d41215b65647947762a91fc --- /dev/null +++ b/deploy/huggingface/README.md @@ -0,0 +1,75 @@ +# Deploying SRHarness on Hugging Face Spaces + +SRHarness can run as a Hugging Face Docker Space using the repository's root +`Dockerfile`. The Space metadata at the top of the root `README.md` tells +Hugging Face to expose the application's existing port, `8000`. + +## 1. Create the Space + +Create a new Space with the **Docker** SDK. A private Space is recommended when +the deployment uses an owner-funded model API key. Then push this repository to +the Space repository: + +```bash +git remote add huggingface https://huggingface.co/spaces/OWNER/SPACE_NAME +git push huggingface HEAD:main +``` + +The container starts the equivalent of: + +```bash +sr-harness run \ + --save-path /data \ + --workspace-dir /data \ + --isolate-users \ + --host 0.0.0.0 \ + --port 8000 +``` + +The health endpoint is `/health`. + +## 2. Configure model credentials + +Add provider credentials under the Space's **Settings → Secrets**. Supported +secret names include: + +- `OPENROUTER_API_KEY` +- `OPENAI_API_KEY` +- `DEEPSEEK_API_KEY` +- `SILICONFLOW_API_KEY` +- `GEMINI_API_KEY` + +Never add API keys as repository files or public Space variables. + +For a public Space, avoid installing an owner-funded key unless unrestricted +public use and its cost are intentional. SRHarness lets each browser session +configure its own provider key in the WebUI, but `--isolate-users` is +cookie-based isolation rather than authentication or abuse prevention. + +## 3. Choose a storage policy + +The image writes conversations, uploaded data, settings, and run artifacts to +`/data`. + +- Without persistent storage, Space restarts can erase `/data`. +- To retain work, attach persistent storage or a writable Storage Bucket at + `/data` in the Space settings. +- Persisted workspaces can contain user-uploaded data and provider keys entered + through the WebUI. Use a private Space for sensitive work and apply an + appropriate retention policy. + +## 4. Resource expectations + +CPU Basic is enough to start the WebUI and use remote LLM providers. Symbolic +regression workloads can be CPU- and memory-intensive, so larger hardware may +be needed for concurrent users, large datasets, or expensive local fitting +tools. Optional GPU-backed tools require a GPU Space and their corresponding +model assets. + +## Local smoke test + +```bash +docker build -t sr-harness-space . +docker run --rm -p 8000:8000 sr-harness-space +curl --fail http://127.0.0.1:8000/health +``` diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..2884e1cd0ef364ac6d6383c8943a93cf23352980 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,108 @@ +[build-system] +requires = ["setuptools>=61.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "sr-harness" +version = "1.0.6" +description = "SRHarness: a harness for agentic symbolic regression" +readme = "README.md" +requires-python = ">=3.12" +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Science/Research", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.12", + "Topic :: Scientific/Engineering :: Artificial Intelligence", +] +license = "MIT" +authors = [ + {name = "YuMeow", email = "yuzh19@tsinghua.org.cn"} +] +dependencies = [ + "numpy>=1.24.0", + "scipy>=1.10.0", + "scikit-learn>=1.3.0", + "sympy>=1.12", + "pandas>=2.0.0", + "openpyxl>=3.1.0", + "joblib>=1.3.0", + "docstring-parser>=0.16", + "pyyaml>=6.0", + "rich>=13.0.0", + "matplotlib>=3.7.0", + "openai>=1.0.0", + "google-genai>=1.0.0", + "requests>=2.28.0", + "python-dotenv>=1.0.0", + "h5py>=3.16.0", + "datasets>=4.8.0", + "textual>=1.0.0", + "prompt_toolkit>=3.0.0", + "fastapi>=0.115.0", + "uvicorn>=0.30.0", +] + +[project.scripts] +sr-harness = "sr_harness.cli:entrypoint" + +[project.optional-dependencies] +nn = [ + "torch>=2.0.0", + "torch-geometric>=2.4.0", +] +tools = [ + "pysr>=1.5.10", + "pysindy>=2.1.0", + "pypdf>=5.0.0", +] +dev = [ + "pytest>=8.0.0", + "pytest-cov>=4.0.0", + "ipynbname>=2025.8.0.0", + "yumeow_plot>=0.1.2", + "mkdocs>=1.6", + "mkdocs-material>=9.5", + "mkdocstrings[python]>=0.27", + "mkdocs-static-i18n>=1.3", + "ruff>=0.8", +] +all = [ + "sr-harness[nn,tools,dev]", +] + +[tool.setuptools.packages.find] +where = ["src"] +include = ["sr_harness*", "sr_harness_engine*"] + +[tool.setuptools.package-data] +sr_harness = [ + "*.md", + "*.yaml", + "**/*.md", + "**/*.yaml", + "web/static/*.html", + "web/static/*.svg", + "web/static/brands/*.svg", + "web/static/brands/*.png", +] +sr_harness_engine = ["README.zh.md"] + +[tool.pytest.ini_options] +minversion = "7.0" +testpaths = ["tests"] +python_files = "test_*.py" +python_classes = "Test*" +python_functions = "test_*" +markers = [ + "slow: marks tests as slow (integration tests)", + "paid: marks tests as paid API calls (requires credits)", +] +addopts = "--quiet -m 'not slow and not paid'" + +[tool.ruff] +line-length = 100 +target-version = "py312" + +[tool.ruff.lint] +select = ["E", "F", "W"] diff --git a/src/sr_harness/README.md b/src/sr_harness/README.md new file mode 100644 index 0000000000000000000000000000000000000000..369c91f9d1f546c70858c5db2767b2c7fe5d706d --- /dev/null +++ b/src/sr_harness/README.md @@ -0,0 +1,109 @@ +# SRHarness 框架说明 + +> SRHarness 的长篇使用文档和 API Reference:[`docs/index.md`](../../docs/index.md) + +## SRAgent 整体架构 + +SRAgent 是一个基于 LLM 的符号回归 Agent。其核心是一个 **"请求 LLM → 解析工具调用 → 调用工具 → 格式化消息"** 的循环,循环的 pipeline 由四个参数控制: + +``` +for R in 1..max_restart_loop: # best-solution restart 次数 + for C in 1..global_width: # 独立对话分支数量 + for L in 1..max_refinement_depth: # 每个分支的迭代轮数 + for K in 1..local_sample_size: # 每轮 LLM 重复采样次数 + ... (单次迭代) +``` + +- **R (Restart)**:外层重启循环。每轮重启会用历史最优结果构建新的初始 prompt,引导 LLM 在已有成果上继续搜索。 +- **C (Conversation branch)**:独立对话分支,每个分支从相同的初始 prompt 出发独立探索。 +- **L (Refinement step)**:单个分支内的对话迭代,每轮包含一次完整的 prompt 构建、LLM 请求、工具调用、buffer 更新。 +- **K (Local sample)**:单次 LLM 请求的重复采样次数,产生多个候选响应,产生最佳结果的响应会被追加到 buffer 中,其余结果中不涉及公式评估的工具调用结果也会被追加到 buffer 中以供后续参考。 + +## SRAgent 核心组件 + +`Agent` 抽象基类负责 API、Parser、共享工具上下文和工具执行机制。 +`DataPreparationAgent` 基于它维护独立、可持续的资料整理对话;`SRAgent` 基于它维护 +R-C-L-K 符号回归搜索,`SRAgentInteractive` 则在同一个搜索循环上增加人工控制和事件。 +这些 Agent 可以共享一个 `AgentContext`,但不会混用各自的对话 Buffer。 + +`AgentContext`:内存中的权威研究上下文。它保存完整结构化数据、目标和自变量、变量 +描述、来源、工作区、当前训练/验证划分以及单调递增的数据版本。工具继续通过 Mapping +接口读取上下文。数据准备 Agent 只在工作区生成或验证 `context.data/`;`InteractiveSession` 在受控边界加载新版本。运行中的交互式 +SRAgent 只在安全迭代边界刷新划分并把变量变化写入原有对话。 + +SRAgent 在运行时组织以下核心组件: + +`tool_box: BaseParser`:同时持有可执行工具实例,并负责工具描述与工具调用解析。 +- `tool_box.tools` 是 `List[BaseTool]`;每个工具接收调用参数,返回一个 `ToolCallResult`。 +- 工具的详细开发指南见 [`tools/README.md`](tools/README.md)。 +- 工具的调用流程如下: + 1. 初始化 SRAgent 时,工具被实例化并拿到运行时上下文(数据、目标变量等)。 + 2. LLM 产生工具调用(名称 + 参数) + 3. Agent 通过 `tool_box[name]` 查找对应工具实例 + 4. 调用 `tool(**params)`,返回 `ToolCallResult`(包含 `ok`、`result`、`result_str`、`meta_data`) + +`api: BaseAPI`:LLM API 实例,负责与 LLM 服务交互。 +- 调用方式如下: + ```python + llm_result = self.api(messages, n=local_sample_size) + ``` +- `messages` 是对话消息列表,格式为 `[{'role': 'system', 'content': ...}, {'role': 'user', 'content': ...}, ...]`。 +- `llm_result` 是一次完整调用的 `APICallSummary`,迭代时产生零到 `n` 个 `APICallSample`: + ```python + for sample in llm_result: + content = sample.content + tool_calls = sample.tool_calls + message = sample.message + # content: LLM 响应中的文字内容 + # tool_calls: 从响应中解析出的工具调用列表 (List[ToolCall]) + # - 文本解析模式 (text/json): 从 content 中解析 + # - OpenAI 模式: 从 message 的 tool_calls 字段直接提取 + # message: 可直接追加到 messages 中以延续对话的消息字典 + ``` +- 迭代完成后,`llm_result` 中保留用量统计: + ```python + llm_result.token_usage + llm_result.money_usage + llm_result.ok + llm_result.error + ``` + +## SRAgent 单次迭代流程 + +每一轮 (L) 的执行步骤如下: + +1. **构建 Prompt**:根据当前 buffer(对话历史)构建 messages。 +2. **请求 LLM**:调用 `api(messages)`,得到 K 个候选响应。 +3. **执行工具**:解析每个响应中的 tool_calls,查找并调用对应工具,得到结果列表。 +4. **记录搜索节点**:将当前 Prompt、响应、工具结果、父节点关系和用量写入 `SearchRunState`。 +5. **收集候选公式**:验证 `is_candidate=True` 的结果,并按配置的排名指标更新候选集合。 +6. **更新 Buffer**:选择产生最优候选的分支,将其 message 和工具结果追加到 buffer;其它分支中不涉及公式评估的工具结果也会追加,避免丢失有用信息。 +7. **日志与终止检查**:打印当前最优结果、工具调用统计和 token/费用用量,并判断是否结束搜索。 + +## 目录结构 + +``` +src/sr_harness/ +├── agents/ +│ ├── agent.py # Agent 抽象基类与共享工具执行机制 +│ ├── data_preparation_agent.py # 持久化的数据准备 Agent +│ ├── sr_agent.py # SRAgent 主类,包含 run() 主循环和各个步骤方法 +│ └── sr_agent_interactive.py # 交互式 SRAgent +├── api/ # BaseAPI 与各 Provider API +│ ├── base_api.py +│ └── *_api.py # OpenAI、DeepSeek、Gemini 等实现 +├── core/ # APICallSample、APICallSummary、ToolCall 和搜索状态等核心结构 +│ ├── api.py +│ ├── context.py # AgentContext 共享研究上下文 +│ ├── search.py +│ └── tool.py +├── interaction/ # 终端与 Web 交互管理器 +├── runtime/ # 模型路由与交互控制器 +├── parser/ # 工具调用解析器 +│ ├── base_parser.py # BaseParser 基类 +│ ├── *_parser.py # 具体解析器实现 (TextParser, JSONParser, ...) +├── tools/ # BaseTool 与具体科学工具 +├── skills/ # 运行时技能管理 +├── web/ # Web 服务与会话适配 +└── utils/ # 通用工具函数 +``` diff --git a/src/sr_harness/__init__.py b/src/sr_harness/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1bf2201f43b881d2a2199371b00b31f83aa73f27 --- /dev/null +++ b/src/sr_harness/__init__.py @@ -0,0 +1,31 @@ +from .agents.agent import Agent +from .agents.data_preparation_agent import DataPreparationAgent +from .agents.evaluator_construction_agent import EvaluatorConstructionAgent +from .agents.sr_agent import SRAgent +from .agents.sr_agent_interactive import SRAgentInteractive +from .core import AgentContext, ToolCall +from .evaluator import DefaultEvaluator, DelayRolloutEvaluator, GraphEvaluator +from .runtime import InteractionManager, SRInteractionManager +from . import api +from . import tools +from . import utils +from . import parser + +__all__ = [ + "Agent", + "AgentContext", + "DataPreparationAgent", + "DefaultEvaluator", + "DelayRolloutEvaluator", + "EvaluatorConstructionAgent", + "GraphEvaluator", + "InteractionManager", + "SRAgent", + "SRAgentInteractive", + "SRInteractionManager", + "ToolCall", + "api", + "parser", + "tools", + "utils", +] diff --git a/src/sr_harness/_vendor/README.zh.md b/src/sr_harness/_vendor/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..0f6f651311e30666767c8c23eef12f3b068810ed --- /dev/null +++ b/src/sr_harness/_vendor/README.zh.md @@ -0,0 +1,13 @@ +本目录用于存放被 `sr_harness` 私有化的第三方源码。 + +具体而言,sr_harness 需要利用第三方的代码和/或工具,尽管绝大多数工具可以通过 `pip install` 等方式安装,某些代码可能: +1. 不存在合理的包结构、无法通过常规方式安装; +2. 需要经过适当修改或包装以适应 SRHarness 的调用; +我们将这类代码作为 `sr_harness` 的内部实现细节,安装到这一目录中。 + +这一目录中的依赖应使用 `sr_harness._vendor` 作为唯一导入入口,例如: +```python +import sr_harness._vendor.vendor_package +``` +对于可以安装的第三方库,优先使用正常依赖声明和/或 `pip install`,不要将它放入这一目录。 +不要让同一份源码同时支持 `import vendor_package` 和 `import sr_harness._vendor.vendor_package` 两种入口,否则 Python 会把它们加载成两套模块对象,可能导致 `isinstance`、类身份比较、注册表和缓存失效。 diff --git a/src/sr_harness/_vendor/__init__.py b/src/sr_harness/_vendor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/sr_harness/_vendor/llmsr_bench/__init__.py b/src/sr_harness/_vendor/llmsr_bench/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..66c2d3faadfcd05116b1cf86c6471a17d46b5771 --- /dev/null +++ b/src/sr_harness/_vendor/llmsr_bench/__init__.py @@ -0,0 +1 @@ +from .core import SEDTask, SRResult, Problem diff --git a/src/sr_harness/_vendor/llmsr_bench/algorithms/__init__.py b/src/sr_harness/_vendor/llmsr_bench/algorithms/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ebb0418dd281b111362cd7cf19325cf7534cd20c --- /dev/null +++ b/src/sr_harness/_vendor/llmsr_bench/algorithms/__init__.py @@ -0,0 +1,32 @@ +""" +符号回归算法集合 +""" + +import importlib +from pathlib import Path + +# 算法目录 +ALGORITHMS_DIR = Path(__file__).parent + +def get_algorithm(name: str): + """获取指定算法的 run 函数""" + module = importlib.import_module(f".{name}", __name__) + return getattr(module, "run") + + +def get_update_parser(name: str): + """获取指定算法的 update_parser 函数""" + module = importlib.import_module(f".{name}", __name__) + return getattr(module, "update_parser", None) + + +def list_algorithms(): + """列出所有可用的算法""" + algorithms = [] + for p in ALGORITHMS_DIR.glob("*.py"): + if p.stem != "__init__": + algorithms.append(p.stem) + for p in ALGORITHMS_DIR.iterdir(): + if p.is_dir() and (p / "__init__.py").exists() and not p.name.startswith("__"): + algorithms.append(p.name) + return sorted(algorithms) diff --git a/src/sr_harness/_vendor/llmsr_bench/algorithms/codex/__init__.py b/src/sr_harness/_vendor/llmsr_bench/algorithms/codex/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a1decc64bb7b23d53449773639d32df3a51b1ce9 --- /dev/null +++ b/src/sr_harness/_vendor/llmsr_bench/algorithms/codex/__init__.py @@ -0,0 +1,747 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""Codex CLI coding-agent algorithm for llmsr_bench.""" +from __future__ import annotations +import os +import re +import sys +import time +import signal +import json +import shlex +import shutil +import logging +import argparse +import selectors +import subprocess +import sr_harness_engine as engine +import numpy as np +from typing import Any +from pathlib import Path +from datetime import datetime +from sr_harness.tools import BaseTool +from sr_harness.utils import tag2ansi +from ...core import SEDTask, SRResult + +_PACKAGE_DIR = Path(__file__).resolve().parent +_REPO_ROOT = Path(__file__).resolve().parents[6] +_README_TEMPLATE_PATH = _PACKAGE_DIR / "readme_template.md" +_CALL_TOOL_TEMPLATE_PATH = _PACKAGE_DIR / "call_tool_template.py" + +# ChatGPT/Codex credit rates published by OpenAI, in credits per 1M tokens. +# Source (checked 2026-09-22): https://learn.chatgpt.com/docs/pricing +_CREDIT_RATES_PER_MILLION = { + "gpt-5.5": {"input": 125.0, "cached_input": 12.5, "output": 750.0}, +} + +os.environ.setdefault("HF_HOME", "/tmp/sr_agent_hf_home") +os.environ.setdefault("HF_DATASETS_CACHE", "/tmp/sr_agent_hf_datasets") +os.environ.setdefault("MPLCONFIGDIR", "/tmp/sr_agent_mplconfig") +for _cache_dir in ("HF_HOME", "HF_DATASETS_CACHE", "MPLCONFIGDIR"): + Path(os.environ[_cache_dir]).mkdir(parents=True, exist_ok=True) + +__all__ = ["update_parser", "run"] +_logger = logging.getLogger(f"sr_harness.{__name__}") + + +def update_parser(parser: argparse.ArgumentParser) -> argparse.ArgumentParser: + parser.add_argument("--codex_cmd", default=os.environ.get("CODEX_CMD"), help=( + "Full Codex command prefix, e.g. 'npx --yes @openai/codex@latest'. Overrides --codex_bin." + )) + parser.add_argument("--codex_bin", default=os.environ.get("CODEX_BIN", "codex"), help=( + "Codex executable used when --codex_cmd is unset." + )) + parser.add_argument("--codex_model", default=os.environ.get("CODEX_MODEL", "gpt-5.5"), help=( + "Model passed to Codex CLI." + )) + parser.add_argument("--codex_timeout_seconds", default=int(os.environ.get("CODEX_TIMEOUT_SECONDS", "900")), type=int, help=( + "Per-problem Codex wall-clock timeout." + )) + parser.add_argument("--codex_progress_interval", default=int(os.environ.get("CODEX_PROGRESS_INTERVAL", "30")), type=int, help=( + "Seconds between Codex progress log lines. Use 0 to disable." + )) + parser.add_argument("--codex_echo_events", action=argparse.BooleanOptionalAction, default=True, help=( + "Print raw Codex JSONL events while saving them." + )) + parser.add_argument("--codex_sandbox", default=os.environ.get("CODEX_SANDBOX", "workspace-write"), help=( + "Sandbox mode passed to Codex CLI." + )) + parser.add_argument("--codex_approval_policy", default=os.environ.get("CODEX_APPROVAL_POLICY"), help=( + "Optional Codex config override for approval_policy." + )) + parser.add_argument("--codex_extra_args", default=os.environ.get("CODEX_EXTRA_ARGS", ""), type=str, help=( + "Extra arguments inserted before the prompt." + )) + parser.add_argument("--codex_overwrite", action=argparse.BooleanOptionalAction, default=False, help=( + "Overwrite per-problem Codex public files and result JSON." + )) + parser.add_argument("--codex_finalize_timeout_seconds", default=int(os.environ.get("CODEX_FINALIZE_TIMEOUT_SECONDS", "60")), type=int, help=( + "Wall-clock timeout for the finalization pass (second Codex call). 60s only allows a fast memory-based submission; reading logs / re-analysis times out and counts as missing." + )) + parser.add_argument("--codex_finalize", action=argparse.BooleanOptionalAction, default=True, help=( + "Run a second Codex call to extract the best formula from the main pass's exploration log when result.json was not completed." + )) + parser.add_argument("--tools", default=BaseTool.all_registered_names, type=str, nargs='+', help=( + "Optional list of tools to use. Default is all built-in tools." + )) + parser.add_argument("--ban_tools", default=[], type=str, nargs='+', help=( + "Optional list of tools to exclude. Default is no excluded tools." + )) + parser.add_argument("--llm_provider", default="openrouter", help=( + "LLM provider used for the symbolic-accuracy equivalence judge." + )) + parser.add_argument("--llm_model", default="deepseek/deepseek-v4-flash", help=( + "LLM model used for the symbolic-accuracy equivalence judge." + )) + return parser + + +def run(args: argparse.Namespace, task: SEDTask) -> SRResult: + # 初始化 + artifacts = export_task(args, task) + command = build_codex_command(args, artifacts) + command_for_log = " ".join(shlex.quote(part) for part in command[:-1]) + " " + _logger.note(tag2ansi( + f"[blue bold][CODEX RUN][reset] [green]{artifacts['problem_name']}[reset]\n" + f" [blue]dir:[reset] [green]{artifacts['problem_dir']}[reset]\n" + f" [blue]problem:[reset] [green]{artifacts['problem_path']}[reset]\n" + f" [blue]context:[reset] [green]{artifacts['context_path']}[reset]\n" + f" [blue]result:[reset] [green]{artifacts['result_path']}[reset]\n" + f" [blue]events:[reset] [green]{artifacts['event_path']}[reset]\n" + f" [blue]cmd:[reset] [green]{command_for_log}[reset]" + )) + + # 运行 + status = run_codex_command(command, artifacts, args) + + # 二阶段 finalize pass + # 主 agent 未以 completed 提交有效公式时另起一个 Codex 实例,从主 pass 的探索日志中提取最佳公式并写入 result.json。 + # 例如:DeepSeek 过度思考导致超时 + result = load_result_json(artifacts["result_path"]) + main_submitted = result.get("status") == "completed" and (result.get("discovered_expression") or result.get("formula")) + if not main_submitted and args.codex_finalize: + _logger.note(tag2ansi( + f"[blue bold][CODEX FINALIZE][reset] main pass did not complete a submission " + f"(status=[blue]{result.get('status', 'unknown')}[reset]); " + f"starting finalization pass with a fresh Codex instance..." + )) + finalize_status = run_finalize_pass(args, artifacts) + _logger.note(tag2ansi( + f"[blue bold][CODEX FINALIZE][reset] finalization pass exited with status " + f"[green]{finalize_status}[reset]; result: [blue]{result_status(artifacts['result_path'])}[reset]" + )) + result = load_result_json(artifacts["result_path"]) + + # 后处理 + result = load_result_json(artifacts["result_path"]) + result['token_usage'] = latest_usage_from_codex_events(artifacts["event_path"], retries=10, retry_delay=0.2) + result['credit_usage'] = estimate_credit_usage(args.codex_model, result['token_usage']) + result['tool_call_count'] = count_jsonl(artifacts["tool_call_log_path"]) + result['end_time'] = (end_time := datetime.now()).isoformat() + result['duration_seconds'] = (end_time - artifacts["start_time"]).total_seconds() + if expression := (result.pop("discovered_expression", None) or result.pop("formula", None)): + result['discovered_expression'] = expression + elif expression := best_formula_from_tool_calls(artifacts["tool_call_log_path"]): + result['discovered_expression'] = expression + result['notes'] = (result.get('notes') or '') + "\nFallback: selected the lowest-mse formula from tool-call records." + # Persist accounting even when the run failed to produce a formula. + artifacts["result_path"].write_text(json.dumps(result, indent=2, ensure_ascii=False, allow_nan=True) + "\n", encoding="utf-8") + if not expression and status != 0: + raise RuntimeError(f"Codex exited with status {status} and did not write discovered_expression. See {artifacts['event_path']}") + elif not expression: + raise ValueError(f"Codex did not discover an expression. See {artifacts['event_path']} for details.") + + # 返回 + f = engine.parse(expression.strip().replace("^", "**").replace("np.", "").replace("math.", "")) + target = task.symbols[0] + features = task.symbols[1:] + constants = {} + for var in f.iter_preorder(): + if not isinstance(var, engine.Variable) or var.name in features: + pass + elif var.name.lower() == 'pi': + constants[var.name] = np.pi + elif var.name.lower() == 'e': + constants[var.name] = np.e + else: + raise ValueError(f"Unknown variable '{var.name}' in discovered expression that is not in features. Please ensure all variables are either features or known constants like pi and e.") + + def predict(X: np.ndarray) -> np.ndarray: + pred_data = {feat: X[:, i] for i, feat in enumerate(features)} + pred_data[target] = np.zeros(len(X)) # 占位,不会被使用 + pred_data |= constants # 将常数也加入数据字典,供表达式求值使用 + return f.eval(pred_data).flatten() + + return SRResult(predict=predict, expression=expression, metadata={ + "duration_seconds": result.get("duration_seconds"), + "token_usage": result.get("token_usage"), + "credit_usage": result.get("credit_usage"), + "tool_call_count": result.get("tool_call_count"), + }) + + +def export_task(args: argparse.Namespace, task: SEDTask) -> dict[str, Path]: + target = task.symbols[0] + features = task.symbols[1:] + lines = [] + for sym, desc, prop in zip(task.symbols, task.symbol_descs, task.symbol_properties): + kind = {"O": "Output", "V": "Input Variable"}.get(prop, "Unknown") + lines.append(f"{sym} ({kind}): {desc}") + problem_description = "\n".join(lines) + start_time = datetime.now() + + # 初始化目录 + save_name = sanitize_filename(task.name) + if args.save_path is not None: + problem_dir = Path(args.save_path) / "experiments" / f"{save_name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}" + else: + problem_dir = Path("/tmp") / "sr_agent_codex" / f"{save_name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}" + problem_dir.mkdir(parents=True, exist_ok=True) + readme_path = problem_dir / "README.md" # Agent 本地操作说明 + manifest_path = problem_dir / "manifest.json" # 存储运行元数据 + problem_path = problem_dir / "problem.json" # 存储问题描述 + call_tool_path = problem_dir / "call_tool.py" # Agent 本地工具入口 + context_path = problem_dir / "context.npz" # 存储用于 call_tool 的上下文 + result_path = problem_dir / "result.json" # 存储运行结果 + final_path = problem_dir / "final_message.txt" # 记录 Codex 输出的最终消息 + event_path = problem_dir / "codex_events.jsonl" # 记录 Codex 输出的事件流 + tool_call_log_path = problem_dir / "tool_calls.jsonl" # 记录工具调用日志 + finalize_event_path = problem_dir / "codex_finalize_events.jsonl" # 记录 finalize pass 的事件流 + finalize_message_path = problem_dir / "finalize_message.txt" # 记录 finalize pass 的最终消息 + if not args.codex_overwrite and any(path.exists() for path in (context_path, problem_path, result_path)): + raise FileExistsError(f"Codex artifacts already exist in {problem_dir}. Use --codex-overwrite to regenerate them.") + + manifest_path.write_text(json.dumps({ + "equation_id": task.name, + "target": target, + "features": features, + "symbols": task.symbols, + "symbol_descs": task.symbol_descs, + "symbol_properties": task.symbol_properties, + "num_train": int(len(task.train_y)), + "problem_dir": str(problem_dir.absolute()), + "problem_path": str(problem_path.relative_to(problem_dir)), + "context_path": str(context_path.relative_to(problem_dir)), + "manifest_path": str(manifest_path.relative_to(problem_dir)), + "result_path": str(result_path.relative_to(problem_dir)), + "readme_path": str(readme_path.relative_to(problem_dir)), + "call_tool_path": str(call_tool_path.relative_to(problem_dir)), + "tool_call_log_path": str(tool_call_log_path.relative_to(problem_dir)), + "problem_description": problem_description, + }, indent=2, ensure_ascii=False, allow_nan=True), encoding="utf-8") + + problem_path.write_text(json.dumps({ + "symbols": task.symbols, + "symbol_descs": task.symbol_descs, + "symbol_properties": task.symbol_properties, + "problem_description": problem_description, + }, indent=2, ensure_ascii=False, allow_nan=True), encoding="utf-8") + + np.savez(context_path, **{ + 'data': {feature: task.train_X[:, i].astype(float) for i, feature in enumerate(features)} | {target: task.train_y.astype(float)}, + 'target': target, + }) + + readme_path.write_text(( + _README_TEMPLATE_PATH.read_text(encoding="utf-8") + .replace("", str(problem_dir.absolute())) + .replace("", str(problem_path.relative_to(problem_dir))) + .replace("", str(manifest_path.relative_to(problem_dir))) + .replace("", str(result_path.relative_to(problem_dir))) + .replace("", str(call_tool_path.relative_to(problem_dir))) + .replace("", str(context_path.relative_to(problem_dir))) + .replace("", str(readme_path.relative_to(problem_dir))) + .replace("", str(args.codex_timeout_seconds)) + ), encoding="utf-8") + + call_tool_path.write_text(( + _CALL_TOOL_TEMPLATE_PATH.read_text(encoding="utf-8") + .replace("", str(problem_dir.absolute())) + .replace("", str(context_path.relative_to(problem_dir))) + .replace("", str(tool_call_log_path.relative_to(problem_dir))) + .replace("", ','.join(sorted(set(args.tools) - set(args.ban_tools)))) + ), encoding="utf-8") + + result_path.write_text(json.dumps({ + "equation_id": task.name, + "start_time": start_time.isoformat(), + "status": "started", + "end_time": None, + "duration_seconds": None, + "tool_call_count": None, + "token_usage": None, + "discovered_expression": None, + "notes": None, + }, indent=2, ensure_ascii=False, allow_nan=True) + "\n", encoding="utf-8") + + return { + "problem_name": task.name, + "problem_dir": problem_dir, + "context_path": context_path, + "problem_path": problem_path, + "manifest_path": manifest_path, + "result_path": result_path, + "readme_path": readme_path, + "call_tool_path": call_tool_path, + "tool_call_log_path": tool_call_log_path, + "event_path": event_path, + "final_path": final_path, + "finalize_event_path": finalize_event_path, + "finalize_message_path": finalize_message_path, + "start_time": start_time, + } + + +def build_codex_command(args: argparse.Namespace, artifacts: dict[str, Path]) -> list[str]: + prefix = codex_command_prefix(args) + extra_args = shlex.split(args.codex_extra_args) + approval_args = [] + if args.codex_approval_policy: + approval_args = ["-c", f"approval_policy={json.dumps(args.codex_approval_policy)}"] + return [ + *prefix, + "exec", + "--json", + "-C", str(artifacts["problem_dir"]), + "-s", args.codex_sandbox, *approval_args, + "-m", args.codex_model, + "-o", str(artifacts["final_path"]), + *extra_args, + artifacts["readme_path"].read_text(encoding="utf-8"), + ] + + +_FINALIZE_PROMPT = """You are the finalization pass of a symbolic-regression benchmark run. A previous coding agent already explored this problem for the full time budget but never wrote a final formula to `result.json`. Your only job is to recover the best formula the previous agent found and write it to `result.json`. This is not optional: the run is judged by `result.json`, and it currently has no valid `discovered_expression`. + +The problem directory contains the previous agent's full exploration log: +- `codex_events.jsonl`: every command the previous agent ran and its output. It very likely contains candidate formulas and their evaluation scores (e.g. `R²=`, `RMSE`, `r2`, `Reformulated`, `best formula`) printed during exploration. +- `problem.json` and `manifest.json`: problem description and variable metadata (the first symbol is the target; the rest are input features). +- `context.npz`: training data. Load with `np.load('context.npz', allow_pickle=True)`; the `data` key holds a dict of feature arrays plus the target array. +- `README.md`: the original task instructions. +- `result.json`: the only file you are allowed to write. + +Follow these steps in order: +1. Immediately scan `codex_events.jsonl` and extract the best candidate formula the previous agent found, i.e. the one with the highest R² / lowest error. Search for lines containing `R²`, `RMSE`, `r2`, `formula`, or `Reformulated`. +2. If the formula is not obvious or looks wrong, refuse to submit: do not create or modify `result.json`, and exit. +3. Otherwise, write `result.json` now: + +{"discovered_expression": "", "status": "completed", "notes": ""} + +The expression must use only the feature variables listed in `manifest.json` plus `pi`/`e` constants. Do not over-search: extracting the previous agent's best formula and submitting it is far better than submitting nothing.""" + + +_RESUME_FINALIZE_PROMPT = """Your earlier exploration of this symbolic-regression problem was cut off by the time budget before you wrote a final formula to `result.json`. The run is judged by `result.json`, and it currently holds only your initial `in_progress` baseline, so the run counts as FAILED unless you submit now. + +Your task, and nothing else: look at your exploration history (your memory and `codex_events.jsonl`), identify the best formula it contains, and submit it to `result.json`. Do not run any verification, calculation, or data analysis. Do not start a new search. If you cannot identify a formula you consider credible, refuse to submit: do not create or modify `result.json`, and exit. + +Update `result.json` now: preserve its existing fields and fill `discovered_expression` and `status` ("completed"), optionally `notes`: + +{"discovered_expression": "", "status": "completed", "notes": ""} + +The expression must use only the feature variables listed in `manifest.json` plus `pi`/`e` constants. Submitting a formula is success; searching further is failure.""" + + +def get_thread_id_from_events(event_path: Path) -> str | None: + """从主 pass 事件流解析 codex 会话 thread_id(供 finalize pass 续接会话)。""" + try: + with event_path.open("r", encoding="utf-8") as f: + for line in f: + line = line.strip() + if not line or not line.startswith("{"): + continue + try: + event = json.loads(line) + except json.JSONDecodeError: + continue + if event.get("type") == "thread.started": + return event.get("thread_id") + except OSError: + return None + return None + + +def _codex_session_meta(session_id: str) -> dict[str, Any]: + """在 ~/.codex/sessions 下定位该会话的 rollout 文件,读取 session_meta 元信息。""" + codex_home = Path(os.environ.get("CODEX_HOME", str(Path.home() / ".codex"))).expanduser() + try: + for rollout in codex_home.glob(f"sessions/**/rollout-*-{session_id}.jsonl"): + with rollout.open("r", encoding="utf-8") as f: + for line in f: + line = line.strip() + if not line: + continue + try: + event = json.loads(line) + except json.JSONDecodeError: + continue + if event.get("type") == "session_meta": + return event.get("payload") or {} + except OSError: + return {} + return {} + + +def build_finalize_command(args: argparse.Namespace, artifacts: dict[str, Path], thread_id: str | None = None) -> list[str]: + prefix = codex_command_prefix(args) + approval_args = [] + if args.codex_approval_policy: + approval_args = ["-c", f"approval_policy={json.dumps(args.codex_approval_policy)}"] + if thread_id: + # resume 续接主 pass 会话,继承其记忆与判断(历史最优公式的判定与主 agent 一致)。 + # resume 不支持 -p/--profile、-s、-C:剥离 profile 参数;provider 从会话元信息 + # 恢复(找不到则依赖会话继承,sandbox/cwd 由会话自带,与主 pass 一致)。 + extra_args, skip_next = [], False + for part in shlex.split(args.codex_extra_args): + if skip_next: + skip_next = False + continue + if part in ("-p", "--profile"): + skip_next = True + continue + if part.startswith("--profile="): + continue + extra_args.append(part) + provider_args = [] + meta = _codex_session_meta(thread_id) + if meta.get("model_provider"): + provider_args = ["-c", f'model_provider="{meta["model_provider"]}"'] + return [ + *prefix, + "exec", "resume", + "--json", + "-m", args.codex_model, + *provider_args, + "-o", str(artifacts["finalize_message_path"]), + *approval_args, + *extra_args, + thread_id, + _RESUME_FINALIZE_PROMPT, + ] + extra_args = shlex.split(args.codex_extra_args) + return [ + *prefix, + "exec", + "--json", + "-C", str(artifacts["problem_dir"]), + "-s", args.codex_sandbox, *approval_args, + "-m", args.codex_model, + "-o", str(artifacts["finalize_message_path"]), + *extra_args, + _FINALIZE_PROMPT, + ] + + +def run_finalize_pass(args: argparse.Namespace, artifacts: dict[str, Path]) -> int: + thread_id = get_thread_id_from_events(artifacts["event_path"]) + if thread_id: + _logger.note(tag2ansi( + f"[blue bold][CODEX FINALIZE][reset] resuming main-pass session " + f"[green]{thread_id}[reset] to recover its best formula..." + )) + else: + _logger.note(tag2ansi( + f"[yellow bold][CODEX FINALIZE][reset] no thread.started in events; " + f"falling back to a cold-start Codex instance" + )) + command = build_finalize_command(args, artifacts, thread_id) + command_for_log = " ".join(shlex.quote(part) for part in command[:-1]) + " " + _logger.info(tag2ansi(f"[blue bold][CODEX FINALIZE][reset] {command_for_log}")) + status = run_codex_command( + command, artifacts, args, + timeout_seconds=args.codex_finalize_timeout_seconds, + event_path=artifacts["finalize_event_path"], + ) + if status != 0 and thread_id: + # resume 失败重试一次:典型原因是主 pass 超时被强杀后 codex 会话写锁残留, + # resume 因 thread-store conflict 立即退出;codex 退出时会释放锁, + # 等待片刻后重试可成功(v6 实测:失败后锁目录已清空)。 + _logger.note(tag2ansi( + f"[yellow bold][CODEX FINALIZE][reset] resume failed (status={status}); " + f"waiting 2s and retrying once..." + )) + time.sleep(2) + status = run_codex_command( + command, artifacts, args, + timeout_seconds=args.codex_finalize_timeout_seconds, + event_path=artifacts["finalize_event_path"].with_name("codex_finalize_retry_events.jsonl"), + ) + # 统计分层(学长的三分类设计):主 pass 自提交 = completed;resume 补交 = resume; + # resume 也搞不定 = missing。resume 成功时把 status 从 completed 改为 resume, + # 实验结束后扫 experiments/*/result.json 即可区分三类题。 + result_path = artifacts["result_path"] + result = load_result_json(result_path) + if status == 0 and result.get("status") == "completed" and ( + result.get("discovered_expression") or result.get("formula") + ): + result["status"] = "resume" + result_path.write_text(json.dumps(result, indent=2, ensure_ascii=False, allow_nan=True) + "\n", encoding="utf-8") + _logger.note(tag2ansi( + f"[blue bold][CODEX FINALIZE][reset] resume submitted a formula; " + f"marking result status as [green]resume[/green]." + )) + return 0 + # resume 也搞不定:把 status 标记为 missing 存进 result.json, + # 供后续统计定位与更优模型补跑。 + result["status"] = "missing" + result_path.write_text(json.dumps(result, indent=2, ensure_ascii=False, allow_nan=True) + "\n", encoding="utf-8") + _logger.note(tag2ansi( + f"[yellow bold][CODEX FINALIZE][reset] finalize failed (status={status}); " + f"marking result status as [red]missing[/red]." + )) + return 1 + + +def _kill_group(process: subprocess.Popen, sig: int) -> None: + """向 codex 进程组发送信号;进程组已消失(进程恰好自然退出)时静默忽略。""" + try: + os.killpg(process.pid, sig) + except ProcessLookupError: + pass + + +def run_codex_command(command: list[str], artifacts, args: argparse.Namespace, timeout_seconds: int | None = None, event_path: Path | None = None) -> int: + result_path = artifacts["result_path"] + tool_call_log_path = artifacts["tool_call_log_path"] + timeout_seconds = args.codex_timeout_seconds if timeout_seconds is None else timeout_seconds + event_path = artifacts["event_path"] if event_path is None else event_path + start = time.monotonic() + deadline = start + timeout_seconds + next_progress = start + args.codex_progress_interval + event_count = 0 + # 提交即止:agent 将 result.json 置为 completed 后提前结束,避免提交后继续消耗时间与 token。 + baseline_mtime = result_path.stat().st_mtime if result_path.exists() else 0.0 + + with event_path.open("w", encoding="utf-8") as event_file: + process = subprocess.Popen( + command, + cwd=_REPO_ROOT, # 这里不能改成 problem_dir, 因为 problem_dir 是相对于 _REPO_ROOT 的路径 + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + bufsize=1, + start_new_session=True, # 独立进程组:信号用 killpg 全组发送,保证到达 codex 二进制 + ) + assert process.stdout is not None + selector = selectors.DefaultSelector() + selector.register(process.stdout, selectors.EVENT_READ) + try: + while process.poll() is None: + now = time.monotonic() + if now >= deadline: + # 先 SIGINT 让 codex 优雅退出(清理会话写锁),避免强杀残留 + # thread-store 写锁导致后续 finalize resume 立即失败。 + # 必须 killpg:进程链为 npx -> codex.js(node shim) -> 二进制, + # 单发信号只打到 npx,codex.js 收不到就不会转发,优雅退出落空。 + _kill_group(process, signal.SIGINT) + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + _kill_group(process, signal.SIGTERM) + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + _kill_group(process, signal.SIGKILL) + process.wait() + event_file.write(json.dumps({"type": "bench.timeout", "timeout_seconds": timeout_seconds}, ensure_ascii=False) + "\n") + event_file.flush() + return 124 + + # 提交即止:result.json 被置为 completed 后提前结束(见上方 baseline_mtime 注释)。 + try: + if result_path.stat().st_mtime > baseline_mtime: + with result_path.open("r", encoding="utf-8") as rf: + _r = json.load(rf) + if _r.get("status") == "completed": + _logger.info(tag2ansi( + f"[green bold][CODEX DONE][reset] result.json marked completed; " + f"stopping early (elapsed={int(now - start)}s)" + )) + # 终止 codex 进程组,避免提交后孤儿进程继续消耗时间与 token。 + _kill_group(process, signal.SIGINT) + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + _kill_group(process, signal.SIGKILL) + process.wait() + return 0 + except (OSError, json.JSONDecodeError): + pass + + for key, _ in selector.select(timeout=1): + line = key.fileobj.readline() + if not line: + continue + event_file.write(line) + event_file.flush() + event_count += 1 + if args.codex_echo_events: + _logger.info(line.rstrip()) + + if args.codex_progress_interval > 0 and now >= next_progress: + elapsed = int(now - start) + tool_count = count_jsonl(tool_call_log_path) + _logger.info(tag2ansi( + "[yellow bold][CODEX WAIT][reset] " + f"elapsed={elapsed}s events={event_count} " + f"tool_calls={tool_count if tool_count is not None else 0} " + f"status=[blue]{result_status(result_path)}[reset]" + )) + next_progress = now + args.codex_progress_interval + + for line in process.stdout: + event_file.write(line) + event_file.flush() + event_count += 1 + if args.codex_echo_events: + _logger.info(line.rstrip()) + finally: + selector.close() + + return int(process.returncode or 0) + + +def latest_usage_from_codex_events( + event_path: Path, + retries: int = 0, + retry_delay: float = 0.0, +) -> dict[str, Any] | None: + + def find_usage(value: Any) -> dict[str, Any] | None: + if isinstance(value, dict): + keys = set(value) + if {"input_tokens", "output_tokens"} & keys or "total_tokens" in keys: + return value + for child in value.values(): + found = find_usage(child) + if found: + return found + elif isinstance(value, list): + for child in value: + found = find_usage(child) + if found: + return found + return None + + usage = None + if not event_path.exists(): + return None + for line in event_path.read_text(encoding="utf-8", errors="replace").splitlines(): + try: + event = json.loads(line) + except json.JSONDecodeError: + continue + if candidate := find_usage(event): + usage = candidate + if usage is not None: + return usage + # codex 0.152 的 stdout 事件流不含 token 统计(v8 实测 token_usage 恒为 None): + # 回退到 codex 会话 rollout 文件,读取最后一条 token_count 的累计用量 + # (口径含 finalize/resume 回合,与之前手动统计一致)。 + thread_id = get_thread_id_from_events(event_path) + if not thread_id: + return None + codex_home = Path(os.environ.get("CODEX_HOME", str(Path.home() / ".codex"))).expanduser() + for attempt in range(retries + 1): + try: + for rollout in codex_home.glob(f"sessions/**/rollout-*-{thread_id}.jsonl"): + for line in rollout.read_text(encoding="utf-8", errors="replace").splitlines(): + if not line.strip() or not line.strip().startswith("{"): + continue + try: + event = json.loads(line) + except json.JSONDecodeError: + continue + payload = event.get("payload") or {} + if event.get("type") == "event_msg" and payload.get("type") == "token_count": + usage = (payload.get("info") or {}).get("total_token_usage") + except OSError: + pass + if usage is not None or attempt == retries: + break + time.sleep(retry_delay) + return usage + + +def estimate_credit_usage(model: str, usage: dict[str, Any] | None) -> dict[str, Any] | None: + """Estimate Codex credits from cumulative token usage using the published rate card.""" + if not usage or model not in _CREDIT_RATES_PER_MILLION: + return None + input_tokens = int(usage.get("input_tokens") or 0) + cached_input_tokens = int(usage.get("cached_input_tokens") or 0) + output_tokens = int(usage.get("output_tokens") or 0) + uncached_input_tokens = max(0, input_tokens - cached_input_tokens) + rates = _CREDIT_RATES_PER_MILLION[model] + components = { + "uncached_input": uncached_input_tokens * rates["input"] / 1_000_000, + "cached_input": cached_input_tokens * rates["cached_input"] / 1_000_000, + "output": output_tokens * rates["output"] / 1_000_000, + } + return { + "model": model, + "estimated_credits": sum(components.values()), + "components": components, + "billable_tokens": { + "uncached_input_tokens": uncached_input_tokens, + "cached_input_tokens": cached_input_tokens, + "output_tokens": output_tokens, + }, + "rates_per_million_tokens": rates, + "rate_source": "https://learn.chatgpt.com/docs/pricing", + "rate_checked_date": "2026-09-22", + } + + +def load_result_json(path: Path) -> dict[str, Any]: + try: + return json.loads(path.read_text(encoding="utf-8")) + except Exception: + return {} + + +def result_status(path: Path) -> str: + if not (result := load_result_json(path)): + return "result JSON missing or unreadable" + else: + status = result.get("status") or "unknown" + expression = result.get("discovered_expression", "(No Expression)") + return f"[{status}] {expression}" + + +def count_jsonl(path: Path) -> int | None: + if not path.exists(): + # 文件不存在 = 没有任何工具调用记录(no-tool 模式下必然如此),计数为 0。 + return 0 + with path.open("r", encoding="utf-8", errors="replace") as f: + return sum(1 for line in f if line.strip()) + + +def best_formula_from_tool_calls(path: Path) -> str | None: + best_record = None + if not path.exists(): + return None + for line in path.read_text(encoding="utf-8", errors="replace").splitlines(): + try: + record = json.loads(line) + result = record["tool_call_result"]["result"] + formula = result["formula"] + split_results = result["data_split_results"] + split_name = "validation" if "validation" in split_results else "train" + metrics = split_results[split_name]["metrics"] + mse = float(metrics["mse"]) + except Exception: + continue + if best_record is None or mse < best_record["mse"]: + best_record = {"formula": formula, **metrics} + return best_record["formula"] if best_record else None + + +def codex_command_prefix(args: argparse.Namespace) -> list[str]: + value = args.codex_cmd or args.codex_bin + prefix = shlex.split(value) if isinstance(value, str) else list(value) + if not prefix: + raise ValueError("Codex command is empty. Set --codex_cmd or --codex_bin.") + return prefix + + +def sanitize_filename(value: str) -> str: + return re.sub(r'[ <>:"/\\|?*\x00-\x1f]', "_", value.strip())[:255] or "unnamed" diff --git a/src/sr_harness/_vendor/llmsr_bench/algorithms/codex/call_tool_template.py b/src/sr_harness/_vendor/llmsr_bench/algorithms/codex/call_tool_template.py new file mode 100644 index 0000000000000000000000000000000000000000..895b503cac35f2e189506e358ce2c0e4abc0ecd6 --- /dev/null +++ b/src/sr_harness/_vendor/llmsr_bench/algorithms/codex/call_tool_template.py @@ -0,0 +1,63 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""Problem-local tool wrapper for this Codex symbolic-regression run.""" +from __future__ import annotations +import os +import sys +import json +from pathlib import Path +from sr_harness.tools import BaseTool +from sr_harness.cli.tool import load_context, load_params, setup_parser +from sr_harness._vendor.llmsr_bench.algorithms.codex.utils import record_tool_call + + +WORK_DIR = Path("") +CONTEXT_PATH = Path("") +TOOL_CALL_LOG_PATH = Path("") +ENABLED_TOOLS = "".split(',') + +os.chdir(WORK_DIR) +os.environ.setdefault("HF_HOME", "/tmp/sr_agent_hf_home") +os.environ.setdefault("HF_DATASETS_CACHE", "/tmp/sr_agent_hf_datasets") +os.environ.setdefault("MPLCONFIGDIR", "/tmp/sr_agent_mplconfig") +for cache_dir in ("HF_HOME", "HF_DATASETS_CACHE", "MPLCONFIGDIR"): + Path(os.environ[cache_dir]).mkdir(parents=True, exist_ok=True) + + +def main(args) -> None: + if args.tool_command == "list": + for idx, metadata in enumerate(BaseTool.load_tool_list(ENABLED_TOOLS)): + name = metadata['name'] + description = '\n'.join(' ' + line for line in (metadata['description'] or "").splitlines()) + print(f"{name}\n{description}\n") + elif args.tool_command == "schema": + if not args.tool: + schema = BaseTool.to_tool_list(ENABLED_TOOLS) + print(json.dumps(schema, indent=2, ensure_ascii=False)) + elif args.tool in ENABLED_TOOLS: + tool_cls = BaseTool.create(args.tool, create_instance=False) + schema = tool_cls.to_dict() + print(json.dumps(schema, indent=2, ensure_ascii=False)) + else: + print(f"Tool {args.tool!r} is not in the enabled tools list: {ENABLED_TOOLS}", file=sys.stderr) + elif args.tool_command == "call": + if args.tool not in ENABLED_TOOLS: + print(f"Tool {args.tool!r} is not in the enabled tools list: {ENABLED_TOOLS}", file=sys.stderr) + raise SystemExit(1) + else: + tool_cls = BaseTool.create(args.tool, create_instance=False) + context = load_context(args.context, target=args.target) + params = load_params(args.params, args.params_file) + result = tool_cls(**context)(**params) + record_tool_call(TOOL_CALL_LOG_PATH, args, params, result) + print(result.result_str) + if not result.ok: + raise SystemExit(1) + else: + parser.error(f"Unknown tool command: {args.tool_command}") + + +if __name__ == "__main__": + parser = setup_parser() + args = parser.parse_args() + args.context = CONTEXT_PATH + main(args) diff --git a/src/sr_harness/_vendor/llmsr_bench/algorithms/codex/readme_template.md b/src/sr_harness/_vendor/llmsr_bench/algorithms/codex/readme_template.md new file mode 100644 index 0000000000000000000000000000000000000000..f76525a4505e2f8a89e8b73a9b767fb67b1c62e3 --- /dev/null +++ b/src/sr_harness/_vendor/llmsr_bench/algorithms/codex/readme_template.md @@ -0,0 +1,83 @@ +# Codex Symbolic Regression Problem + +You are solving a symbolic-regression problem as a coding agent. + +The benchmark runner has created public files for this problem and set your +working directory to the problem directory. Use only the files and tools listed +below. + +Your current working directory: + +## Hard Limits + +- Finish within seconds. +- Do not read, write or create files outside this directory, except temporary analysis scripts in `/tmp`. +- Do not modify files other than . +- Do not start or delegate to sub-agents. This benchmark measures the current coding agent as a single solver. + +## Submission Protocol (MANDATORY — applies in ALL cases, even if tools are unavailable) + +Your run is judged by the content of . If it does not contain a valid +`discovered_expression` when the run ends, the run counts as FAILED. Follow these steps in order: + +1. Immediately after reading this README — before any data analysis — write an initial baseline to , e.g. a simple linear model: `{"discovered_expression": "1.0*x1 + 1.0*x2 + 1.0*x3 + 1.0*x4 + 0.0", "status": "in_progress"}`. Coefficients do not need to be fitted yet; the file just needs a valid entry. This is not optional. + +2. After every 5 analysis commands, update with your current best formula, even if it did not improve. Never run more than 2 analysis commands without updating it. + +3. Whenever a new formula beats the one currently in , update it immediately before doing anything else.s + +4. When you are confident a formula is final, set `"status": "completed"`. + +## Public Files + +The problem directory contains: + +- ``: Public problem description and variable metadata. +- ``: Paths and metadata for this run. +- ``: Write your expression here (see Submission Protocol above). +- ``: Local tool wrapper for this problem. +- ``: Tool context, relied by ``. +- ``: Readme file saving this information + +## Expected Workflow + +1. Inspect the Problem file ``. It contains: + +- `problem_description`: natural-language variable information. +- `symbols`: variable names. The first symbol is the target; the rest are input features. +- `symbol_descs`, `symbol_properties`: variable descriptions and roles. +- `context_path`, `result_path`: paths generated by the runner. + +2. Inspect available tools through the `` wrapper: + +```bash +python list +python schema statistics_analysis +python schema evaluate_formula +python schema ... +``` + +3. Use the `` wrapper to call tool for analysing or searching. + +```bash +python call statistics_analysis --params '{"variables": ["x1", "x2"]}' +python call evaluate_formula --params '{"f": "sin(x1) + x2", "fit": false}' +``` + +4. Call `evaluate_formula` for every serious candidate before final submission. + +5. Also call at least one structure-discovery tool, such as `polynomial_fit`, `call_sindy`, or `call_pysr`, unless the relationship is already obvious from the required tool outputs. + +6. Custom Python analysis is allowed under your current workspace or `/tmp`, but it is supplementary. + +7. During ablation experiments, some tools may be removed. Don't be surprised if you find that some of the tools mentioned above are not provided by `call_tool.py`. + +8. When you have a final formula, update ``. Preserve the existing fields and fill at least: + +```json +{ + "discovered_expression": "sin(x1) + x2", + "status": "in_progress", // or "completed" + "notes": "short optional notes" +} +``` diff --git a/src/sr_harness/_vendor/llmsr_bench/algorithms/codex/utils.py b/src/sr_harness/_vendor/llmsr_bench/algorithms/codex/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1e3635da836a1f7fd88bf0f29604f5406cd47a03 --- /dev/null +++ b/src/sr_harness/_vendor/llmsr_bench/algorithms/codex/utils.py @@ -0,0 +1,41 @@ +import sys +import json +import numpy as np +from typing import Any +from pathlib import Path +from datetime import datetime, timezone +from sr_harness.tools import ToolCallResult + + +def json_default(value: Any) -> Any: + if isinstance(value, np.ndarray): + return value.tolist() + if isinstance(value, np.generic): + return value.item() + if isinstance(value, Path): + return str(value) + if isinstance(value, set): + return sorted(value) + raise TypeError(f"Object of type {type(value).__name__} is not JSON serializable") + + +def record_tool_call(save_path, args, params: dict[str, Any], result: ToolCallResult) -> None: + try: + record = { + "timestamp": datetime.now(timezone.utc).isoformat(), + "tool": args.tool, + "context_path": str(args.context), + "params": params, + "tool_call_result": { + "ok": result.ok, + "result": result.result, + "result_str": result.result_str, + "meta_data": result.meta_data, + }, + } + record_str = json.dumps(record, ensure_ascii=False, allow_nan=True, default=json_default) + save_path.parent.mkdir(parents=True, exist_ok=True) + with save_path.open("a", encoding="utf-8") as f: + f.write(record_str + "\n") + except Exception as e: + print(f"Failed to record tool call: [{type(e).__name__}] {e}", file=sys.stderr) diff --git a/src/sr_harness/_vendor/llmsr_bench/algorithms/functionevolve.py b/src/sr_harness/_vendor/llmsr_bench/algorithms/functionevolve.py new file mode 100644 index 0000000000000000000000000000000000000000..7b74ff3341d7504e498f9020c4e29a97551b334a --- /dev/null +++ b/src/sr_harness/_vendor/llmsr_bench/algorithms/functionevolve.py @@ -0,0 +1,288 @@ +"""Run the original FunctionEvolve search in an isolated subprocess. + +Clone Phoinikas03/FunctionEvolve into baseline/repo/FunctionEvolve and install +its requirements in the selected Python environment. Example: + + sr-harness benchmark --algorithm functionevolve --datasets bio_pop_growth \ + --problem_names BPG5 --llm_model qwen/qwen3.6-27b + +The default search uses 30 steps and 20 seeds. A small integration smoke test can +set --functionevolve_max_steps 0 --functionevolve_n_seeds 3. OpenRouter reasoning +is enabled by default. Defaults follow the upstream full/Qwen preset, with a +fixed training NMSE threshold (1e-11) rather than the unavailable GT baseline. + +Only SEDTask training data and descriptions reach the upstream search. No GT +baseline, automatic GT threshold, or upstream symbolic verifier is invoked. +Artifacts are saved under save_path/functionevolve/-. +""" +from __future__ import annotations + +import argparse +from datetime import datetime +import functools +import json +import os +from pathlib import Path +import re +import signal +import subprocess +import sys +import tempfile +from typing import TYPE_CHECKING + +import numpy as np + +if TYPE_CHECKING: + from ..core import SEDTask, SRResult + +_ROOT = Path(__file__).resolve().parents[5] +_DEFAULTS = { + 'max_steps': 30, 'n_seeds': 20, 'candidate_num': 5, + 'selector_context_size': 200, 'max_params': 10, + 'eval_workers': 16, 'timeout': 120.0, 'run_timeout': 0.0, + 'max_tokens': 110000, 'max_retries': 5, 'max_mature_nodes': 50, + 'mature_train_threshold': 1e-11, 'overfit_min_depth': 10, + 'temperature': 1.0, +} + + +def update_parser(parser: argparse.ArgumentParser) -> argparse.ArgumentParser: + parser.add_argument('--llm_provider', choices=['openrouter'], default='openrouter') + parser.add_argument('--llm_model', default='qwen/qwen3.6-27b') + parser.add_argument('--functionevolve_repo', type=Path, + default=_ROOT / 'baseline/repo/FunctionEvolve') + parser.add_argument('--functionevolve_python', default=sys.executable) + parser.add_argument('--functionevolve_optimizer', default='Structure', + choices=['Structure', 'DE', 'CMA-ES', 'L-BFGS-B', 'least_squares']) + parser.add_argument('--functionevolve_reasoning', choices=['enabled', 'disabled', 'low'], + default='enabled', help='OpenRouter reasoning setting for all agents; low sets effort=low.') + parser.add_argument('--functionevolve_resume', action=argparse.BooleanOptionalAction, default=False, help=( + 'Resume the newest existing task checkpoint under save_path.' + )) + for name, default in _DEFAULTS.items(): + parser.add_argument(f'--functionevolve_{name}', type=type(default), default=default) + return parser + + +def _real_pow(base, exponent): + """Match upstream optimizer.base._real_pow_np for signed rational powers.""" + base = np.asarray(base, dtype=float) + numerator = int(round(float(exponent) * 3)) + value = np.power(np.abs(base), numerator / 3) + return np.where(base < 0, -value, value) if numerator % 2 else value + + +def _build_result(result: dict, symbols: list[str]): + import sympy as sp + from ..core import SRResult + + if not result.get('expression') or not np.isfinite(result.get('train_nmse', np.inf)): + raise RuntimeError('FunctionEvolve returned no finite fitted candidate.') + names = [f'x{i + 1}' for i in range(len(symbols) - 1)] + # Benchmark inputs are real-valued. The upstream simplifier may emit + # re(x1) when symbols lack assumptions; real symbols reduce that wrapper + # before returning an expression to SRHarness Engine, which has no ``re`` callable. + variables = [sp.Symbol(name, real=True) for name in names] + local = dict(zip(names, variables)) + local['_RealPow'] = sp.Function('_RealPow') + expr = sp.sympify(result['expression'], locals=local) + prediction_expr = sp.sympify(result.get('prediction_expression', str(expr)), locals=local) + unknown = (expr.free_symbols | prediction_expr.free_symbols) - set(variables) + if unknown: + raise RuntimeError(f'FunctionEvolve returned unresolved symbols: {unknown}') + func = sp.lambdify(variables, prediction_expr, modules=[{'_RealPow': _real_pow}, 'numpy']) + + def predict(X): + X = np.asarray(X, dtype=float) + if X.ndim != 2 or X.shape[1] != len(variables): + raise ValueError(f'Expected X with shape (n, {len(variables)}), got {X.shape}') + if not len(X): + return np.empty(0, dtype=float) + with np.errstate(all='ignore'): + values = np.asarray(func(*(X[:, i] for i in range(len(variables)))), dtype=float) + return np.broadcast_to(values, (len(X),)).copy() + + expr = expr.xreplace({var: sp.Symbol(name, real=True) for var, name in zip(variables, symbols[1:])}) + expression = str(expr) + # SRHarness Engine uses NumPy-style inverse-trig names and lower-case abs/min/max. + for source, target in {'asin': 'arcsin', 'acos': 'arccos', 'atan': 'arctan', + 'Abs': 'abs', 'Min': 'min', 'Max': 'max'}.items(): + expression = re.sub(rf'\b{source}(?=\()', target, expression) + return SRResult(predict=predict, expression=expression) + + +def run(args: argparse.Namespace, task: SEDTask) -> SRResult: + from dotenv import dotenv_values + + X = np.asarray(task.train_X, dtype=float) + y = np.asarray(task.train_y, dtype=float).reshape(-1) + if X.ndim != 2 or len(X) != len(y) or not len(y): + raise ValueError('FunctionEvolve requires a nonempty training matrix and matching targets.') + if len(task.symbols) != X.shape[1] + 1 or not np.isfinite(X).all() or not np.isfinite(y).all(): + raise ValueError('Training symbols must match columns and training data must be finite.') + repo = Path(getattr(args, 'functionevolve_repo', _ROOT / 'baseline/repo/FunctionEvolve')).resolve() + if not (repo / 'src/search.py').is_file(): + raise FileNotFoundError(f'Clone https://github.com/Phoinikas03/FunctionEvolve into {repo}') + env = os.environ.copy() + # The project .env key takes precedence over shell startup configuration. + key = dotenv_values(_ROOT / '.env').get('OPENROUTER_API_KEY') or env.get('OPENROUTER_API_KEY') + if not key: + raise ValueError('OPENROUTER_API_KEY is missing from the project .env/environment.') + env['OPENROUTER_API_KEY'] = key + for name in ('OPENBLAS_NUM_THREADS', 'OMP_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): + env[name] = '1' + env.setdefault('LLM_REQUEST_TIMEOUT', '300') + config = {name: getattr(args, f'functionevolve_{name}', default) + for name, default in _DEFAULTS.items()} + for name in ('n_seeds', 'candidate_num', 'eval_workers', 'max_params', 'max_tokens', + 'max_retries', 'max_mature_nodes', 'selector_context_size', 'timeout'): + if config[name] <= 0: + raise ValueError(f'functionevolve_{name} must be positive.') + if config['max_steps'] < 0 or config['mature_train_threshold'] < 0 or config['run_timeout'] < 0: + raise ValueError('Search steps and maturity threshold must be nonnegative.') + config.update(model=getattr(args, 'llm_model', 'qwen/qwen3.6-27b'), + optimizer=getattr(args, 'functionevolve_optimizer', 'Structure'), + reasoning=getattr(args, 'functionevolve_reasoning', 'enabled'), + resume=getattr(args, 'functionevolve_resume', False), + seed=getattr(args, 'seed', -1), verbose=getattr(args, 'verbose', False)) + if config['seed'] >= 0: + env['PYTHONHASHSEED'] = str(config['seed']) + root = Path(getattr(args, 'save_path', None) or _ROOT / 'logs/functionevolve') / 'functionevolve' + root.mkdir(parents=True, exist_ok=True) + prefix = re.sub(r'[^\w.-]', '_', task.name)[:80] + '-' + existing = sorted(root.glob(prefix + '*'), key=lambda path: path.stat().st_mtime, reverse=True) + resumable = next((path for path in existing if (path / 'checkpoint.json').is_file()), None) + work = resumable.resolve() if config['resume'] and resumable else Path( + tempfile.mkdtemp(prefix=prefix, dir=root)).resolve() + np.savez(work / 'train.npz', X=X, y=y) + (work / 'request.json').write_text(json.dumps(dict(config=config, name=task.name, + symbols=list(task.symbols), descriptions=list(task.symbol_descs), + properties=list(task.symbol_properties)), indent=2), encoding='utf-8') + worker_code = ( + "import runpy,sys; from pathlib import Path; " + "ns=runpy.run_path(sys.argv[1]); " + "ns['_worker'](Path(sys.argv[2]), Path(sys.argv[3]))" + ) + cmd = [str(getattr(args, 'functionevolve_python', sys.executable)), '-c', worker_code, + str(Path(__file__).resolve()), str(repo), str(work)] + log_path = work / 'worker.log' + with log_path.open('w', encoding='utf-8') as log: + process = subprocess.Popen(cmd, cwd=repo, env=env, stdout=log, + stderr=subprocess.STDOUT, start_new_session=True) + try: + returncode = process.wait(timeout=config['run_timeout'] or None) + except subprocess.TimeoutExpired as exc: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + raise RuntimeError(f'FunctionEvolve exceeded its run timeout. See {log_path}') from exc + except BaseException: + if process.poll() is None: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + raise + if returncode: + raise RuntimeError(f'FunctionEvolve exited with status {returncode}. See {log_path}') + result = json.loads((work / 'result.json').read_text(encoding='utf-8')) + return _build_result(result, list(task.symbols)) + + +def _worker(repo: Path, work: Path): + # This script runs outside sr_harness imports; upstream owns the generic src namespace. + sys.path.insert(0, str(repo)) + from src.dataset import SRDataset + from src.evaluator import Evaluator + from src.evolution_tree import EvolutionTree + from src.generator import create_generator + from src.selector import create_selector + from src.mutator import LLMMutator + from src.llm_client import build_openai_client, LLMUsageLogger + from src.search import TreeSearch + from src.checkpoint import load_checkpoint + from src.optimizer.base import parse_expr, detect_rational_constrained, make_safe_expr + import random + import sympy as sp + + request = json.loads((work / 'request.json').read_text(encoding='utf-8')) + os.environ['FUNCTIONEVOLVE_API_AUDIT'] = str(work / 'api_calls.jsonl') + cfg = request['config'] + if cfg['seed'] >= 0: + random.seed(cfg['seed']) + np.random.seed(cfg['seed']) + with np.load(work / 'train.npz') as data: + X, y = data['X'], data['y'] + names = [f'x{i + 1}' for i in range(X.shape[1])] + # Canonical names avoid collisions with SymPy functions and parameter names. + ds = SRDataset.from_arrays(X, y, symbols=['y'] + names, + symbol_descs=request['descriptions'], equation_name=request['name']) + ds.symbol_properties = request['properties'] + usage = LLMUsageLogger(str(work / 'usage.csv')) + llm = dict(model=cfg['model'], base_url='https://openrouter.ai/api/v1', + api_key=os.environ['OPENROUTER_API_KEY'], max_tokens=cfg['max_tokens'], + max_retries=cfg['max_retries'], usage_logger=usage, + temperature=cfg['temperature']) + search = None + try: + if cfg.get('resume') and (work / 'search.txt').is_file(): + stamp = datetime.now().strftime('%Y%m%d_%H%M%S') + for name in ('search.txt', 'diagnostics.log'): + source = work / name + if source.is_file(): + source.replace(work / f'{source.stem}.pre_resume_{stamp}{source.suffix}') + generator = create_generator(**llm) + selector = create_selector(**llm) + mutator = LLMMutator(api_client=build_openai_client(llm['model'], llm['base_url'], + api_key=llm['api_key']), model=llm['model'], max_tokens=cfg['max_tokens'], + max_retries=cfg['max_retries'], usage_logger=usage, temperature=cfg['temperature']) + reasoning = ({'effort': 'low'} if cfg['reasoning'] == 'low' + else {'enabled': cfg['reasoning'] == 'enabled'}) + for agent in (generator, selector, mutator): + agent.api.chat.completions.create = functools.partial(agent.api.chat.completions.create, + extra_body={'reasoning': reasoning, + 'usage': {'include': True}}) + # The upstream budget is total tokens. OpenRouter caps completion tokens. + original = agent.api.chat.completions.create + def capped_create(_original=original, **kwargs): + if kwargs.get('max_tokens') is not None: + kwargs['max_tokens'] = min(kwargs['max_tokens'], 65536) + return _original(**kwargs) + agent.api.chat.completions.create = capped_create + search = TreeSearch(dataset=ds, + evaluator=Evaluator(feature_names=names, X_train=X, y_train=y, + optimizer=cfg['optimizer'], timeout=cfg['timeout']), + tree=EvolutionTree(), generator=generator, selector=selector, llm_mutator=mutator, + max_steps=cfg['max_steps'], n_seeds=cfg['n_seeds'], candidate_num=cfg['candidate_num'], + selector_context_size=cfg['selector_context_size'], max_params=cfg['max_params'], + n_parent_workers=cfg['candidate_num'], n_eval_workers=cfg['eval_workers'], + timeout=cfg['timeout'], max_mature_nodes=cfg['max_mature_nodes'], + mature_train_threshold=cfg['mature_train_threshold'], mature_anneal_budget=0, + overfit_min_depth=cfg['overfit_min_depth'], log_path=str(work / 'search.txt'), verbose=cfg['verbose'], + checkpoint_path=str(work / 'checkpoint.json'), + diagnostic_log_path=str(work / 'diagnostics.log')) + if cfg.get('resume') and (work / 'checkpoint.json').is_file(): + search.load_checkpoint_state(load_checkpoint(work / 'checkpoint.json')) + search.initialize_seeds() + search.run() + result = search.get_best_result() + if not result.get('expression') or not np.isfinite(result.get('train_nmse', np.inf)): + raise RuntimeError('Search produced no finite fitted candidate.') + params = result['params'] + values = result['best_params'] + if len(params) != len(values): + raise RuntimeError('Fitted parameter count does not match the skeleton.') + expr = parse_expr(result['expression'], params, names) + safe = make_safe_expr(expr, params, detect_rational_constrained(expr, params, names, X), names) + replacements = {sp.Symbol(name): sp.Float(repr(float(value)), 17) for name, value in zip(params, values)} + result['skeleton'] = result['expression'] + result['expression'] = str(expr.subs(replacements)) + result['prediction_expression'] = str(safe.subs(replacements)) + result['model'] = cfg['model'] + result['reasoning'] = cfg['reasoning'] + result['parameter_float_hex'] = {name: float(value).hex() for name, value in zip(params, values)} + result['key_source'] = 'project .env/environment' + result['upstream_commit'] = subprocess.check_output( + ['git', '-C', str(repo), 'rev-parse', 'HEAD'], text=True).strip() + (work / 'result.json').write_text(json.dumps(result, default=str, indent=2), encoding='utf-8') + finally: + if search is not None: + search.close_log() + usage.close() diff --git a/src/sr_harness/_vendor/llmsr_bench/algorithms/linear.py b/src/sr_harness/_vendor/llmsr_bench/algorithms/linear.py new file mode 100644 index 0000000000000000000000000000000000000000..e301be6363080d5e51169b88575c87a5e6842df2 --- /dev/null +++ b/src/sr_harness/_vendor/llmsr_bench/algorithms/linear.py @@ -0,0 +1,37 @@ +""" +线性拟合符号回归方法 +""" +from __future__ import annotations + +import argparse +import numpy as np +from numpy.linalg import lstsq +from ..core import SEDTask, SRResult + + +def run(args: argparse.Namespace, task: SEDTask) -> SRResult: + """线性拟合符号回归方法 + + Args: SEDTask 包含了 SR 方法需要的所有输入信息, 可以根据需要使用其中的任意部分: + - task.name: str — 问题标识符 + - task.symbols: List[str] — 所有符号名, 第一个为输出变量 + - task.symbol_descs: List[str] — 符号的自然语言描述 + - task.symbol_properties: List[str] — 符号属性 ('O'=输出, 'V'=输入变量) + - task.train_X: np.ndarray — 训练输入, shape=(n_samples, n_input_vars) + - task.train_y: np.ndarray — 训练输出, shape=(n_samples,) + + Returns: SRResult 包含了 SR 方法的输出: + - predict: Callable[[np.ndarray], np.ndarray] — 输入 X, shape=(n, n_input_vars); 输出 y, shape=(n,) + - expression: Optional[str] — 发现的公式字符串 (可选, 用于记录) + """ + # 简单线性回归 + X_aug = np.column_stack([task.train_X, np.ones(len(task.train_X))]) + coeffs, _, _, _ = lstsq(X_aug, task.train_y, rcond=None) + + def predict(X: np.ndarray) -> np.ndarray: + X_aug = np.column_stack([X, np.ones(len(X))]) + return X_aug @ coeffs + + expr_parts = " + ".join(f"{c:.4f}*{s}" for c, s in zip(coeffs[:-1], task.symbols[1:])) + expression = f"{expr_parts} + {coeffs[-1]:.4f}" + return SRResult(predict=predict, expression=expression) diff --git a/src/sr_harness/_vendor/llmsr_bench/algorithms/my_igsr.py b/src/sr_harness/_vendor/llmsr_bench/algorithms/my_igsr.py new file mode 100644 index 0000000000000000000000000000000000000000..6a6f2b64ae311045f70a988017fca46f2613693b --- /dev/null +++ b/src/sr_harness/_vendor/llmsr_bench/algorithms/my_igsr.py @@ -0,0 +1,419 @@ +"""LLM-SRBench adapter for the upstream IGSR implementation. + +The upstream checkout is used without source changes. This module starts it in +an isolated process, injects the benchmark training data as an IGSR DataBundle, +and audits every LiteLLM call before returning control to IGSR. Per-call usage +is flushed to ``usage.jsonl`` and relayed through ``_logger`` so completed calls +remain accountable if a later search step fails. +""" +from __future__ import annotations + +import argparse +import ast +import json +import logging +import os +from pathlib import Path +import re +import signal +import subprocess +import sys +import tempfile +import threading +import time +import traceback +from typing import TYPE_CHECKING, Any + +import numpy as np + +if TYPE_CHECKING: + from ..core import SEDTask, SRResult + +_logger = logging.getLogger(f"sr_harness.{__name__}") +_ROOT = Path(__file__).resolve().parents[5] +_DEFAULTS = { + # Released upstream experiment defaults, except for the deliberately + # reduced adapter runtime budget documented below. + "max_agent_steps": 5, + "terms_per_round": 5, + "first_round_n_candidates": 10, + "keep_n_terms": 6, + # One root batch contains n_successors=5 candidates. Budget 5 keeps the + # default smoke/benchmark run to that single batch (~0.5--0.75 h with the + # current OpenRouter model); budget 6 starts another five-candidate batch. + "total_budget": 5, + "depth_limit": 10, + "n_successors": 5, + "early_stop_patience": 10, + "retry_attempts": 10, + "preview_n_elements": 50, + "run_timeout": 0.0, +} + + +def update_parser(parser: argparse.ArgumentParser) -> argparse.ArgumentParser: + parser.add_argument("--llm_provider", choices=["openrouter"], default="openrouter") + parser.add_argument("--llm_model", default="deepseek/deepseek-v4-flash-0731") + parser.add_argument("--igsr_repo", type=Path, default=_ROOT / "baseline/repo/IGSR") + parser.add_argument("--igsr_python", default=sys.executable) + for name, default in _DEFAULTS.items(): + parser.add_argument(f"--igsr_{name}", type=type(default), default=default) + parser.add_argument("--igsr_max_tokens", type=int, default=None, + help="Maximum completion tokens for each IGSR LLM call.") + parser.add_argument("--igsr_reasoning", choices=["default", "low"], default="default", + help="OpenRouter reasoning effort; default leaves provider behavior unchanged.") + parser.add_argument("--igsr_error_on_all_weights_zero", + action=argparse.BooleanOptionalAction, default=True, + help="Preserve upstream's hard failure for an all-near-zero linear fit.") + parser.add_argument("--igsr_tree", action=argparse.BooleanOptionalAction, default=True) + parser.add_argument("--igsr_early_stop", action=argparse.BooleanOptionalAction, default=True) + return parser + + +def _usage_from_response(response: Any) -> dict[str, Any]: + """Normalize LiteLLM/OpenRouter usage like ``sr_harness.api.openrouter_api``.""" + usage = getattr(response, "usage", None) + raw = usage.to_dict() if hasattr(usage, "to_dict") else dict(usage or {}) + prompt = int(raw.get("prompt_tokens") or 0) + completion = int(raw.get("completion_tokens") or 0) + total = int(raw.get("total_tokens") or prompt + completion) + details = raw.get("completion_tokens_details") or {} + reasoning = int(details.get("reasoning_tokens") or 0) + tokens = {"prompt": prompt, "answer": max(completion - reasoning, 0)} + if reasoning: + tokens["reason"] = reasoning + if total > prompt + completion: + tokens["other"] = total - prompt - completion + + # OpenRouter may expose its authoritative cost in usage.cost. LiteLLM + # commonly moves it to response._hidden_params.response_cost instead. + cost = raw.get("cost") + hidden = getattr(response, "_hidden_params", None) or {} + if cost is None and isinstance(hidden, dict): + cost = hidden.get("response_cost") + if cost is None: + extra = getattr(response, "model_extra", None) or {} + cost = extra.get("cost") if isinstance(extra, dict) else None + return {"token": tokens, "price": {"total": float(cost or 0.0)}} + + +def _summarize_usage(path: Path) -> dict[str, Any]: + token: dict[str, int] = {} + price: dict[str, float] = {} + calls = failed_calls = 0 + elapsed = 0.0 + if path.is_file(): + for line in path.read_text(encoding="utf-8").splitlines(): + if not line.strip(): + continue + row = json.loads(line) + calls += row.get("status") == "ok" + failed_calls += row.get("status") != "ok" + elapsed += float(row.get("elapsed_seconds") or 0) + for key, value in row.get("usage", {}).get("token", {}).items(): + token[key] = token.get(key, 0) + int(value) + for key, value in row.get("usage", {}).get("price", {}).items(): + price[key] = price.get(key, 0.0) + float(value) + return {"calls": calls, "failed_calls": failed_calls, "elapsed_seconds": elapsed, + "token": token, "price": price} + + +def _safe_term(expr: str, values: dict[str, np.ndarray]) -> np.ndarray: + tree = ast.parse(expr, mode="eval") + for node in ast.walk(tree): + if isinstance(node, (ast.Lambda, ast.FunctionDef, ast.ClassDef, ast.Import, ast.ImportFrom)): + raise ValueError(f"Unsafe IGSR term: {expr!r}") + if isinstance(node, ast.Name) and node.id.startswith("__"): + raise ValueError(f"Unsafe IGSR term: {expr!r}") + result = eval(compile(tree, "", "eval"), + {"__builtins__": {}, "np": np, "numpy": np, "abs": np.abs}, values) + return np.asarray(result, dtype=float) + + +def _display_term(term: str, symbols: list[str]) -> str: + result = term.replace("numpy.", "").replace("np.", "") + result = re.sub(r"\bsquare\(([^()]*)\)", r"(\1)**2", result) + for index in range(len(symbols) - 1, 0, -1): + result = re.sub(rf"\bx{index}\b", symbols[index], result) + return result + + +def _build_result(result: dict[str, Any], symbols: list[str]): + from ..core import SRResult + + terms = list(result.get("terms") or []) + coefficients = np.asarray(result.get("coefficients"), dtype=float).reshape(-1) + intercept = float(result.get("intercept") or 0.0) + if not terms or len(terms) != len(coefficients) or not np.isfinite(coefficients).all(): + raise RuntimeError("IGSR returned no finite fitted candidate.") + + pieces = [repr(intercept)] if intercept else [] + pieces.extend(f"({float(coef)!r})*({_display_term(term, symbols)})" + for coef, term in zip(coefficients, terms)) + expression = " + ".join(pieces) or "0.0" + + def predict(X): + X = np.asarray(X, dtype=float) + if X.ndim != 2 or X.shape[1] != len(symbols) - 1: + raise ValueError(f"Expected X with shape (n, {len(symbols) - 1}), got {X.shape}") + if not len(X): + return np.empty(0, dtype=float) + values = {f"x{i + 1}": X[:, i] for i in range(X.shape[1])} + columns = [] + for term in terms: + column = _safe_term(term, values) + columns.append(np.broadcast_to(column, (len(X),))) + return np.column_stack(columns) @ coefficients + intercept + + return SRResult(predict=predict, expression=expression) + + +def run(args: argparse.Namespace, task: SEDTask) -> SRResult: + from dotenv import dotenv_values + + X = np.asarray(task.train_X, dtype=float) + y = np.asarray(task.train_y, dtype=float).reshape(-1) + if X.ndim != 2 or len(X) != len(y) or len(X) < 6: + raise ValueError("IGSR requires at least six matching training samples.") + if len(task.symbols) != X.shape[1] + 1 or not np.isfinite(X).all() or not np.isfinite(y).all(): + raise ValueError("Training symbols must match columns and training data must be finite.") + repo = Path(getattr(args, "igsr_repo", _ROOT / "baseline/repo/IGSR")).resolve() + if not (repo / "src/igsr/method/igsr.py").is_file(): + raise FileNotFoundError(f"Clone https://github.com/DrShushen/IGSR into {repo}") + + # Deliberately read the project .env, never a shell startup file. The + # project value overrides a possibly inherited OPENROUTER_API_KEY. + key = dotenv_values(_ROOT / ".env").get("OPENROUTER_API_KEY") + if not key: + raise ValueError("OPENROUTER_API_KEY is missing from the project .env.") + env = os.environ.copy() + env["OPENROUTER_API_KEY"] = key + env["LITELLM_LOCAL_MODEL_COST_MAP"] = "True" + for name in ("OPENBLAS_NUM_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS", "NUMEXPR_NUM_THREADS"): + env[name] = "1" + + config = {name: getattr(args, f"igsr_{name}", default) for name, default in _DEFAULTS.items()} + config.update(model=getattr(args, "llm_model", "deepseek/deepseek-v4-flash-0731"), + max_tokens=getattr(args, "igsr_max_tokens", None), + reasoning=getattr(args, "igsr_reasoning", "default"), + error_on_all_weights_zero=getattr( + args, "igsr_error_on_all_weights_zero", True), + tree=getattr(args, "igsr_tree", True), + early_stop=getattr(args, "igsr_early_stop", True), + seed=int(getattr(args, "seed", 0))) + for name in ("max_agent_steps", "terms_per_round", "first_round_n_candidates", "keep_n_terms", + "total_budget", "depth_limit", "n_successors", "early_stop_patience", "retry_attempts"): + if config[name] <= 0: + raise ValueError(f"igsr_{name} must be positive.") + if config["run_timeout"] < 0: + raise ValueError("igsr_run_timeout must be nonnegative.") + if config["max_tokens"] is not None and config["max_tokens"] <= 0: + raise ValueError("igsr_max_tokens must be positive when provided.") + + root = Path(getattr(args, "save_path", None) or _ROOT / "logs/igsr") / "igsr" + root.mkdir(parents=True, exist_ok=True) + prefix = re.sub(r"[^\w.-]", "_", task.name)[:80] + "-" + work = Path(tempfile.mkdtemp(prefix=prefix, dir=root)).resolve() + np.savez(work / "train.npz", X=X, y=y) + request = {"config": config, "name": task.name, "symbols": list(task.symbols), + "descriptions": list(task.symbol_descs), "properties": list(task.symbol_properties)} + (work / "request.json").write_text(json.dumps(request, indent=2), encoding="utf-8") + metadata = {"status": "running", "started_at": time.time(), "task": task.name, + "model": config["model"], "config": config, "artifacts": str(work)} + metadata_path = work / "metadata.json" + metadata_path.write_text(json.dumps(metadata, indent=2), encoding="utf-8") + _logger.info( + f"IGSR start task={task.name} model={config['model']} " + f"config={config} artifacts={work}" + ) + + python = Path(getattr(args, "igsr_python", sys.executable)) + if not python.is_absolute(): + python = (_ROOT / python).resolve() + if not python.is_file(): + raise FileNotFoundError(f"IGSR Python interpreter does not exist: {python}") + # ``runpy`` starts the worker without giving an algorithm module a script + # entry point, and avoids shadowing upstream's ``igsr`` namespace package. + worker_code = ( + "import runpy,sys; from pathlib import Path; " + "ns=runpy.run_path(sys.argv[1]); " + "ns['_worker'](Path(sys.argv[2]), Path(sys.argv[3]))" + ) + cmd = [str(python), "-c", worker_code, str(Path(__file__).resolve()), str(repo), str(work)] + log_path = work / "worker.log" + process = subprocess.Popen(cmd, cwd=repo, env=env, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, text=True, bufsize=1, start_new_session=True) + + def relay(): + assert process.stdout is not None + with log_path.open("w", encoding="utf-8", buffering=1) as log: + for line in process.stdout: + log.write(line) + _logger.info(f"IGSR worker | {line.rstrip()}") + + reader = threading.Thread(target=relay, name="igsr-log-relay", daemon=True) + reader.start() + failure: BaseException | None = None + try: + returncode = process.wait(timeout=config["run_timeout"] or None) + if returncode: + raise RuntimeError(f"IGSR exited with status {returncode}. See {log_path}") + except subprocess.TimeoutExpired as exc: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + failure = RuntimeError(f"IGSR exceeded its run timeout. See {log_path}") + failure.__cause__ = exc + except BaseException as exc: + failure = exc + if process.poll() is None: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + finally: + reader.join(timeout=10) + summary = _summarize_usage(work / "usage.jsonl") + metadata.update(status="failed" if failure else "completed", finished_at=time.time(), + elapsed_seconds=time.time() - metadata["started_at"], usage=summary) + if failure: + metadata["error"] = repr(failure) + metadata_path.write_text(json.dumps(metadata, indent=2), encoding="utf-8") + _logger.info( + f"IGSR usage task={task.name} elapsed={metadata['elapsed_seconds']:.3f}s " + f"calls={summary['calls']} failed_calls={summary['failed_calls']} " + f"tokens={summary['token']} money_usd={summary['price'].get('total', 0.0):.9f} " + f"artifacts={work}" + ) + if failure: + raise failure + result_path = work / "result.json" + if not result_path.is_file(): + raise RuntimeError(f"IGSR produced no result. See {log_path}") + return _build_result(json.loads(result_path.read_text(encoding="utf-8")), list(task.symbols)) + + +def _worker(repo: Path, work: Path) -> None: + sys.path.insert(0, str(repo / "src")) + import pandas as pd + import litellm + from omegaconf import OmegaConf + from sklearn.linear_model import LinearRegression + from igsr.dataset import DataBundle + import igsr.method.igsr as method + from igsr.method.igsr_utils import DesignMatrix + from igsr.agent.agent import LiteLLMAgent as UpstreamAgent + + request = json.loads((work / "request.json").read_text(encoding="utf-8")) + cfg_in = request["config"] + with np.load(work / "train.npz") as data: + X, y = data["X"], data["y"] + names = [f"x{i + 1}" for i in range(X.shape[1])] + frame = pd.DataFrame(X, columns=names) + frame["y"] = y + rng = np.random.default_rng(cfg_in["seed"]) + order = rng.permutation(len(frame)) + n_train = max(2, int(0.7 * len(frame))) + n_val = max(2, int(0.15 * len(frame))) + if n_train + n_val > len(frame) - 1: + n_train, n_val = len(frame) - 3, 2 + bundle = DataBundle( + name=request["name"], data_settings={}, dataset_train=frame.iloc[order[:n_train]].copy(), + dataset_validation=frame.iloc[order[n_train:n_train + n_val]].copy(), + dataset_test=frame.iloc[order[n_train + n_val:]].copy(), target_columns=["y"], + data_dictionary="\n".join( + [f"y (target): {request['descriptions'][0]}"] + + [f"{name}: {desc}" for name, desc in zip(names, request["descriptions"][1:])] + ), + ) + method.get_dataset = lambda _cfg: bundle + + usage_path = work / "usage.jsonl" + original_completion = litellm.completion + + def audited_completion(*args, **kwargs): + started = time.time() + kwargs.setdefault("extra_body", {"usage": {"include": True}}) + try: + response = original_completion(*args, **kwargs) + record = {"timestamp": time.time(), "status": "ok", "model": kwargs.get("model"), + "elapsed_seconds": time.time() - started, "usage": _usage_from_response(response)} + return response + except BaseException as exc: + record = {"timestamp": time.time(), "status": "error", "model": kwargs.get("model"), + "elapsed_seconds": time.time() - started, + "usage": {"token": {}, "price": {}}, "error": repr(exc)} + raise + finally: + with usage_path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(record, default=str) + "\n") + handle.flush() + os.fsync(handle.fileno()) + print("IGSR_API_USAGE " + json.dumps(record, default=str), flush=True) + + litellm.completion = audited_completion + + class OpenRouterAgent(UpstreamAgent): + def __init__(self, *args, model="openai/gpt-4", completion_kwargs=None, **kwargs): + if model.startswith("openai/"): + model = "openrouter/" + model[len("openai/"):] + completion_kwargs = dict(completion_kwargs or {}) + completion_kwargs["api_key"] = os.environ["OPENROUTER_API_KEY"] + if cfg_in.get("max_tokens") is not None: + completion_kwargs["max_tokens"] = int(cfg_in["max_tokens"]) + extra_body = dict(completion_kwargs.get("extra_body") or {}) + extra_body["usage"] = {"include": True} + if cfg_in.get("reasoning") == "low": + extra_body["reasoning"] = {"effort": "low"} + completion_kwargs["extra_body"] = extra_body + super().__init__(*args, model=model, completion_kwargs=completion_kwargs, **kwargs) + + method.LiteLLMAgent = OpenRouterAgent + experiment = { + "kind": "igsr", "tree": cfg_in["tree"], "n_iters": cfg_in["total_budget"], + "max_agent_steps": cfg_in["max_agent_steps"], "terms_per_round": cfg_in["terms_per_round"], + "first_round_n_candidates": cfg_in["first_round_n_candidates"], + "keep_n_terms": cfg_in["keep_n_terms"], "total_budget": cfg_in["total_budget"], + "depth_limit": cfg_in["depth_limit"], "n_successors": cfg_in["n_successors"], + "c": 1.41421356, "rollout_is_just_node_reward": True, "rollout_depth": 1, + "influence_feedback": True, "history_enabled": True, "refit_aware": False, + "refit_aware_efficient": False, "early_stop_enabled": cfg_in["early_stop"], + "early_stop_patience": cfg_in["early_stop_patience"], "optimization_method": "linear", + "fallback_ridge_small_alpha_for_stability": False, + "error_on_all_weights_zero": cfg_in["error_on_all_weights_zero"], + "allow_error_history_length": 15, "print_prompts": False, "save_new_terms": False, + "algorithmic_pruning": False, "additional_validation_of_terms": True, + "retry_attempts": cfg_in["retry_attempts"], "simplified_prompts": False, + "use_xgb_predictor": False, "keep_n_columns": None, "keep_n_columns_always_keep": None, + "break_on_tokens": False, "break_above_N_tokens": 260000, + "break_on_wallclock": False, "break_above_wallclock": 300, + "preview_N_elements": cfg_in["preview_n_elements"], "collapse_seq_feats": False, + "focus_on_seq_feats": False, "show_feature_importance": False, + "feature_importance_max_features": 20, + } + cfg = OmegaConf.create({ + "logging": {"logger_name": "igsr.adapter", "mode": "w", + "log_file": str(work / "igsr.jsonl")}, + # `kind=openai` passes the upstream branch; OpenRouterAgent changes only + # LiteLLM's provider prefix, leaving IGSR's prompts/search untouched. + # Never put the real credential in cfg: upstream prints the whole cfg + # before its logger has a chance to redact it. OpenRouterAgent injects + # the credential directly from the child environment at request time. + "llm": {"kind": "openai", "model_type": cfg_in["model"], "model_version": "", + "deployment": cfg_in["model"], "api_key": "***ENV_ONLY***"}, + "experiment": experiment, + "dataset": {"kind": "adapter", "name": request["name"], "task": "regression", "seed": None}, + }) + try: + upstream_result = method.igsr(cfg, cfg_in["seed"]) + history = upstream_result["history_test"] + best = min(history, key=lambda entry: float(entry["metrics"]["mse"])) + terms = list(best["metadata"]["terms_after"]) + design = DesignMatrix.from_terms(terms, {name: X[:, i] for i, name in enumerate(names)}) + reg = LinearRegression().fit(design.phi, y) + result = {"terms": design.term_names, "coefficients": np.asarray(reg.coef_).reshape(-1).tolist(), + "intercept": float(np.asarray(reg.intercept_).reshape(-1)[0]), + "upstream_result": upstream_result, + "upstream_commit": subprocess.check_output( + ["git", "-C", str(repo), "rev-parse", "HEAD"], text=True).strip()} + (work / "result.json").write_text(json.dumps(result, default=str, indent=2), encoding="utf-8") + except BaseException: + (work / "worker_error.txt").write_text(traceback.format_exc(), encoding="utf-8") + raise diff --git a/src/sr_harness/_vendor/llmsr_bench/algorithms/my_pysr.py b/src/sr_harness/_vendor/llmsr_bench/algorithms/my_pysr.py new file mode 100644 index 0000000000000000000000000000000000000000..85b5167f299b238b5cb60f8f50c9957d26fda887 --- /dev/null +++ b/src/sr_harness/_vendor/llmsr_bench/algorithms/my_pysr.py @@ -0,0 +1,104 @@ +"""PySR benchmark adapter with persistent, full precision artifacts.""" +from __future__ import annotations + +import argparse +import json +import logging +import os +import re +import time +import traceback +from pathlib import Path + +import numpy as np + +from .pysr import best_expression +from ..core import SEDTask, SRResult + +logger = logging.getLogger(__name__) + + +def update_parser(parser: argparse.ArgumentParser) -> argparse.ArgumentParser: + parser.add_argument('--pysr_timeout', type=float, default=1500) + parser.add_argument('--pysr_niterations', type=int, default=1000000) + parser.add_argument('--pysr_maxsize', type=int, default=30) + parser.add_argument('--pysr_populations', type=int, default=31) + parser.add_argument('--pysr_max_samples', type=int, default=0) + parser.add_argument('--pysr_binary_operators', nargs='+', default=['+', '-', '*', '/']) + parser.add_argument('--pysr_unary_operators', nargs='*', default=['sin', 'cos', 'exp', 'log', 'sqrt', 'square']) + parser.add_argument('--pysr_model_selection', choices=['best', 'accuracy', 'score'], default='best') + parser.add_argument('--pysr_parallelism', choices=['serial', 'multithreading', 'multiprocessing'], default='multithreading') + parser.add_argument('--pysr_procs', type=int, default=4) + return parser + + +def run(args: argparse.Namespace, task: SEDTask) -> SRResult: + started = time.time() + directory = Path(args.save_path).resolve() / 'pysr' / re.sub(r'[^\w.-]', '_', task.name) + directory.mkdir(parents=True, exist_ok=True) + metadata = {'task': task.name, 'symbols': task.symbols, 'seed': args.seed, + 'started_at': started, 'status': 'running', 'pid': os.getpid()} + + def save_metadata(): + temporary = directory / 'metadata.json.tmp' + temporary.write_text(json.dumps(metadata, indent=2, default=str)) + temporary.replace(directory / 'metadata.json') + + save_metadata() + try: + os.environ.setdefault('PYTHON_JULIACALL_HANDLE_SIGNALS', 'yes') + os.environ.setdefault('PYTHON_JULIACALL_THREADS', str(args.pysr_procs)) + os.environ.setdefault('JULIA_NUM_THREADS', str(args.pysr_procs)) + os.environ.setdefault('JULIA_NUM_GC_THREADS', '1') + from pysr import PySRRegressor + import pysr + X, y = task.train_X, task.train_y + indices = np.arange(len(y)) + if 0 < args.pysr_max_samples < len(y): + indices = np.random.default_rng(args.seed).choice(len(y), args.pysr_max_samples, replace=False) + X, y = X[indices], y[indices] + np.save(directory / 'fit_indices.npy', indices) + names = [f'x{i + 1}' for i in range(X.shape[1])] + model = PySRRegressor( + niterations=args.pysr_niterations, timeout_in_seconds=args.pysr_timeout, + maxsize=args.pysr_maxsize, populations=args.pysr_populations, + binary_operators=args.pysr_binary_operators, unary_operators=args.pysr_unary_operators, + model_selection=args.pysr_model_selection, precision=64, print_precision=17, + parallelism=args.pysr_parallelism, procs=args.pysr_procs, random_state=args.seed, + output_directory=str(directory), run_id='search', temp_equation_file=False, + progress=False, verbosity=1, + ) + metadata.update(pysr_version=pysr.__version__, parameters=model.get_params()) + save_metadata() + fit_started = time.time() + model.fit(X, y, variable_names=names) + fit_seconds = time.time() - fit_started + expression = best_expression(model, names, task.symbols[1:]) + (directory / 'expression.txt').write_text(expression + '\n') + model.equations_.drop(columns=['lambda_format'], errors='ignore').to_csv( + directory / 'equations.csv', index=False, float_format='%.17g') + selected = model.get_best() + metadata.update(status='completed', expression=expression, + internal_expression=str(selected.equation), selected_index=int(selected.name), + fit_seconds=fit_seconds, finished_at=time.time(), + total_seconds=time.time() - started) + save_metadata() + logger.info( + f"PySR {task.name}: {expression} (fit {fit_seconds:.3f}s); artifacts: {directory}" + ) + except BaseException: + metadata.update(status='failed', finished_at=time.time(), total_seconds=time.time() - started, + error=traceback.format_exc()) + save_metadata() + raise + + def predict(X): + prediction = np.asarray(model.predict(X), dtype=np.float64).reshape(-1) + # Benchmark calls ID then OOD; persist exact predictions for metric audits. + path = directory / f'predictions_{predict.calls}.npy' + np.save(path, prediction) + predict.calls += 1 + return prediction + + predict.calls = 0 + return SRResult(predict=predict, expression=expression) diff --git a/src/sr_harness/_vendor/llmsr_bench/algorithms/polynomial.py b/src/sr_harness/_vendor/llmsr_bench/algorithms/polynomial.py new file mode 100644 index 0000000000000000000000000000000000000000..29a6d0753c5a03c4850e9976702484c8586b97ea --- /dev/null +++ b/src/sr_harness/_vendor/llmsr_bench/algorithms/polynomial.py @@ -0,0 +1,59 @@ +""" +多项式拟合符号回归方法 +""" + +from __future__ import annotations + +import argparse +import numpy as np +import sr_harness_engine as engine +from sr_harness.core import AgentContext +from sr_harness.tools import PolynomialFitTool +from ..core import SEDTask, SRResult + + +def update_parser(parser): + """更新 parser,添加多项式拟合相关参数""" + parser.add_argument("--poly_degree", type=int, default=2, help="多项式拟合的最高阶数") + return parser + + +def run(args: argparse.Namespace, task: SEDTask) -> SRResult: + """多项式拟合符号回归方法 + + Args: SEDTask 包含了 SR 方法需要的所有输入信息, 可以根据需要使用其中的任意部分: + - task.name: str — 问题标识符 + - task.symbols: List[str] — 所有符号名, 第一个为输出变量 + - task.symbol_descs: List[str] — 符号的自然语言描述 + - task.symbol_properties: List[str] — 符号属性 ('O'=输出, 'V'=输入变量) + - task.train_X: np.ndarray — 训练输入, shape=(n_samples, n_input_vars) + - task.train_y: np.ndarray — 训练输出, shape=(n_samples,) + + Returns: SRResult 包含了 SR 方法的输出: + - predict: Callable[[np.ndarray], np.ndarray] — 输入 X, shape=(n, n_input_vars); 输出 y, shape=(n,) + - expression: Optional[str] — 发现的公式字符串 (可选, 用于记录) + """ + # 构建数据字典: {变量名: 数据数组} + target = task.symbols[0] + features = task.symbols[1:] + data = {feat: task.train_X[:, i] for i, feat in enumerate(features)} + data[target] = task.train_y + + # 执行多项式拟合 + tool = PolynomialFitTool(context=AgentContext(data=data, target=target)) + result = tool.execute( + x=features, + y=target, + max_degree=args.poly_degree, + include_interactions=True, + include_bias=True, + ) + + f = engine.parse(result["formula"]) + + def predict(X: np.ndarray) -> np.ndarray: + pred_data = {feat: X[:, i] for i, feat in enumerate(features)} + pred_data[target] = np.zeros(len(X)) # 占位,不会被使用 + return f.eval(pred_data).flatten() + + return SRResult(predict=predict, expression=result["formula"]) diff --git a/src/sr_harness/_vendor/llmsr_bench/algorithms/pysr.py b/src/sr_harness/_vendor/llmsr_bench/algorithms/pysr.py new file mode 100644 index 0000000000000000000000000000000000000000..a4fbe7741a9525a2aa3519271c4e02d16fa739dc --- /dev/null +++ b/src/sr_harness/_vendor/llmsr_bench/algorithms/pysr.py @@ -0,0 +1,105 @@ +""" +PySR 符号回归方法 +""" +from __future__ import annotations +import os +import re +import shutil +import logging +import argparse +import tempfile +import numpy as np +from typing import Any +from ..core import SEDTask, SRResult + +_logger = logging.getLogger(f"sr_harness.{__name__}") + + +def update_parser(parser: argparse.ArgumentParser) -> argparse.ArgumentParser: + """更新 parser,添加 PySR 相关参数。""" + parser.add_argument("--pysr_timeout", type=int, default=120, help="PySR 每个问题的搜索时间上限(秒)。") + parser.add_argument("--pysr_niterations", type=int, default=1000000, help="PySR 进化迭代次数。") + parser.add_argument("--pysr_maxsize", type=int, default=30, help="PySR 表达式最大复杂度。") + parser.add_argument("--pysr_populations", type=int, default=31, help="PySR 种群数量。") + parser.add_argument("--pysr_max_samples", type=int, default=500, help=( + "拟合时最多使用的训练样本数;<=0 表示使用全部样本。" + )) + parser.add_argument("--pysr_binary_operators", nargs="+", default=["+", "-", "*", "/"], help=( + 'PySR 二元算子列表' + )) + parser.add_argument("--pysr_unary_operators", nargs="+", default=["sin", "cos", "exp", "log", "sqrt", "square"], help=( + "PySR 一元算子列表" + )) + parser.add_argument("--pysr_model_selection", default="best", choices=["best", "accuracy", "score"], help=( + "PySR 模型选择策略。" + )) + return parser + + +def run(args: argparse.Namespace, task: SEDTask) -> SRResult: + """使用 PySRRegressor 执行符号回归。""" + try: + os.environ.setdefault("PYTHON_JULIACALL_HANDLE_SIGNALS", "yes") + from pysr import PySRRegressor + except ImportError as exc: + raise ImportError( + "PySR is not installed in the current environment. " + 'Install optional tool dependencies with: pip install -e ".[tools]"' + ) from exc + + features = task.symbols[1:] + X_fit, y_fit = task.train_X, task.train_y + + max_samples = getattr(args, "pysr_max_samples", 500) + if max_samples is not None and max_samples > 0 and len(y_fit) > max_samples: + rng = np.random.default_rng(args.seed) + idx = rng.choice(len(y_fit), size=max_samples, replace=False) + X_fit = X_fit[idx] + y_fit = y_fit[idx] + + internal_names = [f"x{i + 1}" for i in range(X_fit.shape[1])] + tmpdir = tempfile.mkdtemp(prefix=f"pysr_bench_{task.name}_") + + try: + model = PySRRegressor( + niterations=args.pysr_niterations, + timeout_in_seconds=args.pysr_timeout, + maxsize=args.pysr_maxsize, + populations=args.pysr_populations, + binary_operators=args.pysr_binary_operators, + unary_operators=args.pysr_unary_operators, + model_selection=args.pysr_model_selection, + temp_equation_file=True, + tempdir=tmpdir, + verbosity=1 if getattr(args, "verbose", False) else 0, + progress=bool(getattr(args, "verbose", False)), + parallelism="serial", + random_state=args.seed, + ) + model.fit(X_fit, y_fit, variable_names=internal_names) + expression = best_expression(model, internal_names, features) + _logger.note(f"PySR best expression for {task.name}: {expression}") + finally: + shutil.rmtree(tmpdir, ignore_errors=True) + + def predict(X: np.ndarray) -> np.ndarray: + return np.asarray(model.predict(X), dtype=float).reshape(-1) + + return SRResult(predict=predict, expression=expression) + + +def best_expression(model: Any, internal_names: list[str], original_names: list[str]) -> str: + expression = model.get_best().equation + expression = expression or "0" + expression = expression.strip() + expression = expression.replace("^", "**") + expression = expression.replace("Abs(", "abs(") + expression = expression.replace("square(", "pow2(") + + replacements = dict(zip(internal_names, original_names)) + placeholders = {name: f"__pysr_feature_{idx}__" for idx, name in enumerate(internal_names)} + for name in sorted(internal_names, key=len, reverse=True): + expression = re.sub(rf"\b{re.escape(name)}\b", placeholders[name], expression) + for name in internal_names: + expression = expression.replace(placeholders[name], replacements[name]) + return expression diff --git a/src/sr_harness/_vendor/llmsr_bench/algorithms/sr_harness.py b/src/sr_harness/_vendor/llmsr_bench/algorithms/sr_harness.py new file mode 100644 index 0000000000000000000000000000000000000000..310a1715c7cf6ec80c88c00d1b3bf829c27dd588 --- /dev/null +++ b/src/sr_harness/_vendor/llmsr_bench/algorithms/sr_harness.py @@ -0,0 +1,212 @@ +""" +多项式拟合符号回归方法 +""" +from __future__ import annotations + +import json +import argparse +import numpy as np +import sr_harness_engine as engine +from pathlib import Path +from logging import getLogger +from datetime import datetime +from sr_harness import SRAgent +from sr_harness.tools import BaseTool +from sr_harness.utils import format_pareto_front, log_exception, tag2ansi +from ..core import SEDTask, SRResult + +_logger = getLogger(f'sr_harness.{__name__}') + + +def update_parser(parser): + """更新 parser,添加多项式拟合相关参数""" + default_tools = sorted(set(BaseTool.all_registered_names) - { + 'evaluate_code', 'workspace_code_executor', 'ask_human', + 'call_llm', 'workspace_shell', 'create_skill', 'edit_skill', + 'edit_tool', 'harmonic_interaction_fit', + }) + parser.add_argument("--llm_provider", default="openrouter", help="LLM provider name.") + parser.add_argument("--llm_model", default="qwen/qwen3.5-flash-02-23", help="LLM model name.") + parser.add_argument("--tools", default=default_tools, type=str, nargs='+', choices=BaseTool.all_registered_names, help=( + "Optional list of tools to use." + )) + parser.add_argument("--ban_tools", default=[], type=str, nargs='+', help=( + "Optional list of tools to ban. Takes precedence over --tools." + )) + parser.add_argument("-K", "--local_sample_size", type=int, default=2, help=( + "Number of LLM samples to generate for each branch." + )) + parser.add_argument("-L", "--max_refinement_depth", type=int, default=10, help=( + "Maximum agent refinement depth." + )) + parser.add_argument("-C", "--global_width", type=int, default=1, help=( + "Number of independent branches per restart loop." + )) + parser.add_argument("-R", "--max_restart_loop", type=int, default=2, help=( + "Maximum number of best-solution restart loops." + )) + parser.add_argument("--restart_top_k", type=int, default=1, help=( + "Number of previous best formulas to inject into the next restart prompt." + )) + parser.add_argument("--llm_max_tokens", type=int, default=4096, help=( + "Maximum number of tokens to generate for each LLM response." + )) + parser.add_argument("--tool_parser", default="openai", choices=["openai", "text", "json", "xml"], help=( + "Tool response parser type." + )) + parser.add_argument("--max_workers", type=int, default=0, help=( + "Maximum number of parallel workers for tool execution. 0 means no parallel execution." + )) + parser.add_argument("--validation_fraction", type=float, default=0.2, help=( + "Fraction of samples held out for validation." + )) + parser.add_argument("--split_by", choices=["random", "ood"], default="random", help=( + "Validation split strategy." + )) + parser.add_argument("--split_random_state", type=int, default=42, help=( + "Random seed used by the random validation split." + )) + parser.add_argument("--force_initial_diagnostics", action=argparse.BooleanOptionalAction, default=True, help=( + "Before each branch's first LLM request, run statistics_analysis, " + "relationship_analysis, and read discover-symbolic-laws." + )) + return parser + + +def run(args: argparse.Namespace, task: SEDTask) -> SRResult: + """多项式拟合符号回归方法 + + Args: SEDTask 包含了 SR 方法需要的所有输入信息, 可以根据需要使用其中的任意部分: + - task.name: str — 问题标识符 + - task.symbols: List[str] — 所有符号名, 第一个为输出变量 + - task.symbol_descs: List[str] — 符号的自然语言描述 + - task.symbol_properties: List[str] — 符号属性 ('O'=输出, 'V'=输入变量) + - task.train_X: np.ndarray — 训练输入, shape=(n_samples, n_input_vars) + - task.train_y: np.ndarray — 训练输出, shape=(n_samples,) + + Returns: SRResult 包含了 SR 方法的输出: + - predict: Callable[[np.ndarray], np.ndarray] — 输入 X, shape=(n, n_input_vars); 输出 y, shape=(n,) + - expression: Optional[str] — 发现的公式字符串 (可选, 用于记录) + """ + if args.save_path is None: + exp_save_path = None + else: + exp_save_path = Path(args.save_path) / "experiments" / f"{task.name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}" + exp_save_path.mkdir(parents=True, exist_ok=True) + + # 构建数据字典: {变量名: 数据数组} + target = task.symbols[0] + features = task.symbols[1:] + y = {target: task.train_y} + X = {feat: task.train_X[:, i] for i, feat in enumerate(features)} + + # 构建问题描述 + problem_description = [] + for sym, desc, prop in zip(task.symbols, task.symbol_descs, task.symbol_properties): + kind = {'O': "Output", 'V': "Input Variable"}.get(prop, "Unknown") + problem_description.append(f"{sym} ({kind}): {desc}") + # problem_description.append("(Note: The formula MUST utilize all input variables!)") + problem_description = "\n".join(problem_description) + _logger.note(f"Problem Description:\n{problem_description}") + + # 构建可用工具集合 + tools = [tool for tool in args.tools if tool not in args.ban_tools] + _logger.note(tag2ansi(f"Using tools: [green bold]{', '.join(tools)}[reset]")) + + # 执行符号回归拟合 + agent = SRAgent( + llm_provider=args.llm_provider, + llm_model=args.llm_model, + tools=tools, + local_sample_size=args.local_sample_size, + max_refinement_depth=args.max_refinement_depth, + global_width=args.global_width, + max_restart_loop=args.max_restart_loop, + restart_top_k=args.restart_top_k, + llm_max_tokens=args.llm_max_tokens, + verbose=args.verbose, + tool_parser=args.tool_parser, + save_path=exp_save_path, + max_workers=args.max_workers, + validation_fraction=args.validation_fraction, + split_by=args.split_by, + split_random_state=args.split_random_state, + force_initial_diagnostics=args.force_initial_diagnostics, + ) + result = { + "start_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), + "problem_name": task.name, + "duration_seconds": None, + "status": "not_started", + "progress": None, + "token_usage": None, + "money_usage": None, + "tools_usage": None, + "llm_model": f"{args.llm_model} @ {args.llm_provider}", + } + try: + result |= agent.run(X=X, y=y, problem_description=problem_description) + except KeyboardInterrupt as e: + _logger.note("Experiment interrupted by user.") + result |= getattr(e, "partial_result", {"status": "interrupted"}) + except Exception as e: + _logger.error(f"Experiment failed with an exception: {log_exception(e)}") + result |= getattr(e, "partial_result", {"status": "failed"}) + result["error"] = repr(e) + if args.debug: raise + finally: + result["duration_seconds"] = (datetime.now() - datetime.strptime(result["start_time"], "%Y-%m-%d %H:%M:%S")).total_seconds() + result["times_usage"] = agent.named_timer.named_time + result["token_usage"] = agent.token_counter.count + result["money_usage"] = agent.money_counter.count + result["tools_usage"] = agent.tools_counter.named_count + # 打印日志 + log = '\n'.join([ + f"[red]{k.replace('_', ' ').title()}[reset]: {v}" + for k, v in result.items() + if k not in {"pareto_front", "candidates"} + ]) + candidates = result.get("candidates", []) + pareto = [ + {"formula": candidates[index]["formula"], **candidates[index]["details"]} + for index in result.get("pareto_front", []) + if 0 <= index < len(candidates) + ] + _logger.note(tag2ansi( + f'\n[gray]{"=" * 50}[reset]\n' + "[red bold]Symbolic Regression Result[reset]\n" + f"{log}\n" + f"\n[red bold]Pareto Front[reset]\n" + f"{format_pareto_front(pareto)}\n" + f'[gray]{"=" * 50}[reset]' + )) + # 保存文件 + if exp_save_path is not None: + result_path = exp_save_path / "result.jsonl" + with open(result_path, "a", encoding="utf-8") as f: + json.dump(result, f, ensure_ascii=True) + f.write("\n") + _logger.note(f"Result saved to {result_path}") + + if result.get("status") not in {"completed", "early_stopped"}: + error = result.get("error") or f"agent did not complete (status={result.get('status')!r})" + raise RuntimeError(error) + best_index = result.get("best_candidate") + candidates = result.get("candidates", []) + best_formula = ( + candidates[best_index]["formula"] + if isinstance(best_index, int) and 0 <= best_index < len(candidates) + else None + ) + if not best_formula: + error = f"agent finished with status={result.get('status')!r} but no formula was produced" + raise RuntimeError(error) + + f = engine.parse(best_formula) + + def predict(X: np.ndarray) -> np.ndarray: + pred_data = {feat: X[:, i] for i, feat in enumerate(features)} + pred_data[target] = np.zeros(len(X)) # 占位,不会被使用 + return f.eval(pred_data).flatten() + + return SRResult(predict=predict, expression=best_formula) diff --git a/src/sr_harness/_vendor/llmsr_bench/algorithms/sr_scientist.py b/src/sr_harness/_vendor/llmsr_bench/algorithms/sr_scientist.py new file mode 100644 index 0000000000000000000000000000000000000000..84f4013de44d3a778a448915a0402eaec639d611 --- /dev/null +++ b/src/sr_harness/_vendor/llmsr_bench/algorithms/sr_scientist.py @@ -0,0 +1,425 @@ +""" +Raw SR-Scientist runner for llmsr_bench. + +Unlike ``sr_scientist.py``, this module does not reimplement the SR-Scientist +search loop. It serializes one ``SEDTask`` into the parquet format expected by +``third-party/sr_scientist/inference/infer/inference.py`` and calls +``run_inference_batch`` directly. + +This keeps SR-Scientist's original assumptions: an OpenAI-compatible model API +and one or more SandboxFusion ``/run_code`` endpoints must be available. + +## 安装依赖 +# cd third-party/ +# git clone git@github.com:GAIR-NLP/SR-Scientist.git sr_scientist +# git clone git@github.com:bytedance/SandboxFusion.git SandboxFusion +# cd SandboxFusion +# conda create -n sandbox-runtime python=3.11 # 注:sandbox-runtime 这个名称被硬编码在 SandboxFusion 中,不宜自行修改! +# conda activate sandbox-runtime +# pip install poetry +# poetry install +# mkdir -p docs/build +# cd runtime/python && pip install -r requirements.txt && cd ../.. + +## 启动 SandBox +# cd ./third-party/SandboxFusion +# conda activate sandbox-runtime +# make run-online HOST=127.0.0.1 PORT=8080 + +## 测试 SandBox +# curl 'http://127.0.0.1:8080/run_code' -H 'Content-Type: application/json' --data-raw '{"code": "print(\"Hello, world!\")", "language": "python"}' + +## 启动多个 SandBox 并传给 sr-harness benchmark +# cd ./third-party/SandboxFusion +# conda activate sandbox-runtime +# make run-online HOST=127.0.0.1 PORT=9010 & +# make run-online HOST=127.0.0.1 PORT=9020 & +# make run-online HOST=127.0.0.1 PORT=9070 & +# make run-online HOST=127.0.0.1 PORT=9080 & +# cd ../../ +# sr-harness benchmark \ +# --algorithm sr_scientist \ +# --datasets lsrtransform \ +# --llm_provider openrouter \ +# --llm_model "deepseek/deepseek-v4-flash" \ +# --sr_scientist_sandbox_urls \ +# http://127.0.0.1:9010/run_code \ +# http://127.0.0.1:9020/run_code \ +# http://127.0.0.1:9030/run_code \ +# http://127.0.0.1:9040/run_code \ +# http://127.0.0.1:9050/run_code \ +# http://127.0.0.1:9060/run_code \ +# http://127.0.0.1:9070/run_code \ +# http://127.0.0.1:9080/run_code + +## 关闭 SandBox +# pkill -f "sandbox.server.server:app" + +By default this module checks the requested sandbox URLs once during import and +tries to auto-start missing local SandboxFusion endpoints. Set +SR_SCIENTIST_RAW_AUTO_SANDBOX=0 to disable auto-start, or set +SR_SCIENTIST_RAW_SANDBOX_URLS to choose default URLs when command-line URLs are +not available yet. +""" +from __future__ import annotations + +import os +import re +import sys +import ast +import json +import time +import socket +import logging +import asyncio +import subprocess +import tempfile +import numpy as np +import pandas as pd +from pathlib import Path +from dotenv import load_dotenv +from typing import Any, Dict, List, Tuple +from urllib.parse import urlparse +from ..core import SEDTask, SRResult + +_logger = logging.getLogger(f"sr_harness.{__name__}") +_ROOT = Path(__file__).resolve().parents[5] +_SANDBOX_FUSION_ROOT = _ROOT / "third-party" / "SandboxFusion" +_SR_SCIENTIST_INFERENCE = _ROOT / "third-party" / "sr_scientist" / "inference" +if _SR_SCIENTIST_INFERENCE.exists(): + sys.path.insert(0, str(_SR_SCIENTIST_INFERENCE)) +else: + raise SystemExit( + f"SR-Scientist inference code not found at {_SR_SCIENTIST_INFERENCE!r}. Please clone the SR-Scientist repository into third-party/ and try again." + f"Follow {__file__!r} docstring for detailed instructions." + ) + +try: + from infer.inference import run_inference_batch +except Exception as exc: + run_inference_batch = None + _IMPORT_ERROR = exc +else: + _IMPORT_ERROR = None + + +def _parse_sandbox_urls_from_argv() -> List[str]: + urls: List[str] = [] + argv = sys.argv[1:] + for idx, arg in enumerate(argv): + if arg == "--sr_scientist_sandbox_urls": + for value in argv[idx + 1:]: + if value.startswith("-"): + break + urls.append(value) + break + if arg.startswith("--sr_scientist_sandbox_urls="): + urls.extend(value for value in arg.split("=", 1)[1].split(",") if value) + break + if not urls: + urls = os.environ.get("SR_SCIENTIST_RAW_SANDBOX_URLS", "").split() + return urls or ["http://127.0.0.1:8080/run_code"] + + +def _endpoint_host_port(url: str) -> Tuple[str, int]: + parsed = urlparse(url) + host = parsed.hostname or "127.0.0.1" + port = parsed.port or (443 if parsed.scheme == "https" else 80) + return host, port + + +def _port_is_open(host: str, port: int, timeout: float = 0.25) -> bool: + try: + with socket.create_connection((host, port), timeout=timeout): + return True + except OSError: + return False + + +def _start_sandboxfusion_endpoint(host: str, port: int) -> bool: + if not _SANDBOX_FUSION_ROOT.exists(): + _logger.warning( + f"SandboxFusion is not installed in third-party/SandboxFusion, or conda env sandbox-runtime is missing. " + f"Install it according to {__file__}'s module docstring." + ) + return False + + log_dir = _ROOT / "logs" / "sr_scientist" / "sandbox" + log_dir.mkdir(parents=True, exist_ok=True) + log_path = log_dir / f"sandboxfusion_{port}.log" + log_file = open(log_path, "ab") + env = os.environ.copy() + venv_python = _SANDBOX_FUSION_ROOT / "venv" / "bin" / "python" + if venv_python.exists(): + env.setdefault("SANDBOX_PYTHON", str(venv_python)) + cmd = [ + str(venv_python), + "-m", + "uvicorn", + "sandbox.server.server:app", + "--host", + host, + "--port", + str(port), + ] + else: + cmd = [ + "bash", + "-lc", + ( + "conda run -n sandbox-runtime python -m uvicorn " + f"sandbox.server.server:app --host {host} --port {port}" + ), + ] + try: + subprocess.Popen( + cmd, + cwd=str(_SANDBOX_FUSION_ROOT), + env=env, + stdout=log_file, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + except Exception as exc: + _logger.warning(f"Failed to auto-start SandboxFusion on {host}:{port}: {exc}. Log: {log_path}") + log_file.close() + return False + + for _ in range(80): + if _port_is_open(host, port, timeout=0.1): + _logger.info(f"Auto-started SandboxFusion at http://{host}:{port}/run_code. Log: {log_path}") + return True + time.sleep(0.25) + _logger.warning(f"SandboxFusion did not become ready on {host}:{port}. Check log: {log_path}") + return False + + +def _ensure_sandboxfusion_on_import(): + if os.environ.get("SR_SCIENTIST_RAW_AUTO_SANDBOX", "1").lower() in {"0", "false", "no", "off"}: + return + + seen = set() + for url in _parse_sandbox_urls_from_argv(): + host, port = _endpoint_host_port(url) + key = (host, port) + if key in seen: + continue + seen.add(key) + if _port_is_open(host, port): + continue + _start_sandboxfusion_endpoint(host, port) + + +_ensure_sandboxfusion_on_import() + + +def update_parser(parser): + parser.add_argument("--llm_provider", default="openrouter", help=( + "LLM provider name used to infer model URL and API key." + )) + parser.add_argument("--llm_model", default="qwen/qwen3.6-plus", help=( + "Model name passed to SR-Scientist." + )) + parser.add_argument("--sr_scientist_model_url", default=None, help=( + "OpenAI-compatible model API base URL." + )) + parser.add_argument("--sr_scientist_api_key", default=None, help="API key override.") + parser.add_argument("--sr_scientist_sandbox_urls", nargs="+", default=["http://127.0.0.1:8080/run_code"], help=( + "SandboxFusion /run_code endpoints used by original SR-Scientist tools." + )) + parser.add_argument("--sr_scientist_mape_threshold", type=float, default=0.001, help=( + "Initial MAPE target." + )) + parser.add_argument("--sr_scientist_num_turns", type=int, default=3, help=( + "Original SR-Scientist --num-turns." + )) + parser.add_argument("--sr_scientist_top_k", type=int, default=3, help=( + "Original SR-Scientist --top-k." + )) + parser.add_argument("--sr_scientist_max_assistant_turns", type=int, default=100, help=( + "Original SR-Scientist --max-assistant-turns." + )) + return parser + + +def _provider_defaults(provider: str) -> Tuple[str, str]: + provider = provider.lower() + if provider == "openrouter": + return "https://openrouter.ai/api/v1", "OPENROUTER_API_KEY" + if provider == "deepseek": + return "https://api.deepseek.com", "DEEPSEEK_API_KEY" + if provider == "openai": + return "https://api.openai.com/v1", "OPENAI_API_KEY" + if provider == "siliconflow": + return "https://api.siliconflow.cn/v1", "SILICONFLOW_API_KEY" + raise ValueError( + f"Unsupported llm_provider={provider!r}. Pass --sr_scientist_model_url " + "and --sr_scientist_api_key for custom OpenAI-compatible endpoints." + ) + + +def _model_connection(args) -> Tuple[str, str]: + load_dotenv() + if args.sr_scientist_model_url: + model_url = args.sr_scientist_model_url + env_key = None + else: + model_url, env_key = _provider_defaults(args.llm_provider) + api_key = args.sr_scientist_api_key or (os.environ.get(env_key) if env_key else None) + if not api_key: + _logger.warning(f"Missing API key. Set {env_key} or pass --sr_scientist_api_key.") + return model_url, api_key + + +def _task_samples(task: SEDTask) -> Dict[str, Any]: + train = np.column_stack([task.train_y, task.train_X]).astype(float).tolist() + # The llmsr_bench algorithm interface only gives train data. Original + # SR-Scientist requires a test split for final aggregation, but selects the + # submitted equation by train MSE. Reusing train here preserves that choice; + # bench_sr_agent will perform the real ID/OOD evaluation afterwards. + return {"train": train, "test": train} + + +def _write_single_task_parquet(task: SEDTask, path: Path): + row = { + "dataset_identifier": "llmsr_bench", + "expression": "", + "symbols": task.symbols, + "symbol_descs": task.symbol_descs, + "symbol_properties": task.symbol_properties, + "samples": _task_samples(task), + } + df = pd.DataFrame([row], index=[task.name]) + path.parent.mkdir(parents=True, exist_ok=True) + df.to_parquet(path) + + +def _clean_code_block(raw_code: str) -> str: + raw_code = (raw_code or "").strip() + if "```python" in raw_code: + return raw_code.split("```python")[-1].split("```")[0].strip() + if "```" in raw_code: + parts = raw_code.split("```") + if len(parts) > 1: + return parts[1].strip() + return raw_code + + +def _compile_equation(equation_code: str): + scope: Dict[str, Any] = {} + exec(_clean_code_block(equation_code), {"np": np, "numpy": np}, scope) + equation = scope.get("equation") + if not callable(equation): + raise ValueError("SR-Scientist result did not define equation(..., params).") + return equation + + +def _expression_from_equation(equation_code: str, params: Any, task: SEDTask) -> str: + params = params or [] + code = _clean_code_block(equation_code) + try: + tree = ast.parse(code) + except SyntaxError: + return code + fn = next((node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == "equation"), None) + if fn is None: + return code + + assignments: Dict[str, ast.AST] = {} + ret_expr = None + for stmt in fn.body: + if isinstance(stmt, ast.Assign) and len(stmt.targets) == 1 and isinstance(stmt.targets[0], ast.Name): + assignments[stmt.targets[0].id] = stmt.value + elif isinstance(stmt, ast.Return): + ret_expr = stmt.value + if ret_expr is None: + return code + while isinstance(ret_expr, ast.Name) and ret_expr.id in assignments: + ret_expr = assignments[ret_expr.id] + + expr = ast.unparse(ret_expr) + for idx, value in enumerate(params): + if value is not None: + expr = re.sub(rf"\bparams\s*\[\s*{idx}\s*\]", f"({float(value):.17g})", expr) + + for original in task.symbols[1:]: + cleaned = original.strip("$").strip("\\").replace(" ", "_").replace("text", "") + if cleaned != original: + expr = re.sub(rf"\b{re.escape(cleaned)}\b", lambda _: original, expr) + return expr.replace("np.", "") + + +def _make_predict(equation_code: str, params: Any): + equation = _compile_equation(equation_code) + params_arr = np.asarray(params, dtype=float) + + def predict(X: np.ndarray) -> np.ndarray: + try: + y_pred = np.asarray(equation(*X.T, params_arr), dtype=float) + if y_pred.shape == (): + y_pred = np.full(X.shape[0], float(y_pred)) + return y_pred.reshape(-1) + except Exception: + return np.full(X.shape[0], np.nan) + + return predict + + +def _load_raw_result(output_json_path: Path, task: SEDTask) -> Dict[str, Any]: + records = json.loads(output_json_path.read_text(encoding="utf-8")) + if not records: + raise RuntimeError("Original SR-Scientist produced an empty results file.") + for record in records: + if str(record.get("index")) == str(task.name): + return record["submitted_results"] + return records[0]["submitted_results"] + + +def run(args, task: SEDTask) -> SRResult: + if run_inference_batch is None: + raise RuntimeError(f"Could not import original SR-Scientist inference code from {_SR_SCIENTIST_INFERENCE}: {_IMPORT_ERROR!r}") + + work_dir = Path(tempfile.gettempdir()) + input_path = work_dir / "input.parquet" + output_path = work_dir / "output.json" + _logger.note( + f"[{task.name}] Running original SR-Scientist inference: " + f"num_turns={args.sr_scientist_num_turns}, top_k={args.sr_scientist_top_k}, " + f"max_assistant_turns={args.sr_scientist_max_assistant_turns}" + ) + + try: + model_url, api_key = _model_connection(args) + _write_single_task_parquet(task, input_path) + + asyncio.run( + run_inference_batch( + model_name=args.llm_model, + model_url=model_url, + api_key=api_key, + sandbox_urls=args.sr_scientist_sandbox_urls, + parquet_file_path=str(input_path), + source=None, + mape_threshold=args.sr_scientist_mape_threshold, + num_turns=args.sr_scientist_num_turns, + top_k=args.sr_scientist_top_k, + output_json_path=str(output_path), + max_assistant_turns=args.sr_scientist_max_assistant_turns, + ) + ) + + submitted = _load_raw_result(output_path, task) + equation = submitted.get("equation") + params = submitted.get("optimized_params") + if not equation or params is None: + raise RuntimeError(f"Original SR-Scientist did not submit a usable equation: {submitted}") + + expression = _expression_from_equation(equation, params, task) + _logger.note(f"[{task.name}] Original SR-Scientist submitted expression:\n{expression}") + finally: + if input_path.exists(): + input_path.unlink() + if output_path.exists(): + output_path.unlink() + + return SRResult(predict=_make_predict(equation, params), expression=expression) diff --git a/src/sr_harness/_vendor/llmsr_bench/core.py b/src/sr_harness/_vendor/llmsr_bench/core.py new file mode 100644 index 0000000000000000000000000000000000000000..c98b061222b6aa29083d1c4bb72bf5bbfa527db5 --- /dev/null +++ b/src/sr_harness/_vendor/llmsr_bench/core.py @@ -0,0 +1,81 @@ +""" +LLM-SRBench 核心数据结构 +""" +from __future__ import annotations + +import numpy as np +import sr_harness_engine as engine +from dataclasses import dataclass +from typing import Callable, Dict, List, Optional + + +__all__ = ["SEDTask", "SRResult", "Problem"] + +@dataclass +class SEDTask: + """ + 符号回归任务的输入 — 传递给 SR 方法的最大 input set + + 注意: 原始 benchmark 的搜索器方法有以下资源限制, 公平比较时需声明: + - LLMSR: global_max_sample_num=1000 (LLM 生成的公式骨架数量上限) + - LaSR: max_num_samples=2000 (训练数据样本数上限, 非LLM调用次数) + - SGA: num_iters=25 × population (进化代数 × 种群大小) + - evaluate_timeout_seconds=30 (每个公式执行超时) + """ + name: str + symbols: List[str] + symbol_descs: List[str] + symbol_properties: List[str] + train_X: np.ndarray # shape: (n_train, n_input_vars) + train_y: np.ndarray # shape: (n_train,) + + +@dataclass +class SRResult: + """ + 符号回归方法的输出 — 最小 output set + + 注意: 原始 benchmark (LLMSR) 会对返回的公式做常数优化: + - 使用 BFGS 在训练数据上优化最多 10 个参数 + - 如果你的方法未做常数优化, 结果可能较差 + """ + predict: Callable[[np.ndarray], np.ndarray] # 输入 X(n, d) → y_pred(n,) + expression: Optional[str] = None # 发现的公式字符串 (可选, 用于记录) + metadata: Optional[Dict] = None # 算法侧运行元数据(耗时、token、credits 等) + + +@dataclass +class Problem: + """一个完整的 benchmark 问题, 包含训练/测试数据""" + dataset_identifier: str + equation_idx: str + symbols: List[str] + symbol_descs: List[str] + symbol_properties: List[str] + raw_expression: str # 原始的 ground truth 表达式 (如 "8*pi*Ef*epsilon*r**3/(3*sin(2*theta))") + gt_expression: engine.Expression # 处理后的 ground truth 表达式 + samples: Dict[str, np.ndarray] # {"train": ..., "test": ..., "ood_test"?} + + @property + def train_samples(self) -> np.ndarray: + return self.samples["train"] + + @property + def test_samples(self) -> np.ndarray: + return self.samples["test"] + + @property + def ood_test_samples(self) -> Optional[np.ndarray]: + return self.samples.get("ood_test", None) + + def create_task(self) -> SEDTask: + """将 Problem 转换为 SEDTask (SR 方法的输入)""" + data = self.train_samples + return SEDTask( + name=self.equation_idx, + symbols=self.symbols, + symbol_descs=self.symbol_descs, + symbol_properties=self.symbol_properties, + train_X=data[:, 1:], + train_y=data[:, 0], + ) diff --git a/src/sr_harness/agents/__init__.py b/src/sr_harness/agents/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5d3c363cdf4db337dea29d9ead1dc553a4993235 --- /dev/null +++ b/src/sr_harness/agents/__init__.py @@ -0,0 +1,14 @@ +"""SRAgent implementations.""" +from .agent import Agent +from .data_preparation_agent import DataPreparationAgent +from .evaluator_construction_agent import EvaluatorConstructionAgent +from .sr_agent import SRAgent +from .sr_agent_interactive import SRAgentInteractive + +__all__ = [ + "Agent", + "DataPreparationAgent", + "EvaluatorConstructionAgent", + "SRAgent", + "SRAgentInteractive", +] diff --git a/src/sr_harness/agents/agent.py b/src/sr_harness/agents/agent.py new file mode 100644 index 0000000000000000000000000000000000000000..bde27cc021c480058e69846570f96b10d75128da --- /dev/null +++ b/src/sr_harness/agents/agent.py @@ -0,0 +1,146 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""Common runtime mechanics shared by SRHarness agents.""" +from __future__ import annotations + +import logging +from abc import ABC, abstractmethod +from copy import deepcopy +from typing import Any + +from joblib import Parallel, delayed + +from ..api import BaseAPI +from ..core import AgentContext, ToolCall, ToolCallResult +from ..parser import BaseParser +from ..tools import BaseTool +from ..utils import FactoryMixin + +_logger = logging.getLogger(f"sr_harness.{__name__}") + + +def _execute_tool_call_in_subprocess(tool: BaseTool, tool_call: ToolCall) -> ToolCallResult: + """Execute one tool call in a worker process.""" + return tool(**tool_call.params) + + +class Agent(ABC, FactoryMixin): + """Base class for tool-using agents. + + Subclasses own their task loop and scientific state. This class only owns + common API/tool initialization and tool execution mechanics. + """ + + context: AgentContext + tool_box: BaseParser | None + api: BaseAPI | None + + @abstractmethod + def run(self, *args: Any, **kwargs: Any) -> Any: + """Run the agent's task loop. + + Args: + *args: Positional inputs accepted by the concrete agent. + **kwargs: Keyword inputs accepted by the concrete agent. + + Returns: + The result defined by the concrete agent implementation. + """ + + def initialize_with_context(self, context: AgentContext) -> None: + """Initialize the agent's tools and API from one shared context. + + Args: + context: Shared agent and tool context. + """ + self.context = context + tools = [tool_cls(context=context) for tool_cls in self.tool_cls_list] + self.tool_box = BaseParser.create(self.tool_parser, tool_list=tools) + self.api = BaseAPI.create( + self.llm_provider, + model=self.llm_model, + tool_box=self.tool_box, + environment=getattr(context.args, "api_environment", None), + save_path=getattr(self, "save_path", None), + ) + + def set_messages(self, messages: list[dict[str, Any]]) -> None: + """Expose the current prompt through the shared tool context. + + Args: + messages: Conversation messages in provider-compatible order. + """ + self.context.args.messages = deepcopy(messages) + + def execute_action(self, actions: list[ToolCall]) -> list[ToolCallResult]: + """Execute tool calls serially. + + Args: + actions: Tool calls to execute. + + Returns: + Results in the same order as ``actions``. + """ + if self.tool_box is None: + raise RuntimeError("Agent must be initialized with context before executing tools") + results: list[ToolCallResult] = [] + for action in actions: + try: + tool = self.tool_box[action.name] + except KeyError: + tool = None + if tool is None: + _logger.trace(f"Unknown tool call: {action.name}. Skipping execution.") + results.append(ToolCallResult( + ok=False, + result={}, + result_str=f'Unknown tool calling for "{action.name}"', + meta_data={"tool": action.name}, + )) + continue + self.tools_counter.add(action.name) + results.append(tool(**action.params)) + return results + + def execute_action_parallel( + self, + actions: list[ToolCall], + max_workers: int, + ) -> list[ToolCallResult]: + """Execute independent tool calls in worker processes. + + Args: + actions: Tool calls to execute. + max_workers: Maximum number of parallel workers. + + Returns: + Results in the same order as ``actions``. + """ + if self.tool_box is None: + raise RuntimeError("Agent must be initialized with context before executing tools") + results: list[ToolCallResult | None] = [None] * len(actions) + tasks = [] + for index, action in enumerate(actions): + try: + tool = self.tool_box[action.name] + except KeyError: + tool = None + if tool is None: + _logger.trace(f"Unknown tool call: {action.name}. Skipping execution.") + results[index] = ToolCallResult( + ok=False, + result={}, + result_str=f'Unknown tool calling for "{action.name}"', + meta_data={"tool": action.name}, + ) + else: + tasks.append((index, delayed(_execute_tool_call_in_subprocess)(tool, action))) + self.tools_counter.add(action.name) + + if tasks: + workers = Parallel(n_jobs=max_workers, backend="loky") + task_results = workers(task for _, task in tasks) + for (index, _), result in zip(tasks, task_results): + results[index] = result + if any(result is None for result in results): + raise RuntimeError("Parallel tool execution did not produce one result per call") + return [result for result in results if result is not None] diff --git a/src/sr_harness/agents/data_preparation_agent.py b/src/sr_harness/agents/data_preparation_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..9c7046a1ba4e616da9c2875e24a434cd27c00e0d --- /dev/null +++ b/src/sr_harness/agents/data_preparation_agent.py @@ -0,0 +1,370 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""Persistent tool-using agent for preparing structured research data.""" + +from __future__ import annotations + +import time +import uuid +from copy import deepcopy +from typing import Any + +from ..core import AgentContext +from ..runtime import InteractionManager +from ..parser import BaseParser +from ..skills import SkillManager +from ..tools import BaseTool +from ..utils import ParallelTimer +from .agent import Agent + + +class DataPreparationAgent(Agent): + """Turn workspace and web evidence into the shared structured dataset.""" + + DEFAULT_TOOLS = [ + "workspace_shell", + "workspace_code_executor", + "web_search", + "web_fetch", + "read_pdf", + "read_skill", + "validate_context_data", + ] + DEFAULT_EXCLUDED_SKILLS = frozenset({"discover-symbolic-laws"}) + + def __init__( + self, + llm_provider: str, + llm_model: str, + *, + context: AgentContext, + tools: list[str] | None = None, + tool_parser: str | BaseParser = "openai", + llm_max_tokens: int = 4096, + skills: list[str] | None = None, + interaction_manager: InteractionManager, + ) -> None: + self.llm_provider = llm_provider + self.llm_model = llm_model + self.tool_parser = tool_parser + self.llm_max_tokens = llm_max_tokens + self.turn_count = 0 + if hasattr(context.args, "skill_manager"): + skill_manager = context.args.skill_manager + if not isinstance(skill_manager, SkillManager): + raise TypeError("context.args.skill_manager must be a SkillManager") + else: + skill_manager = SkillManager(workspace=context.workspace) + context.args.skill_manager = skill_manager + self.skills = ( + list(skills) + if skills is not None + else [ + name + for name in skill_manager.load_skills() + if name not in self.DEFAULT_EXCLUDED_SKILLS + ] + ) + if not isinstance(interaction_manager, InteractionManager): + raise TypeError("interaction_manager must be an InteractionManager") + self.interaction_manager = interaction_manager + self.tool_cls_list = BaseTool.load_tool_classes(tools or self.DEFAULT_TOOLS) + self.tools_counter = ParallelTimer(unit="call") + self.tool_box = None + self.api = None + self.context = context + self._force_recorded = False + self._pending_runtime_settings: dict[str, Any] | None = None + self.buffer: list[dict[str, Any]] = [ + { + "role": "system", + "content": ( + "You are the data-preparation agent in SRHarness. Work with the user's persistent " + "workspace and conversation to create structured scientific data. Inspect uploaded files, " + "including PDF documents when relevant, and use web_search plus web_fetch when external " + "evidence is requested. If web_fetch reports that a site blocked automated access, do not " + "retry the same URL; use web_search to locate an accessible authoritative alternative. Use " + "workspace_code_executor for reproducible transformations.\n\n" + "Store general structured results in the flat workspace directory context.data/. Put each " + "variable and each file-backed axis in .npy, using NumPy arrays " + "that load with allow_pickle=False. The directory must contain manifest.json with variables " + "and axes objects. For network or hypergraph data, also add a positive integer num_nodes at " + "the manifest root; omit it for ordinary element-wise data. Each variable entry must contain " + "file, description, and axes; its file must be .npy and its axes list must follow array " + "dimension order. Each axis entry must contain description and exactly one of: values for a " + "short inline JSON array, file for .npy, or size for a positive positional length. " + "Mark every edge-list or hyperedge-list variable itself with kind: relation; relation arrays " + "must contain integer endpoint indices and require num_nodes at the manifest root. " + "For each variable whose final dimension depends on an edge list A or hyperedge list T, " + "set that variable's structure field to the name of A or T. The referenced relation must " + "be an integer (E, 2) or (H, 3) array whose endpoints are in [0, num_nodes), and the " + "dependent variable must have shape (..., E) or (..., H). Do not add structure to A or T " + "itself, and never infer a relation from a variable name. Prefer explicit values such as " + "['target', 'source'] for short semantic axes instead of an anonymous size. " + "Do not add format, version, revision, problem, attributes, shape, or dtype fields. Describe " + "units and other meaning in description. Preserve existing variable files unless the user " + "asks to replace them. NPY variables may contain numeric, Boolean, or string values. Preserve " + "categorical and textual variables as Unicode string arrays rather than object arrays, unless " + "the user explicitly requests an encoding such as one-hot encoding. Create and transform " + "context.data with workspace_code_executor, then call validate_context_data after every " + "write or edit. Use every reported error and repair action before claiming completion. " + "This validation " + "does not mutate the live AgentContext; InteractiveSession loads valid files after your " + "turn completes.\n\n" + "Explain material assumptions and sources. A later request may extend the existing data, so " + "retain and use this conversation and all workspace artifacts." + ), + } + ] + self.initialize_with_context(context) + + def _check_stop(self) -> None: + if self.interaction_manager.is_interrupting: + raise InterruptedError("用户强制中止") + + def _wait(self) -> bool: + with self.interaction_manager.wait() as messages: + for pending in messages: + self._append_prompt({"role": "user", "content": pending.content}) + self._apply_pending_runtime_settings() + return bool(messages) + + def queue_runtime_settings(self, settings: dict[str, Any]) -> None: + """Queue validated settings for the next safe iteration boundary.""" + current = self._pending_runtime_settings or {} + self._pending_runtime_settings = {**current, **settings} + + def _apply_pending_runtime_settings(self) -> None: + settings = self._pending_runtime_settings + if not settings: + return + self._pending_runtime_settings = None + for name in ("llm_provider", "llm_model", "tool_parser", "llm_max_tokens", "skills"): + if name in settings: + setattr(self, name, settings[name]) + if "tools" in settings: + self.tool_cls_list = BaseTool.load_tool_classes(settings["tools"]) + self.initialize_with_context(self.context) + + def _record_force(self, update: dict[str, Any] | None = None) -> None: + if self._force_recorded: + return + if update and (update.get("content") or update.get("reasoning")): + message = {"role": "assistant", "content": update.get("content", "")} + if update.get("reasoning"): + message["reasoning"] = update["reasoning"] + self.buffer.append(message) + self._append_prompt({"role": "user", "content": "用户强制中止"}) + self._force_recorded = True + + def _append_prompt(self, message: dict[str, Any]) -> None: + self.buffer.append(message) + if message.get("role") in {"system", "user"}: + self.interaction_manager.publish_event("prompt_added", {"message": message}) + + def initialize_with_context(self, context: AgentContext) -> None: + """Bind configured skills before constructing context-aware tools. + + Args: + context: Shared agent and tool context. + """ + context.args.enabled_skills = self.skills + super().initialize_with_context(context) + for tool in self.tool_box.tools: + tool.cancel_event = self.interaction_manager.cancellation_signal + + def run(self, instruction: str) -> dict[str, Any]: + """Continue the persistent preparation conversation until it yields control. + + Args: + instruction: Natural-language instruction for the agent. + + Returns: + dict[str, Any]: The operation result. + """ + instruction = instruction.strip() + if not instruction: + raise ValueError("instruction must not be empty") + self.context.args.llm_provider = self.llm_provider + self.context.args.llm_model = self.llm_model + self.context.args.llm_max_tokens = self.llm_max_tokens + if not any( + event["payload"].get("message") == self.buffer[0] + for event in self.interaction_manager.get_recent_events()["events"] + if event["kind"] == "prompt_added" + ): + self.interaction_manager.publish_event("prompt_added", {"message": self.buffer[0]}) + self._append_prompt({"role": "user", "content": instruction}) + committed = False + final_content = "" + while True: + self._check_stop() + self.turn_count += 1 + turn = self.turn_count + prompt = deepcopy(self.buffer) + self.set_messages(prompt) + self._publish("context", {"messages": prompt, "turn": turn}) + response_id = f"data:{uuid.uuid4().hex}" + tool_schemas = { + tool.metadata.name: { + "description": tool.metadata.description, + "parameters": tool.metadata.parameters or {}, + } + for tool in self.tool_box.tools + } + self._publish( + "assistant_started", + { + "response_id": response_id, + "turn": turn, + "tool_schemas": tool_schemas, + "provider": self.llm_provider, + "model": self.llm_model, + }, + ) + last_stream_emit = 0.0 + latest_stream_update: dict[str, Any] = {} + + def callback(update: dict[str, Any]) -> None: + nonlocal last_stream_emit, latest_stream_update + latest_stream_update = update + now = time.monotonic() + if update.get("type") == "delta" and now - last_stream_emit < 0.08: + return + last_stream_emit = now + self._publish( + "assistant_delta", + { + **update, + "response_id": response_id, + "turn": turn, + "tool_schemas": tool_schemas, + "provider": self.llm_provider, + "model": self.llm_model, + }, + ) + + try: + with self.interaction_manager.cancellable(self.api.cancel): + call_result = self.api( + prompt, + n=1, + max_tokens=self.llm_max_tokens, + callback=callback, + ) + responses = list(call_result) + self._check_stop() + except InterruptedError: + self._record_force(latest_stream_update) + self._publish( + "assistant_failed", + { + **latest_stream_update, + "response_id": response_id, + "turn": turn, + "provider": self.llm_provider, + "model": self.llm_model, + "error": "用户强制中止", + "interrupted": True, + }, + ) + self._wait() + continue + except Exception as exc: + self._publish( + "assistant_failed", + { + **latest_stream_update, + "response_id": response_id, + "turn": turn, + "provider": self.llm_provider, + "model": self.llm_model, + "error": str(exc), + }, + ) + raise + usage = { + "token": call_result.token_usage, + "price": call_result.money_usage, + } + if call_result.ok is False: + raise RuntimeError(call_result.error or "Model API request failed.") + if not responses: + raise RuntimeError("The model returned no usable response") + response = responses[0] + content, calls, message = response.content, response.tool_calls, response.message + final_content = content or "" + self._publish( + "assistant_completed", + { + "response_id": response_id, + "content": content, + "message": message, + "tool_calls": calls, + "tool_schemas": tool_schemas, + "turn": turn, + "usage": usage, + "provider": self.llm_provider, + "model": self.llm_model, + }, + ) + if not calls: + self.buffer.append(message) + if self._wait(): + continue + break + results = self._execute_with_events(calls) + self.buffer.append(message) + self.buffer.extend(self.tool_box.format_tool_result_messages(calls, results)) + committed = committed or any(result.result.get("data_committed") for result in results) + if self.interaction_manager.is_interrupting: + self._record_force() + self._check_stop() + self._wait() + result = { + "message": final_content, + "committed": committed, + "context": self.context.schema(), + } + self._publish("execution_completed", result) + return result + + def _execute_with_events(self, calls): + results = [] + for call in calls: + schema = next( + ( + { + "description": tool.metadata.description, + "parameters": tool.metadata.parameters or {}, + } + for tool in self.tool_box.tools + if tool.metadata.name == call.name + ), + {}, + ) + self._publish("tool_started", {"call": call, "tool_schema": schema}) + started_at = time.monotonic() + try: + tool = self.tool_box[call.name] + except KeyError: + tool = None + if tool is None: + result = super().execute_action([call])[0] + else: + with self.interaction_manager.cancellable(tool.cancel): + result = super().execute_action([call])[0] + self._publish( + "tool_completed", + { + "call": call, + "tool_schema": schema, + "result": result, + "duration_seconds": time.monotonic() - started_at, + "interrupted": self.interaction_manager.is_interrupting, + }, + ) + results.append(result) + return results + + def _publish(self, kind: str, payload: Any) -> None: + self.interaction_manager.publish_event(kind, payload) diff --git a/src/sr_harness/agents/evaluator_construction_agent.py b/src/sr_harness/agents/evaluator_construction_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..bb69b5394f14313a14733fe95614349b5046a3a4 --- /dev/null +++ b/src/sr_harness/agents/evaluator_construction_agent.py @@ -0,0 +1,404 @@ +"""Restricted agent for constructing and repairing custom evaluators.""" + +from __future__ import annotations + +import json +import math +import numbers +import time +import uuid +from typing import Any + +from ..api import BaseAPI +from ..core import AgentContext, json_value +from ..parser import BaseParser +from ..runtime import InteractionManager +from ..tools import BaseTool +from ..utils import ParallelTimer +from .agent import Agent + + +class EvaluatorConstructionAgent(Agent): + """Construct and validate evaluator scripts without mutating live context state.""" + + def __init__( + self, + *, + llm_provider: str, + llm_model: str, + context: AgentContext, + tools: list[BaseTool], + interaction_manager: InteractionManager, + tool_parser: str = "openai", + llm_max_tokens: int = 4096, + max_steps: int = 16, + ) -> None: + self.llm_provider = llm_provider + self.llm_model = llm_model + self.tool_parser = tool_parser + self.llm_max_tokens = llm_max_tokens + self.max_steps = max_steps + self.context = context + if not isinstance(interaction_manager, InteractionManager): + raise TypeError("interaction_manager must be an InteractionManager") + self.interaction_manager = interaction_manager + self._force_recorded = False + self._pending_runtime_settings: dict[str, Any] | None = None + self.tool_box = BaseParser.create(tool_parser, tool_list=tools) + for tool in self.tool_box.tools: + tool.cancel_event = self.interaction_manager.cancellation_signal + self.tools_counter = ParallelTimer(unit="call") + self.api = BaseAPI.create( + llm_provider, + model=llm_model, + tool_box=self.tool_box, + environment=getattr(context.args, "api_environment", None), + ) + self.buffer: list[dict[str, Any]] = [ + { + "role": "system", + "content": ( + "You construct SRHarness DefaultEvaluator subclasses using only the tools and skills " + "enabled for this session. Create evaluator scripts under context.evaluator/ with " + "workspace_code_executor, inspect workspace files with workspace_shell, and test scripts " + "with validate_evaluator. Never mutate the live AgentContext evaluator; InteractiveSession " + "alone loads the selected file. Consult read_skill when useful. Use read_source to inspect " + "src/sr_harness/evaluator/ and only the implementation symbols needed for the task. " + "Keep custom subclasses short and reuse evaluator.utils infrastructure. " + "DefaultEvaluator defines class methods split(context), fit(f, y, context), " + "evaluate(f, y, context), fit_candidate(f, context), and " + "evaluate_candidate(f, context). Override fit/evaluate to affect all equations, or " + "override the candidate-only methods for behavior such as ODE trajectory rollouts. " + "fit must return an Expression with every parameter bound. evaluate must return a " + "flat dictionary whose values are only float or int. Preserve mse, rmse, mae, mape, r2, aic, " + "bic, pearson_r, spearman_r, and complexity unless the user explicitly asks to remove " + "one. Metric, split, " + "index-selection, and ODE helpers live in `sr_harness.evaluator.utils`. New evaluator-specific " + "helpers belong on the custom subclass. Never hide metric failures in broad " + "try/except blocks or return placeholders such as strings or NaN: evaluate_formula " + "must exercise the new metric and return a finite numeric value before you finish. " + "Extract only necessary control values from context.args before passing them to other " + "helpers. Test changes when data are available and repair failures before answering.\n\n" + "The current dataset schema below is authoritative. Use its variable names, shapes, " + "axis relationships, target, and descriptions when implementing dataset-specific " + "metrics such as trajectory rollouts. A derivative target and its corresponding " + "observed state trajectory are distinct arrays.\n\n" + "For a trajectory rollout metric, preserve chronological order in split " + "instead of applying a random row split, integrate the fitted RHS from the first " + "observed state of each split, and compare the integrated state with the observed " + "state. Prefer scipy.integrate.solve_ivp with t_eval over a low-accuracy Euler loop. " + "candidate fit/evaluate receive an already-split context: do not call split from " + "either method and do not refit inside evaluate because fit has already run. " + "split should return chronological AgentContext views where practical.\n\n" + "Before implementing numerical infrastructure yourself, inspect " + "src/sr_harness/evaluator/utils/.\n\n" + f"Current dataset schema:\n```json\n" + f"{json.dumps(json_value(context.schema()), ensure_ascii=False, indent=2)}\n```\n\n" + "Begin by inspecting src/sr_harness/evaluator/. If context.evaluator/ already exists, " + "inspect its scripts too. Do not create that directory merely to inspect the workspace; " + "create it only immediately before writing the first custom evaluator script." + ), + } + ] + + def _publish(self, kind: str, payload: dict[str, Any]) -> None: + self.interaction_manager.publish_event(kind, payload) + + def _check_stop(self) -> None: + if self.interaction_manager.is_interrupting: + raise InterruptedError("用户强制中止") + + def _wait(self) -> bool: + with self.interaction_manager.wait() as messages: + for pending in messages: + self._append_prompt({"role": "user", "content": pending.content}) + self._apply_pending_runtime_settings() + return bool(messages) + + def queue_runtime_settings(self, settings: dict[str, Any]) -> None: + """Queue validated settings for the next safe iteration boundary.""" + current = self._pending_runtime_settings or {} + self._pending_runtime_settings = {**current, **settings} + + def _apply_pending_runtime_settings(self) -> None: + settings = self._pending_runtime_settings + if not settings: + return + self._pending_runtime_settings = None + for name in ("llm_provider", "llm_model", "tool_parser", "llm_max_tokens"): + if name in settings: + setattr(self, name, settings[name]) + if "skills" in settings: + self.context.args.enabled_skills = settings["skills"] + if "tools" in settings: + classes = { + tool_cls.metadata.name: tool_cls for tool_cls in BaseTool.load_tool_classes() + } + tools = [classes[name](context=self.context) for name in settings["tools"]] + self.tool_box = BaseParser.create(self.tool_parser, tool_list=tools) + for tool in self.tool_box.tools: + tool.cancel_event = self.interaction_manager.cancellation_signal + self.api = BaseAPI.create( + self.llm_provider, + model=self.llm_model, + tool_box=self.tool_box, + environment=getattr(self.context.args, "api_environment", None), + ) + + def _append_prompt(self, message: dict[str, Any]) -> None: + self.buffer.append(message) + if message.get("role") in {"system", "user"}: + self._publish("prompt_added", {"message": message}) + + def _record_force(self, update: dict[str, Any] | None = None) -> None: + if self._force_recorded: + return + if update and (update.get("content") or update.get("reasoning")): + message = {"role": "assistant", "content": update.get("content", "")} + if update.get("reasoning"): + message["reasoning"] = update["reasoning"] + self.buffer.append(message) + self._append_prompt({"role": "user", "content": "用户强制中止"}) + self._force_recorded = True + + def run(self, instruction: str) -> dict[str, Any]: + """Construct or repair a custom evaluator for one user instruction. + + Args: + instruction: Natural-language evaluator requirements. + + Returns: + The final assistant response and tool-event records produced during + construction. + + Raises: + ValueError: If ``instruction`` is empty. + """ + instruction = instruction.strip() + if not instruction: + raise ValueError("Evaluator construction instruction must not be empty") + if not any( + event["kind"] == "prompt_added" + for event in self.interaction_manager.get_recent_events()["events"] + ): + self._publish("prompt_added", {"message": self.buffer[0]}) + self._append_prompt({"role": "user", "content": instruction}) + tool_events: list[dict[str, Any]] = [] + timeline_events: list[dict[str, Any]] = [] + update_needs_test = False + require_custom_metric = any( + marker in instruction.lower() for marker in ("metric", "rmse", "指标", "评测结果") + ) + + def test_has_finite_custom_metrics(result: Any) -> bool: + if not result.ok or not isinstance(result.result, dict): + return False + standard = { + "mse", + "rmse", + "mae", + "mape", + "r2", + "aic", + "bic", + "pearson_r", + "spearman_r", + "complexity", + } + split_results = result.result.get("data_split_results", {}) + custom_values = [] + for split in split_results.values(): + metrics = split.get("metrics", {}) if isinstance(split, dict) else {} + if not standard <= set(metrics): + return False + custom_values.extend( + value for name, value in metrics.items() if name not in standard + ) + return (not require_custom_metric or bool(custom_values)) and all( + isinstance(value, numbers.Real) + and not isinstance(value, bool) + and math.isfinite(float(value)) + for value in custom_values + ) + + for step in range(1, self.max_steps + 1): + self._check_stop() + response_id = f"evaluator:{uuid.uuid4().hex}" + tool_schemas = { + tool.metadata.name: { + "description": tool.metadata.description, + "parameters": tool.metadata.parameters or {}, + } + for tool in self.tool_box.tools + } + event_context = { + "response_id": response_id, + "turn": step, + "tool_schemas": tool_schemas, + "provider": self.llm_provider, + "model": self.llm_model, + } + self._publish( + "context", + { + "messages": json_value(self.buffer), + "turn": step, + }, + ) + self._publish("assistant_started", event_context) + last_stream_emit = 0.0 + latest_stream_update: dict[str, Any] = {} + + def callback(update: dict[str, Any]) -> None: + nonlocal last_stream_emit, latest_stream_update + latest_stream_update = update + now = time.monotonic() + if update.get("type") == "delta" and now - last_stream_emit < 0.08: + return + last_stream_emit = now + self._publish("assistant_delta", {**update, **event_context}) + + try: + with self.interaction_manager.cancellable(self.api.cancel): + call_result = self.api( + self.buffer, + n=1, + max_tokens=self.llm_max_tokens, + callback=callback, + ) + rows = list(call_result) + self._check_stop() + except InterruptedError: + self._record_force(latest_stream_update) + self._publish( + "assistant_failed", + { + **latest_stream_update, + **event_context, + "error": "用户强制中止", + "interrupted": True, + }, + ) + self._wait() + continue + except Exception as exc: + self._publish( + "assistant_failed", + { + **latest_stream_update, + **event_context, + "error": str(exc), + }, + ) + raise + if call_result.ok is False: + raise RuntimeError(call_result.error or "Model API request failed.") + if not rows: + raise RuntimeError("EvaluatorConstructionAgent returned no usable response") + response = rows[0] + content, calls, message = response.content, response.tool_calls, response.message + self.buffer.append(message) + assistant_event = { + "kind": "assistant", + "timestamp": time.time(), + "content": content or "", + "message": json_value(message), + "tool_calls": [ + {"name": call.name, "params": json_value(call.params), "id": call.id} + for call in calls + ], + } + timeline_events.append(assistant_event) + self._publish( + "assistant_completed", + { + **event_context, + "content": content or "", + "reasoning": message.get("reasoning", ""), + "message": json_value(message), + "tool_calls": assistant_event["tool_calls"], + "usage": { + "token": call_result.token_usage, + "price": call_result.money_usage, + }, + }, + ) + if not calls: + if update_needs_test: + self._append_prompt( + { + "role": "user", + "content": ( + "Completion is blocked: call validate_evaluator after the latest evaluator " + "file edit. Repair the evaluator until validation succeeds and every " + "evaluator-specific metric it returns is a finite number." + ), + } + ) + self._wait() + continue + if self._wait(): + continue + return { + "message": content or "", + "tool_events": tool_events, + "timeline_events": timeline_events, + "streamed": True, + } + results = [] + for call in calls: + try: + tool = self.tool_box[call.name] + except KeyError: + tool = None + self._publish( + "tool_started", + { + "call": { + "name": call.name, + "params": json_value(call.params), + "id": call.id, + }, + }, + ) + if tool is None: + results.extend(self.execute_action([call])) + else: + with self.interaction_manager.cancellable(tool.cancel): + results.extend(self.execute_action([call])) + completed = [ + { + "tool": call.name, + "ok": result.ok, + "call": {"name": call.name, "params": json_value(call.params), "id": call.id}, + "result": { + "ok": result.ok, + "result": json_value(result.result), + "result_str": result.result_str, + "meta_data": json_value(result.meta_data), + }, + "timestamp": float(result.meta_data.get("timestamp", time.time())), + } + for call, result in zip(calls, results) + ] + tool_events.extend(completed) + timeline_events.extend({"kind": "tool_result", **event} for event in completed) + for event in completed: + self._publish("tool_completed", event) + self.buffer.extend(self.tool_box.format_tool_result_messages(calls, results)) + if self.interaction_manager.is_interrupting: + self._record_force() + self._check_stop() + for call, result in zip(calls, results): + if call.name == "workspace_code_executor" and result.ok: + update_needs_test = True + elif ( + call.name == "validate_evaluator" + and update_needs_test + and test_has_finite_custom_metrics(result) + ): + update_needs_test = False + self._wait() + raise RuntimeError( + f"EvaluatorConstructionAgent exceeded the {self.max_steps}-step repair limit" + ) diff --git a/src/sr_harness/agents/sr_agent.py b/src/sr_harness/agents/sr_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..ea4a42c031baa6bdcfa0d1ea7a94c6e3b2a838a1 --- /dev/null +++ b/src/sr_harness/agents/sr_agent.py @@ -0,0 +1,1428 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""基类 Agent 和 Buffer 的定义。 + +提供符号回归 Agent 的基础框架,包括主循环 Pipeline 和工具调用机制。 +""" +from __future__ import annotations +import json +import logging +import numpy as np +from pathlib import Path +from copy import deepcopy +from itertools import islice +from collections import defaultdict +from contextlib import contextmanager +from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, TypeAlias +from ..api import BaseAPI +from ..tools import BaseTool +from ..parser import BaseParser +from ..skills import SkillManager +from ..runtime import ModelRouter +from ..utils import ParallelTimer, NamedTimer, Timer +from ..utils import format_pareto_front, render_markdown, tag2ansi, setup_logging +from ..core import APICallSample, AgentContext, CandidateRecord, ParentLink, SearchRunState, ToolCall, ToolCallResult +from .agent import Agent + +_logger = logging.getLogger(f'sr_harness.{__name__}') + +Message: TypeAlias = dict[str, Any] +Usage: TypeAlias = dict[str, Any] + + +class SRAgent(Agent): + """Agent that performs an R-C-L-K symbolic-regression search.""" + + DEFAULT_TOOLS = ( + "statistics_analysis", + "relationship_analysis", + "evaluate_formula", + "submit_formula", + "evaluate_code", + "polynomial_fit", + "power_law_fit", + "rational_fit", + "constant_fit", + "read_skill", + "create_skill", + "edit_skill", + "edit_tool", + "call_sindy", + "call_pysr", + "web_search", + "web_fetch", + "read_pdf", + ) + + # Construction and public lifecycle + + def __init__( + self, + llm_provider: str, + llm_model: str, + tools: list[str] | None = None, + skills: List[str] | None = None, + verbose: bool = False, + tool_parser: str | BaseParser = 'openai', + save_path: Optional[str] = None, + run_id: str | None = None, + local_sample_size: int = 1, + max_refinement_depth: int = 20, + global_width: int = 1, + max_restart_loop: int = 1, + restart_top_k: int = 1, + llm_max_tokens: int = 4096, + max_workers: int = 0, + validation_fraction: float = 0.2, + split_by: str = "random", + split_ood_variable: str | None = None, + split_random_state: int = 42, + ranking_metric: str = "mse", + larger_is_better: bool = False, + force_initial_diagnostics: bool = False, + auto_routing: bool = True, + strong_llm_provider: str | None = None, + strong_llm_model: str | None = None, + context: AgentContext | None = None, + skill_manager: SkillManager | None = None, + ) -> None: + """初始化 Agent。 + + Args: + llm_provider: LLM 提供商名称(如 "openai", "siliconflow")。 + llm_model: 模型名称(如 "gpt-4o-mini")。 + tools: 可用工具列表。None 表示使用 ``DEFAULT_TOOLS``。 + skills: 可供 Agent 读取的 skill 名称。None 表示使用全部 skill。 + verbose: 是否启用详细日志(DEBUG 级别)。 + tool_parser: 工具解析器,可以是字符串('text', 'json')或 BaseParser 实例。 + save_path: 日志文件保存路径。None 表示不保存到文件。 + run_id: 本次运行的全局唯一标识。None 表示自动生成。 + local_sample_size: 每轮生成的候选解数量。 + max_refinement_depth: 最大迭代次数。 + global_width: 每个 restart turn 中独立对话分支数量。 + max_restart_loop: best-solution restarts 次数 + restart_top_k: 下一轮 restart prompt 中保留的历史最佳结果数量。 + llm_max_tokens: 每次 LLM 响应的最大 token 数。 + max_workers: 并行执行工具调用的最大工作进程数。0 表示不使用并行。 + validation_fraction: 验证集比例;验证集结果会展示给 Agent。设为 0 可关闭。 + split_by: 验证集划分方式。"random" 表示随机划分;"ood" 要求通过 + split_ood_variable 显式指定排序变量。 + split_ood_variable: OOD 划分使用的变量名;随机划分时可留空。 + split_random_state: 数据划分的随机种子。 + ranking_metric: 候选公式排序所用的指标键;默认使用 mse。 + larger_is_better: 排序指标是否越大越好;默认按越小越好排序。 + force_initial_diagnostics: 是否在每个对话分支的 L=1 请求 LLM 前,强制执行 + statistics_analysis、relationship_analysis 和读取 discover-symbolic-laws skill。 + auto_routing: 是否根据任务复杂度在基础与强模型后端之间自动路由。 + strong_llm_provider: 复杂任务使用的后端;默认沿用 llm_provider。 + strong_llm_model: 复杂任务使用的模型。None 表示仅使用基础模型。 + context: 与其它 Agent 共享的数据和工作区上下文。None 表示新建独立上下文。 + skill_manager: Skill 注册表。None 表示使用临时的自定义 skill 目录。 + """ + # 配置日志:如果用户尚未配置,则根据 verbose 和 save_path 自动配置 + log_path = Path(save_path) / "info.log" if save_path is not None else None + setup_logging( + info_level='debug' if verbose else 'info', + save_path=log_path, + force=False, + ) + + tool_cls_list = [] + for tool_cls in BaseTool.load_tool_classes(): + # Custom tools are rediscovered and reloaded from this Agent's + # SkillManager below. Exclude stale process-global class objects. + if getattr(tool_cls, "source_path", None) is not None: + continue + tool_cls_list.append(tool_cls) + + # 参数 + self.llm_provider = llm_provider + self.llm_model = llm_model + self.tool_parser = tool_parser + self.local_sample_size = local_sample_size + self.max_refinement_depth = max_refinement_depth + self.global_width = global_width + self.max_restart_loop = max_restart_loop + self.restart_top_k = restart_top_k + self.llm_max_tokens = llm_max_tokens + self.max_workers = max_workers + if not 0 <= validation_fraction < 1: + raise ValueError("validation_fraction must be in [0, 1).") + if split_by not in {"random", "ood"}: + raise ValueError("split_by must be either 'random' or 'ood'.") + if split_ood_variable is not None and ( + not isinstance(split_ood_variable, str) or not split_ood_variable.strip() + ): + raise ValueError("split_ood_variable must be None or a non-empty string.") + self.validation_fraction = validation_fraction + self.split_by = split_by + self.split_ood_variable = split_ood_variable + self.split_random_state = split_random_state + self.ranking_metric = ranking_metric + self.larger_is_better = larger_is_better + self.force_initial_diagnostics = force_initial_diagnostics + self.auto_routing = auto_routing + self.strong_llm_provider = ( + llm_provider if strong_llm_provider is None else strong_llm_provider + ) + self.strong_llm_model = strong_llm_model + self.model_router = ModelRouter( + enabled=auto_routing, + base_provider=llm_provider, + base_model=llm_model, + strong_provider=self.strong_llm_provider, + strong_model=strong_llm_model, + ) + self._task_route_score = 0 + self._task_route_reasons: list[str] = [] + self._strong_api = None + self._last_model_route = None + + # 关键组件 + self.context = context if context is not None else AgentContext() + self.skill_manager = skill_manager or SkillManager(workspace=self.context.workspace) + requested_tool_names = tuple(self.DEFAULT_TOOLS if tools is None else tools) + requested_tools = set(requested_tool_names) + initially_selected = [ + tool_cls for tool_cls in tool_cls_list + if tool_cls.metadata.name in requested_tools + ] + self.skill_manager.register_tool_docs(initially_selected) + tool_cls_list += BaseTool.discover_custom_tools(self.skill_manager) + self.available_tool_classes = { + tool_cls.metadata.name: tool_cls for tool_cls in tool_cls_list + } + if unknown_tools := requested_tools - self.available_tool_classes.keys(): + raise ValueError(f"Unknown tools: {', '.join(sorted(unknown_tools))}") + self.tool_cls_list = [ + self.available_tool_classes[name] for name in requested_tool_names + ] + registered_skills = self.skill_manager.load_skills() + self.skill_manager.register_tool_docs([ + tool_cls for tool_cls in self.tool_cls_list + if (doc := tool_cls.get_doc()) is not None and doc["name"] not in registered_skills + ]) + available_skills = self.skill_manager.load_skills() + tool_skill_names = { + doc["name"] + for tool_cls in self.tool_cls_list + if (doc := tool_cls.get_doc()) is not None + } + requested_skills = ( + set(skills) | tool_skill_names + if skills is not None + else set(available_skills) + ) + if unknown_skills := requested_skills - available_skills.keys(): + raise ValueError(f"Unknown skills: {', '.join(sorted(unknown_skills))}") + self.enabled_skills = requested_skills + if self.force_initial_diagnostics: + required_tools = {"statistics_analysis", "relationship_analysis", "read_skill"} + enabled_tools = {tool_cls.metadata.name for tool_cls in self.tool_cls_list} + if missing_tools := required_tools - enabled_tools: + raise ValueError( + "force_initial_diagnostics requires these enabled tools: " + + ", ".join(sorted(missing_tools)) + ) + if "discover-symbolic-laws" not in self.enabled_skills: + raise ValueError( + "force_initial_diagnostics requires the 'discover-symbolic-laws' skill." + ) + self.tool_box = None # 延迟实例化,因为需要 context 上下文 + self.api = None # 延迟实例化, 因为需要 tools 工具列表 + + # 附属组件 + self.total_timer = Timer() # 总用时统计 + self.named_timer = NamedTimer() # 细粒度用时统计 + self.token_counter = ParallelTimer(unit='token') # token 统计 + self.money_counter = ParallelTimer(unit='$') # 费用统计 + self.tools_counter = ParallelTimer(unit='call') # 工具调用统计 + self.save_path = save_path + self.context.args.validation_fraction = validation_fraction + self.context.args.split_by = split_by + self.context.args.split_ood_variable = split_ood_variable + self.context.args.split_random_state = split_random_state + self.context.invalidate_splits() + self.run_state = SearchRunState( + save_path=save_path, + ranking_metric=ranking_metric, + larger_is_better=larger_is_better, + agent_metadata={ + "class": self.__class__.__name__, + "llm_provider": llm_provider, + "llm_model": llm_model, + "tool_parser": str(tool_parser), + "local_sample_size": local_sample_size, + "max_refinement_depth": max_refinement_depth, + "global_width": global_width, + "max_restart_loop": max_restart_loop, + "restart_top_k": restart_top_k, + "max_workers": max_workers, + }, + run_id=run_id, + ) + + _logger.info(f"Initialized {self.__class__.__name__}") + + def run(self, X: Dict[str, np.ndarray], y: Dict[str, np.ndarray] | np.ndarray, problem_description: str) -> Dict[str, Any]: + """Run the configured operation. + + Args: + X: Input feature arrays keyed by variable name. + y: Target data or target expression. + problem_description: Natural-language description of the discovery task. + + Returns: + Dict[str, Any]: The operation result. + """ + if not isinstance(y, dict): + y = {"target": y} + + target = next(iter(y)) + supplied_data = X | y + + def existing_value(name: str): + if name in self.context.data: + return self.context.data[name] + return None + + data_changed = not self.context.data or any( + (current := existing_value(name)) is None + or not np.array_equal(current, value) + for name, value in supplied_data.items() + ) + if data_changed: + self.context.commit_data( + supplied_data, + target=target, + features=list(X), + variable_descriptions=self.context.variable_descriptions, + ) + else: + self.context.target = target + self.context.invalidate_splits() + self._active_X = X + self._active_y = y + self._data_revision = int(self.context.args.data_revision) + self.context.args.llm_provider = self.llm_provider + self.context.args.llm_model = self.llm_model + self.context.args.llm_max_tokens = self.llm_max_tokens + self.context.args.skill_manager = self.skill_manager + self.context.args.enabled_skills = sorted(self.enabled_skills) + with self.prepare_tool_context(self.context) as tool_context: + self.initialize_with_context(tool_context) + description = self.tool_box.format_tools() + if isinstance(description, list): + description = json.dumps(description, indent=2) + _logger.debug( + f"Using {self.tool_parser} as tool parser. " + f"Tools will be described as follows:\n{description}" + ) + try: + return self.search(X, y, problem_description) + except KeyboardInterrupt as error: + coordinate = self.run_state.latest_coordinate + error.partial_result = self.build_search_result( + "interrupted", + R=coordinate.R if coordinate else None, + C=coordinate.C if coordinate else None, + L=coordinate.L if coordinate else None, + ) + raise + except Exception as error: + coordinate = self.run_state.latest_coordinate + error.partial_result = self.build_search_result( + "failed", + R=coordinate.R if coordinate else None, + C=coordinate.C if coordinate else None, + L=coordinate.L if coordinate else None, + ) + raise + + @contextmanager + def prepare_tool_context(self, tool_context: AgentContext) -> Iterator[AgentContext]: + """Prepare resources and context shared by initialized tools. + + Args: + tool_context: Shared context used to initialize tools. + + Yields: + The context to bind to initialized tools. + """ + yield tool_context + + # Search orchestration + + def search(self, X: Dict[str, np.ndarray], y: Dict[str, np.ndarray], problem_description: str) -> Dict[str, Any]: + """Run the R-C-L search after data, tools, parser, and API are initialized. + + Each refinement step builds the prompt, requests the model, executes tools, + records the search node, collects candidates, updates the conversation, and + evaluates the termination hook. + + Args: + X: Input feature arrays keyed by variable name. + y: Target data or target expression. + problem_description: Natural-language description of the discovery task. + + Returns: + Dict[str, Any]: The operation result. + """ + ## 开始迭代 + self.total_timer.clear(reset_last_add_time=True) + self.named_timer.clear(reset_last_add_time=True) + R = 1 + while R <= self.max_restart_loop: # R 次 best-solution restart + _logger.info(f"Start Restart Loop (R={R}/{self.max_restart_loop})") + + # 用平凡结果或者历史最佳结果构建新的分支 buffer + restart_records = self.run_state.ranked_candidates()[:self.restart_top_k] + initial_buffer = self.create_initial_buffer(problem_description, X, y, restart_records) + initial_node_parents = {record.node_id: "restart_seed" for record in restart_records} + self.named_timer.add("create_initial_buffer") + C = 1 + next_restart = False + while C <= self.global_width: # C 次独立重复对话 + _logger.info( + f"(R={R}/{self.max_restart_loop}) × " + f"Global Branch (C={C}/{self.global_width})" + ) + + # 用 initial prompt 初始化 buffer,node_parents 记录当前 buffer 的父节点 + buffer = deepcopy(initial_buffer) + node_parents = deepcopy(initial_node_parents) + self.named_timer.add("init_buffer") + + L = 1 + while L <= self.max_refinement_depth: # L 轮对话迭代 + _logger.info( + f"(R={R}/{self.max_restart_loop}) × " + f"(C={C}/{self.global_width}) × " + f"Refinement Step (L={L}/{self.max_refinement_depth})" + ) + + # Step 1: 根据 Buffer 创建 Prompt + transition = self.prepare_iteration(buffer, R=R, L=L, C=C) + if transition == "next_r": + next_restart = True + break + if transition == "next_c": + break + prompt = self.prepare_model_messages(buffer, R=R, L=L, C=C) + self.set_messages(prompt) + self.named_timer.add("prepare_model_messages") + + # Step 2: 请求 LLM 得到 Content、Tool Calls 和 Message + response_list, usage = self.request_llm(prompt, R=R, L=L, C=C) + self.named_timer.add("request_llm") + + # Step 3: 执行 Tool Calls 得到 Results + results_list = self.execute_tool_calls(response_list, R=R, L=L, C=C) + self.named_timer.add("execute_tool_calls") + + # Step 4: 记录当前搜索节点 + self.record_search_iteration( + response_list, results_list, node_parents, prompt, usage, R, L, C, + ) + self.named_timer.add("record_search_iteration") + + # Step 5: 验证并收集候选公式 + self.collect_candidates(response_list, results_list, R=R, L=L, C=C) + self.named_timer.add("collect_candidates") + + # Step 6: 更新对话 Buffer 和父节点关系 + buffer, node_parents = self.update_conversation( + buffer, response_list, results_list, node_parents, R, L, C, + ) + self.named_timer.add("update_conversation") + + # Step 7: 打印本轮日志 + self.log_info(response_list, R=R, L=L, C=C) + self.named_timer.add("log_info") + self.total_timer.add() + + # Step 8: 判断是否终止当前搜索 + status = self.finish_iteration(buffer, R=R, L=L, C=C) + if status is not None: + _logger.note("Early stopping triggered. Returning best result.") + return self.build_search_result(status, R=R, L=L, C=C) + L += 1 + if next_restart: + break + C += 1 + R += 1 + + _logger.note("Finished all iterations. Returning best result.") + coordinate = self.run_state.latest_coordinate + return self.build_search_result( + "completed", + R=coordinate.R if coordinate else None, + C=coordinate.C if coordinate else None, + L=coordinate.L if coordinate else None, + ) + + def _split_data(self, X: Dict[str, np.ndarray], y: Dict[str, np.ndarray]): + """Split aligned arrays into train and validation data mappings.""" + self.context.args.validation_fraction = self.validation_fraction + self.context.args.split_by = self.split_by + self.context.args.split_ood_variable = getattr( + self, "split_ood_variable", self.context.args.split_ood_variable + ) + self.context.args.split_random_state = self.split_random_state + target = next(iter(y)) + data = X | y + variable_axes = { + name: axes for name, axes in self.context.variable_axes.items() if name in data + } + for axis in {axis for axes in variable_axes.values() for axis in axes}: + if axis in self.context.data: + data.setdefault(axis, self.context.data[axis]) + variable_structures = { + name: structure + for name, structure in self.context.variable_structures.items() + if name in data and structure in data + } + split_context = AgentContext( + args=self.context.args, + data=data, + target=target, + variable_descriptions={name: self.context.variable_descriptions.get(name, "") for name in data}, + variable_axes=variable_axes or None, + variable_structures=variable_structures, + relation_names=self.context.relation_names & set(data), + num_nodes=self.context.num_nodes if self.context.relation_names & set(data) else None, + evaluator=self.context.evaluator, + workspace=self.context.workspace, + ) + splits = split_context.evaluator.split(split_context) + return splits["train"].data, splits["validation"].data + + # Prompt and conversation-buffer lifecycle + + def create_initial_buffer(self, problem_description: str, X: dict[str, np.ndarray], y: dict[str, np.ndarray], restart_records: list[CandidateRecord]) -> list[Message]: + """Combine initial prompts with the first progress message for a branch. + + Args: + problem_description: Natural-language description of the discovery task. + X: Input feature arrays keyed by variable name. + y: Target data or target expression. + restart_records: Ranked candidates used to seed a restart. + + Returns: + Initial branch buffer including the first progress message. + """ + self._task_route_score, self._task_route_reasons = self.model_router.assess( + problem_description, + feature_count=len(X), + ) + initial_buffer = [ + *self.create_initial_prompt_messages( + problem_description, X, y, restart_records, + ), + self.build_progress_message(L=0), + ] + self.on_buffer_messages_added(initial_buffer) + return initial_buffer + + def create_initial_prompt_messages(self, problem_description: str, X: dict[str, np.ndarray], y: dict[str, np.ndarray], restart_records: list[CandidateRecord]) -> list[Message]: + """Create finalized system and user messages without buffer metadata. + + Args: + problem_description: Natural-language discovery task. + X: Feature arrays keyed by variable name. + y: Target arrays keyed by variable name. + restart_records: Ranked candidates used to seed a restart. + + Returns: + Finalized system and user messages. + """ + messages = [{ + "role": "system", + "content": self.create_initial_system_prompt(restart_records), + }, { + "role": "user", + "content": self.create_initial_user_prompt( + problem_description, X, y, restart_records, + ), + }] + return self.customize_initial_prompts(messages, X=X, y=y) + + @staticmethod + def _build_mse_goal(restart_records) -> str: + """Describe the next MSE objective from the current restart seeds.""" + if not restart_records: + return "You should try to find a simple formula that fits the data with an MSE of EXACTLY 0." + best_mse = restart_records[0].metric("mse", "train") + if best_mse > 0: + return ( + f"Your target is to find a formula with MSE < {best_mse * 0.1:.6g} " + f"(10x better than the previous best MSE of {best_mse:.6g})." + ) + return ( + "The previous round already achieved MSE = 0. " + "Try to find a simpler formula that also achieves MSE = 0." + ) + + def create_initial_system_prompt(self, restart_records: list[CandidateRecord]) -> str: + """Create the initial system prompt independently of the branch buffer. + + Args: + restart_records: Ranked candidates used to set the next objective. + + Returns: + System-prompt text. + """ + mse_goal = self._build_mse_goal(restart_records) + return ( + "You are a Symbolic Regression Agent. Your goal is to discover mathematical formulas " + "that explain the relationship between feature variables and the target variable. " + "DO NOT be satisfied with an accurate but complex formula — prefer simple, interpretable expressions. " + f"You have at most {self.max_refinement_depth} refinement rounds in each conversation branch. " + "Plan tool use within this budget: use early rounds for targeted exploration, keep concrete " + "candidate formulas as the budget shrinks, and avoid open-ended searches near the end. " + "If possible, try calling multiple tools in each round. " + f"{mse_goal} Please start by analyzing the data to understand the relationship between features and target." + ) + + def create_initial_user_prompt(self, problem_description: str, X: dict[str, np.ndarray], y: dict[str, np.ndarray], restart_records: list[CandidateRecord]) -> str: + """Create the initial user prompt independently of the branch buffer. + + Args: + problem_description: Natural-language discovery task. + X: Feature arrays keyed by variable name. + y: Target arrays keyed by variable name. + restart_records: Ranked candidates included as restart evidence. + + Returns: + User-prompt text. + """ + content = ( + f"{problem_description}\n\n" + f"- Feature names: {list(X.keys())}\n" + f"- Target name: {next(iter(y))}\n" + ) + if not restart_records: + return content + "Please start by analyzing the data to understand the relationship between features and target." + + content += ( + "\n--- Previously Explored Formulas (from best to worst) ---\n" + "Use these as inspiration. Try to improve upon them or find simpler alternatives.\n\n" + ) + for record in restart_records: + mse = record.metric("mse", "validation") + if mse is None: + mse = record.metric("mse", "train") + r2 = record.metric("r2", "validation") + if r2 is None: + r2 = record.metric("r2", "train") + metric_text = f"MSE={mse:.6g}" if mse is not None else "MSE=unavailable" + if r2 is not None: + metric_text += f", R²={r2:.6g}" + content += f" • Formula: {record.formula}\n {metric_text}\n\n" + return content + ( + "---\n\nAnalyze why the previous best formulas may not be perfect, and try a different " + "approach or structure to improve the result." + ) + + def customize_initial_prompts(self, messages: list[Message], *, X: dict[str, np.ndarray], y: dict[str, np.ndarray]) -> list[Message]: + """Customize finalized initial prompts before buffer insertion. + + Args: + messages: Initial system and user messages. + X: Feature arrays keyed by variable name. + y: Target arrays keyed by variable name. + + Returns: + Messages to insert into the branch buffer. + """ + return messages + + def on_buffer_messages_added(self, messages: list[Message], **coordinate: int) -> None: + """Observe messages after they enter a conversation buffer. + + Args: + messages: Newly appended messages. + **coordinate: Optional R/C/L search coordinate. + """ + + def _append_buffer_messages(self, buffer, messages, **coordinate: int) -> None: + """Append messages and notify subclasses through one mutation path.""" + messages = list(messages) + buffer.extend(messages) + self.on_buffer_messages_added(messages, **coordinate) + + def prepare_model_messages(self, buffer: List[Dict[str, Any]], R: int, L: int, C: int) -> List[Dict[str, Any]]: + """Prepare the messages sent to the model for one iteration. + + Args: + buffer: Conversation history buffer. + R: One-based restart index. + L: One-based refinement-step index. + C: One-based conversation-branch index. + + Returns: + List[Dict[str, Any]]: The operation result. + """ + if self.force_initial_diagnostics and L == 1: + # Persist the evidence in the branch buffer so later refinement + # rounds retain the diagnostics and skill instructions. + self._append_buffer_messages( + buffer, + [self.run_initial_diagnostics(R=R, L=L, C=C)], + R=R, + C=C, + L=L, + ) + prompt = deepcopy(buffer) + _logger.info(f"Built prompt with {len(prompt)} messages.") + logs = [] + for msg in prompt: + msg = msg.copy() + order = ['role', 'tool_call_id', 'reasoning', 'content', 'tool_call'] + order = [k for k in order if k in msg] + [k for k in msg if k not in order] + msg = { k: msg[k] for k in order } + + log = '' + log += tag2ansi(f"[red bold][{msg.pop('role')}][reset]") + for k, v in msg.items(): + if k == 'content': + v = render_markdown(v or "(empty)") + v = str(v).strip() + if '\n' in v: + v = '\n '.join(['', *v.splitlines()]) + log += tag2ansi(f"\n [blue]{k}[reset]") + '=' + v + logs.append(log) + _logger.debug("Messages:\n" + '\n---\n'.join(logs)) + return prompt + + def prepare_iteration(self, buffer: List[Dict[str, Any]], R: int, L: int, C: int) -> str | None: + """Apply mode-specific control changes before constructing this iteration's prompt. + + Args: + buffer: Conversation history buffer. + R: One-based restart index. + L: One-based refinement-step index. + C: One-based conversation-branch index. + + Returns: + str | None: The operation result. + """ + return None + + def refresh_data(self) -> dict[str, Any] | None: + """Apply a newly committed shared-data revision and describe the change.""" + revision = int(self.context.args.data_revision) + if revision == self._data_revision: + return None + if self.context.target is None or not self.context.feature_names(): + raise ValueError("The updated context does not define a target and features") + + def selected_value(name: str) -> np.ndarray: + if name in self.context.data: + return self.context.data[name] + raise ValueError(f"The selected variable or axis no longer exists: {name}") + + X = {name: selected_value(name) for name in self.context.feature_names()} + y = {self.context.target: selected_value(self.context.target)} + self.context.invalidate_splits() + self._active_X.clear() + self._active_X.update(X) + self._active_y.clear() + self._active_y.update(y) + previous_revision = self._data_revision + self._data_revision = revision + descriptions = { + name: description + for name in [self.context.target, *self.context.feature_names()] + if (description := self.context.variable_descriptions.get(name, "").strip()) + } + return { + "previous_revision": previous_revision, + "revision": revision, + "target": self.context.target, + "features": list(self.context.feature_names()), + "variable_descriptions": descriptions, + } + + def finish_iteration(self, buffer: List[Dict[str, Any]], R: int, L: int, C: int) -> str | None: + """Return a terminal status when the current search should stop. + + Args: + buffer: Conversation history buffer. + R: One-based restart index. + L: One-based refinement-step index. + C: One-based conversation-branch index. + + Returns: + str | None: The operation result. + """ + best_candidate = self.best_candidate() + if ( + best_candidate is not None and best_candidate.metric("mse", "train") == 0.0 + ): + return "early_stopped" + return None + + def run_initial_diagnostics(self, R: int, L: int, C: int) -> Dict[str, str]: + """Run the mandatory branch-opening diagnostics and format them for the LLM. + + Args: + R: One-based restart index. + L: One-based refinement-step index. + C: One-based conversation-branch index. + + Returns: + Dict[str, str]: The operation result. + """ + calls = [ + ToolCall(name="statistics_analysis", params={}), + ToolCall(name="relationship_analysis", params={}), + ToolCall(name="read_skill", params={"name": "discover-symbolic-laws"}), + ] + results = self.execute_action(calls) + self.record_tool_calls(calls, results, R=R, L=L, C=C, forced=True) + failures = [ + f"{call.name}: {result.result_str}" + for call, result in zip(calls, results) + if not result.ok + ] + if failures: + raise RuntimeError( + "Required initial diagnostic tool call(s) failed:\n" + "\n".join(failures) + ) + sections = [ + f"## {call.name}\n{result.result_str}" + for call, result in zip(calls, results) + ] + return { + "role": "user", + "content": ( + "[Required initial diagnostics]\n" + "The framework ran these mandatory tools before your first response in this branch. " + "Use their evidence and the skill instructions to plan the search.\n\n" + + "\n\n".join(sections) + ), + } + + # Model and tool execution + + def request_llm(self, prompt: List[Dict[str, Any]], R: int, L: int, C: int, callback: Callable[[dict[str, Any]], None] | None = None) -> tuple[list[APICallSample], Usage | None]: + """Run the ``request llm`` operation. + + Args: + prompt: Prompt messages sent to the model. + R: One-based restart index. + L: One-based refinement-step index. + C: One-based conversation-branch index. + callback: Optional callback invoked for model-call progress updates. + + Returns: + Parsed model responses and recorded usage data. + """ + response_list = [] + route = self.model_router.route( + task_score=self._task_route_score, + task_reasons=self._task_route_reasons, + refinement_step=L, + ) + self._last_model_route = route + api = self.api + if route.tier == "strong": + if self._strong_api is None: + self._strong_api = BaseAPI.create( + route.provider, + model=route.model, + tool_box=self.tool_box, + environment=getattr(self.context.args, "api_environment", None), + save_path=self.save_path, + ) + api = self._strong_api + _logger.info( + f"Model route: tier={route.tier}, backend={route.provider}/{route.model}, " + f"score={route.score}, reason={route.reason}" + ) + llm_result = api( + prompt, + n=self.local_sample_size, + max_tokens=self.llm_max_tokens, + callback=callback, + ) + for K, response in enumerate(llm_result, 1): # K 次重复采样 + content = response.content + tool_calls = response.tool_calls + response_list.append(response) + content_for_log = render_markdown(content or "(empty)").strip() + tool_calls_for_log = '\n'.join(str(tool_call) for tool_call in tool_calls) + content_for_log = '\n '.join(['', *content_for_log.splitlines()]) if '\n' in content_for_log else content_for_log + tool_calls_for_log = '\n '.join(['', *tool_calls_for_log.splitlines()]) if '\n' in tool_calls_for_log else tool_calls_for_log + _logger.info( + f"(R={R}/{self.max_restart_loop}) × (C={C}/{self.global_width}) × (L={L}/{self.max_refinement_depth}) × Local Sample (K={K}/{self.local_sample_size})\n" + f"LLM response content: {content_for_log}\n" + f"LLM tool calls: ({len(tool_calls)} tool calls)" + ) + _logger.debug(tool_calls_for_log) + usage = self.record_llm_result(llm_result, R=R, L=L, C=C) + if llm_result.ok is False: + raise RuntimeError(llm_result.error or "Model API request failed.") + return response_list, usage + + def execute_tool_calls(self, response_list: list[APICallSample], R: int, L: int, C: int) -> list[list[ToolCallResult]]: + """Execute tool calls from model responses and preserve sample grouping. + + Args: + response_list: Model responses for the current step. + R: One-based restart index. + L: One-based refinement-step index. + C: One-based conversation-branch index. + + Returns: + Tool results grouped by local model sample. + """ + # 合并 - 调用 - 分割 + all_tool_calls = [] + num_tool_calls = [] + for response in response_list: + all_tool_calls.extend(response.tool_calls) + num_tool_calls.append(len(response.tool_calls)) + if self.max_workers and len(all_tool_calls) > 1: + all_results = self.execute_action_parallel(all_tool_calls, max_workers=self.max_workers) + else: + all_results = self.execute_action(all_tool_calls) + results_iter = iter(all_results) + results_list = [list(islice(results_iter, l)) for l in num_tool_calls] + # 打印工具调用结果 + all_results_for_log = '\n'.join(str(result) for result in all_results or []) + all_results_for_log = '\n '.join(['', *all_results_for_log.splitlines()]) if '\n' in all_results_for_log else all_results_for_log + _logger.debug(f"Action result: {all_results_for_log}") + self.record_tool_calls(all_tool_calls, all_results, R=R, L=L, C=C) + return results_list + + def record_tool_calls( + self, tool_calls: List[ToolCall], + results: List[ToolCallResult], + R: int, L: int, C: int, forced: bool = False + ) -> None: + """Persist tool calls from either the LLM or framework-enforced diagnostics. + + Args: + tool_calls: Tool calls returned by the model. + results: Result records to process. + R: One-based restart index. + L: One-based refinement-step index. + C: One-based conversation-branch index. + forced: The forced value. + """ + if self.save_path is None: + return + with open(Path(self.save_path) / 'tool_calls.jsonl', 'a') as f: + for tool_call, result in zip(tool_calls, results): + json.dump({ + "progress": self.format_progress(R, L, C), + "forced": forced, + 'name': tool_call.name, + 'params': tool_call.params, + "ok": result.ok, + "result": result.result, + "result_str": result.result_str, + "meta_data": result.meta_data, + }, f) + f.write('\n') + + def update_conversation( + self, + buffer: List[Dict[str, Any]], + response_list: List[Tuple[str, List[ToolCall], Dict[str, Any]]], + results_list: List[List[ToolCallResult]], + node_parents: Dict[str, str], R: int, L: int, C: int + ) -> tuple[list[Message], dict[str, str]]: + """Update buffer. + + Args: + buffer: Conversation history buffer. + response_list: Model responses for the current step. + results_list: Tool results aligned with model responses. + node_parents: The node parents value. + R: One-based restart index. + L: One-based refinement-step index. + C: One-based conversation-branch index. + + Returns: + Updated conversation buffer and parent-link mapping. + """ + # 如果没有成功的回复,跳过本轮更新 + if len(response_list) == 0: + return buffer, node_parents + node_parents = {} + # 选择产生了最佳排序指标的 tool_call 所在的 response 分支 + selected_K = 1 + selected_priority = float('inf') + for K, results in enumerate(results_list, 1): + for result in results: + if (priorities := self.candidate_sort_key(result.result)) is not None and priorities[0] < selected_priority: + selected_K = K + selected_priority = priorities[0] + node_parents[self.run_state.node_id(R=R, C=C, L=L, K=selected_K)] = 'continuation' + _logger.info(f"Selected LLM branch: {selected_K}/{len(results_list)}") + selected_response = response_list[selected_K - 1] + tool_calls = selected_response.tool_calls + message = selected_response.message + results = results_list[selected_K - 1] + tool_calls = tool_calls.copy() + message = deepcopy(message) + results = results.copy() + # 将其他 (tool_call, result) pairs 中不涉及 formula & metrics 的 pair 也加入 buffer, 以免丢失有用信息 + for K, (extra_response, extra_results) in enumerate(zip(response_list, results_list), 1): + extra_tool_calls = extra_response.tool_calls + for tool_call, result in zip(extra_tool_calls, extra_results): + # 只考虑不涉及 formula & metrics 的工具调用结果 + if K == selected_K or result.get('data_split_results', {}).get('train', {}).get('metrics') is not None: + continue + tool_calls.append(tool_call) + results.append(result) + # 对于 openai parser, 将 extra_message['tool_calls'] 拼到 message 中 + if self.tool_parser == 'openai': + if not isinstance(message.get('tool_calls'), list): + message['tool_calls'] = [] + message['tool_calls'].append(tool_call.raw) + # 对于 non-openai parser, 将 tool_calls 拼到 content 中 + else: + message['content'] += "\n\n" + tool_call.raw_str + node_parents[self.run_state.node_id(R=R, C=C, L=L, K=K)] = 'context_merge' + # 将 message 和 (tool_call, result) pairs 加入 buffer + if tool_calls or (message.get('content') or '').strip() or message.get('reasoning'): + result_messages = ( + self.tool_box.format_tool_result_messages(tool_calls, results) + if tool_calls else [] + ) + self._append_buffer_messages( + buffer, + [message, *result_messages], + R=R, + C=C, + L=L, + ) + else: + _logger.warning("Skipping empty LLM response (no content nor tool calls).") + followup_messages = self.build_response_followup_messages( + response_list, results_list, R=R, L=L, C=C, + ) + if followup_messages: + self._append_buffer_messages( + buffer, followup_messages, R=R, C=C, L=L, + ) + process_message = self.build_progress_message(L) + self._append_buffer_messages(buffer, [process_message], R=R, C=C, L=L) + return buffer, node_parents + + def build_response_followup_messages( + self, + response_list: list[APICallSample], + results_list: list[list[ToolCallResult]], + *, + R: int, + L: int, + C: int, + ) -> list[Message]: + """Return framework messages to append after one model response. + + Args: + response_list: Model responses for the current iteration. + results_list: Tool results aligned with the model responses. + R: One-based restart index. + L: One-based refinement-step index. + C: One-based conversation-branch index. + + Returns: + Additional conversation messages, empty for the base agent. + """ + return [] + + # Progress prompts and candidate state + + def build_progress_message(self, L: int) -> dict[str, str]: + # 将当前搜索进度加入 buffer + """Build process message. + + Args: + L: One-based refinement-step index. + + Returns: + User-role message describing iteration state and the Pareto front. + """ + remaining_rounds = self.max_refinement_depth - L - 1 + progress_line = ( + f"Current progress: refinement round L={L+1}/{self.max_refinement_depth}. " + f"From now on, {remaining_rounds} refinement round(s) remain in this branch." + ) + if remaining_rounds > 1: + policy = ( + "Plan tool use within the remaining refinement budget. " + "Prefer targeted actions that can lead to a simpler and lower-MSE formula." + ) + elif remaining_rounds == 1: + policy = ( + "Only one refinement round remains after this response. Use at most a tightly targeted " + "tool call now, and preserve a concrete formula candidate so the next round can submit it." + ) + else: + policy = ( + "This is the final refinement round for this branch. Do not spend this response on " + "new data exploration, broad searches, or diagnostic-only evaluations. Submit or state " + "your best available target formula now using the final-answer mechanism available in " + "this environment, with a brief justification if text is required." + ) + pareto_front = self.get_pareto_front() + metric_path = f"validation.metrics.{self.ranking_metric}" + train_metric_path = f"train.metrics.{self.ranking_metric}" + metric_label = self.ranking_metric.replace("_", " ").upper() + pareto_front_str = format_pareto_front( + [self.candidate_to_dict(record) for record in pareto_front], + concise=True, + formula_max_length=160, + balance=( + ("validation.metrics.complexity", "minimize"), + (metric_path, "maximize" if self.larger_is_better else "minimize"), + ), + columns=("validation.metrics.complexity", metric_path, train_metric_path, "formula"), + title_mapping={ + "validation.metrics.complexity": "Complexity", + metric_path: f"Validation {metric_label}", + train_metric_path: f"Train {metric_label}", + "formula": "Formula", + }, + ) + diagnostics = [] + for record in pareto_front: + if eic := record.details.get("eic_diagnostics"): + diagnostics.append( + f"- {record.formula}: EIC={eic['eic']:.6g}; " + f"worst subtree={eic['worst_subtree']}" + ) + available_tools = {tool.metadata.name for tool in getattr(self, "tools", [])} + routing = [] + distinct_formulas = list(dict.fromkeys( + record.formula for record in self.run_state.ranked_candidates() + )) + if ( + len(distinct_formulas) >= 2 + and "delegate_subagent" in available_tools + and self.tools_counter.named_count.get("delegate_subagent", 0) == 0 + and remaining_rounds >= 1 + ): + routing.append( + "There are multiple viable formulas. Use delegate_subagent in " + "candidate_critique mode with the leading formulas and their metrics, then " + "run the cheapest discriminating check it recommends." + ) + diagnostics_text = ( + "\n\n[Candidate structural diagnostics]\n" + "\n".join(diagnostics) + if diagnostics else "" + ) + routing_text = ( + "\n\n[Specialist routing]\n" + "\n".join(f"- {item}" for item in routing) + if routing else "" + ) + return {"role": "user", "content": ( + f"[Iteration status]\n" + f"{progress_line} {policy}\n\n" + f"[Current Pareto Front]\n" + f"{pareto_front_str}" + f"{diagnostics_text}" + f"{routing_text}" + )} + + def push_candidate(self, record: CandidateRecord) -> None: + """Run the ``push candidate`` operation. + + Args: + record: Search or candidate record. + """ + if not self.run_state.push_candidate(record): + _logger.warning( + "Skipping candidate with missing or non-finite ranking metrics: " + f"{record.formula!r}" + ) + + def collect_candidates(self, response_list: list[APICallSample], results_list: list[list[ToolCallResult]], R: int, L: int, C: int) -> list[CandidateRecord]: + """Validate candidate tool results and add them to the run state. + + Args: + response_list: Model responses for the current step. + results_list: Tool results aligned with model responses. + R: One-based restart index. + L: One-based refinement-step index. + C: One-based conversation-branch index. + + Returns: + Candidates ranked under the configured metric. + """ + loader = [] + for K in range(1, len(response_list) + 1): + response = response_list[K - 1] + for _, res in zip(response.tool_calls, results_list[K - 1]): + if res.result.get('is_candidate'): + loader.append((K, res)) + + for K, res in loader: + train_metrics = res.result['data_split_results']['train']['metrics'] + if self.ranking_metric not in train_metrics or 'complexity' not in train_metrics: + _logger.warning( + "Skipping candidate from a tool that does not implement the active " + "ranking protocol %r: %r", + self.ranking_metric, + res.result.get("formula"), + ) + continue + details = { + key: value for key, value in res.result.items() + if key not in {"formula", "is_candidate", "all_formulas"} + } + record = CandidateRecord( + formula=res.result['formula'], + node_id=self.run_state.node_id(R=R, C=C, L=L, K=K), + details=details, + ) + if diagnostics := res.result.get("eic_diagnostics"): + record.details["eic_diagnostics"] = diagnostics + self.run_state.update_diagnostics(record.formula, diagnostics) + self.push_candidate(record) + # 对于 call_pysr 等工具,可能会返回多个 candidate formulas, 可以将它们全部加入 top-k + for formula_dict in res.result.get('all_formulas', []): + formula_metrics = formula_dict["data_split_results"]["train"]["metrics"] + if self.ranking_metric not in formula_metrics or 'complexity' not in formula_metrics: + _logger.warning( + "Skipping secondary candidate without active ranking metric %r: %r", + self.ranking_metric, + formula_dict.get("formula"), + ) + continue + record = CandidateRecord( + formula=formula_dict["formula"], + node_id=self.run_state.node_id(R=R, C=C, L=L, K=K), + details={key: value for key, value in formula_dict.items() if key != "formula"}, + ) + self.push_candidate(record) + return self.run_state.ranked_candidates() + + def log_info(self, response_list: list[APICallSample], R: int, L: int, C: int) -> None: + """Run the ``log info`` operation. + + Args: + response_list: Model responses for the current step. + R: One-based restart index. + L: One-based refinement-step index. + C: One-based conversation-branch index. + """ + new_count = defaultdict(int) + for response in response_list: + for tool_call in response.tool_calls: + new_count[tool_call.name] += 1 + tool_calls_str = ', '.join( + f"{name}: {count} ({new_count[name]} new)" + for name, count in self.tools_counter.named_count.items() + ) + if best_record := self.best_candidate(): + metric_label, metric_value = self.get_ranking_metric(best_record) + best_metric = f"{best_record.formula} ({metric_label}={metric_value:.6g})" + else: + best_metric = "None" + log = { + "Progress": self.format_progress(R, L, C), + "Best": best_metric, + "Tool Calls": tool_calls_str, + "Speed": self.total_timer.to_str('pace'), + "Time Usage": self.named_timer.to_str('time', 'pace', 'by_time'), + "Token Usage": self.token_counter.to_str('count', 'speed', 'by_count'), + "Price Usage": self.money_counter.to_str('count', 'speed', 'by_count'), + } + msg = "[gray] | [reset]".join(f"[blue]{k}[reset]={v}" for k, v in log.items()) + _logger.info(tag2ansi(msg)) + + # Persistence and result projection + + def record_llm_result(self, llm_result: Any, R: int, L: int, C: int) -> Dict[str, Any] | None: + """Record llm result. + + Args: + llm_result: The llm result value. + R: One-based restart index. + L: One-based refinement-step index. + C: One-based conversation-branch index. + + Returns: + Dict[str, Any] | None: The operation result. + """ + usage = { + "token": llm_result.token_usage, + "price": llm_result.money_usage, + } + for name, num in usage['token'].items(): + self.token_counter.add(name, num) + for name, num in usage['price'].items(): + self.money_counter.add(name, num) + if self.save_path is not None: + model_router = vars(self._last_model_route) if self._last_model_route is not None else None + with open(Path(self.save_path) / 'response.jsonl', 'a') as f: + json.dump({ + "responses": [response.message for response in llm_result.yielded], + "progress": self.format_progress(R, L, C), + "usage": usage, + "model_route": model_router + }, f) + f.write('\n') + return usage + + def record_search_iteration( + self, response_list: list[APICallSample], results_list: list[list[ToolCallResult]], + parent_nodes: dict[str, str], prompt: list[Message], usage: Usage | None, + R: int, L: int, C: int, + ) -> None: + """Record one visualization node for each local sample. + + Args: + response_list: Model responses for the current step. + results_list: Tool results aligned with model responses. + parent_nodes: Parent search nodes by response. + prompt: Prompt messages sent to the model. + usage: Token and price usage information. + R: One-based restart index. + L: One-based refinement-step index. + C: One-based conversation-branch index. + """ + parents: list[ParentLink] = [] + for parent_node_id, relation in parent_nodes.items(): + if relation not in {"restart_seed", "continuation", "context_merge"}: + _logger.warning(f"Unknown parent relation: {relation} for node_id: {parent_node_id}.") + continue + parents.append(self.run_state.parent_link(parent_node_id, relation)) + + self.run_state.register_iteration(response_list, results_list, tuple(parents), prompt, usage, R, L, C) + + def format_progress(self, R: int | None, L: int | None, C: int | None) -> str: + """Format progress. + + Args: + R: One-based restart index. + L: One-based refinement-step index. + C: One-based conversation-branch index. + + Returns: + Human-readable R/C/L/K progress text. + """ + return ( + f"(R={R}/{self.max_restart_loop}) × " + f"(C={C}/{self.global_width}) × " + f"(L={L}/{self.max_refinement_depth}) × " + f"(K={self.local_sample_size})" + ) + + def get_ranking_metric(self, record: CandidateRecord | dict[str, Any]) -> tuple[str | None, float | int | None]: + """Return the configured ranking metric and its display label. + + Args: + record: Search or candidate record. + + Returns: + Display label and metric value, or two ``None`` values when absent. + """ + metric_label = self.ranking_metric.replace('_', ' ').upper() + if isinstance(record, CandidateRecord): + split_results = record.details.get("data_split_results") + elif isinstance(record, dict): + split_results = record.get("data_split_results") + else: + return None, None + if not isinstance(split_results, dict): + return None, None + validation_metrics = split_results.get("validation", {}).get("metrics", {}) + if (metric_value := validation_metrics.get(self.ranking_metric)) is not None: + return f"validation {metric_label}", metric_value + train_metrics = split_results.get("train", {}).get("metrics", {}) + if (metric_value := train_metrics.get(self.ranking_metric)) is not None: + return f"training {metric_label}", metric_value + return None, None + + def candidate_sort_key(self, record: CandidateRecord | dict[str, Any]) -> tuple[float, float] | None: + """Return the ranking key for a candidate-like record. + + Args: + record: Search or candidate record. + + Returns: + Metric and complexity sorting key, or ``None`` for invalid metrics. + """ + _, metric_value = self.get_ranking_metric(record) + if metric_value is None: + return None + + split_results = ( + record.details.get('data_split_results', {}) + if isinstance(record, CandidateRecord) + else record.get('data_split_results', {}) + ) + train_metrics = split_results.get('train', {}).get('metrics', {}) + validation_metrics = split_results.get('validation', {}).get('metrics', {}) + metric_values = [train_metrics.get(self.ranking_metric)] + if self.ranking_metric in validation_metrics: + metric_values.append(validation_metrics[self.ranking_metric]) + complexity = train_metrics.get('complexity', float('inf')) + try: + finite_values = [float(value) for value in metric_values] + finite_complexity = float(complexity) + except (TypeError, ValueError): + return None + if any(not np.isfinite(value) for value in finite_values) or not np.isfinite(finite_complexity): + return None + + return ( + -float(metric_value) if self.larger_is_better else float(metric_value), + finite_complexity, + ) + + @staticmethod + def candidate_to_dict(record: CandidateRecord) -> dict[str, Any]: + """Adapt a candidate to utilities that consume split results at top level. + + Args: + record: Search or candidate record. + + Returns: + dict[str, Any]: The operation result. + """ + return { + "formula": record.formula, + "node_id": record.node_id, + **record.details, + } + + def best_candidate(self) -> CandidateRecord | None: + """Run the ``best candidate`` operation. + + Returns: + CandidateRecord | None: The operation result. + """ + candidates = self.run_state.ranked_candidates() + return candidates[0] if candidates else None + + def get_pareto_front(self) -> list[CandidateRecord]: + """Return candidates on the metric-complexity Pareto front. + + Returns: + list[CandidateRecord]: The operation result. + """ + candidates = self.run_state.ranked_candidates() + return [candidates[index] for index in self.run_state.pareto_indices(candidates)] + + def build_search_result(self, status: str, R: int | None, L: int | None, C: int | None) -> dict[str, Any]: + """Build a serializable search result for the current run state. + + Args: + status: Run completion status. + R: One-based restart index. + L: One-based refinement-step index. + C: One-based conversation-branch index. + + Returns: + Serializable run result including progress and ranked candidates. + """ + progress = self.format_progress(R, L, C) + return self.run_state.result(status=status, progress=progress).to_dict() diff --git a/src/sr_harness/agents/sr_agent_interactive.py b/src/sr_harness/agents/sr_agent_interactive.py new file mode 100644 index 0000000000000000000000000000000000000000..ce0b1a1602f4be9737c041bab10b04e2209e5d82 --- /dev/null +++ b/src/sr_harness/agents/sr_agent_interactive.py @@ -0,0 +1,1087 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""人机协同符号回归 Agent。 + +继承自 SRAgent,以 L(对话轮次)为搜索主体,支持人类实时干预和工作区文件操作。 +""" + +from __future__ import annotations +import json +import logging +import math +import tempfile +import time +from contextlib import contextmanager +from pathlib import Path +from typing import Any, Callable, Iterator, List, Optional + +from ..api import BaseAPI +from ..core import APICallSample, AgentContext, CandidateRecord, ToolCall, ToolCallResult +from ..runtime import PendingMessage, SRInteractionManager +from ..skills import SkillManager +from .sr_agent import Message, SRAgent, Usage +from ..parser import BaseParser + +_logger = logging.getLogger(f"sr_harness.{__name__}") + + +class SRAgentInteractive(SRAgent): + """Interactive symbolic-regression agent controlled by an interaction manager.""" + + DEFAULT_TOOLS = (*SRAgent.DEFAULT_TOOLS, "finish_search") + + _LEGACY_WORKSPACE_GUIDANCE = ( + "The structured arrays are already loaded into the scientific tools; analyze them " + "there rather than reconstructing them from workspace files. The workspace contains " + "supplemental files and reproducible artifacts." + ) + _TOOL_USAGE_GUIDANCE = ( + "Use only the tools available in the current request. Do not announce a tool call " + "without making it. If a needed capability is unavailable, explain the limitation " + "and continue with the available scientific tools." + ) + + # Construction and frontend event bridge + + def __init__( + self, + llm_provider: str, + llm_model: str, + interaction_manager: SRInteractionManager, + tools: list[str] | None = None, + skills: List[str] | None = None, + verbose: bool = False, + tool_parser: str | BaseParser = "openai", + save_path: Optional[str] = None, + run_id: str | None = None, + local_sample_size: int = 1, + max_refinement_depth: int = 50, + global_width: int = 1, + max_restart_loop: int = 1, + restart_top_k: int = 1, + llm_max_tokens: int = 4096, + max_workers: int = 0, + validation_fraction: float = 0.2, + split_by: str = "random", + split_ood_variable: str | None = None, + split_random_state: int = 42, + ranking_metric: str = "mse", + larger_is_better: bool = False, + use_workspace: bool = False, + workspace_files: List[str | Path] | None = None, + force_initial_diagnostics: bool = False, + pause_on_truncated_response: bool = True, + tool_free_stop_review_rounds: int = 1, + stop_guard_mode: str = "none", + stop_guard_metric: str | None = None, + stop_guard_threshold: float | None = None, + stop_guard_split: str = "validation", + stop_guard_larger_is_better: bool = True, + auto_routing: bool = True, + strong_llm_provider: str | None = None, + strong_llm_model: str | None = None, + context: AgentContext | None = None, + skill_manager: SkillManager | None = None, + ) -> None: + """初始化 SRAgentInteractive。 + + Args: + llm_provider: LLM 提供商名称。 + llm_model: 模型名称。 + tools: 可用工具名列表。None 表示使用 ``SRAgent.DEFAULT_TOOLS``。 + skills: 可供 Agent 读取的 skill 名称。None 表示使用全部 skill。 + verbose: 是否启用详细日志。 + tool_parser: 工具解析器类型。 + save_path: 日志保存路径。 + run_id: 本次运行的全局唯一标识。None 表示自动生成。 + local_sample_size: 每轮 LLM 采样数量(K)。 + max_refinement_depth: 最大对话轮次(L),也是搜索深度上限。 + global_width: 独立分支数量(C)。 + max_restart_loop: 重启次数(R)。 + restart_top_k: 重启时注入历史最佳结果数量。 + llm_max_tokens: 每次模型响应允许生成的最大 token 数。 + max_workers: 并行工作进程数(0 表示不并行)。 + validation_fraction: 验证集比例。 + split_by: 验证集划分方式,可选 "random" 或 "ood"。 + split_ood_variable: OOD 划分使用的变量名;随机划分时可留空。 + split_random_state: 数据划分随机种子。 + ranking_metric: 候选公式排序所用的指标键;默认使用 mse。 + larger_is_better: 排序指标是否越大越好;默认按越小越好排序。 + use_workspace: 是否使用工作区。 + workspace_files: 初始化到工作区的文件/目录路径列表。 + interaction_manager: 连接 Agent 与 Web、终端等交互界面的管理器。 + force_initial_diagnostics: 是否在每个分支开始时强制执行初始诊断。 + pause_on_truncated_response: 模型输出因长度限制截断后是否在安全边界暂停。 + tool_free_stop_review_rounds: 无工具回复触发停机复核时发送的最近轮数;0 表示禁用。 + stop_guard_mode: 停止许可模式:none、best_in_topk、 + metric_threshold 或 budget_exhausted。 + stop_guard_metric: 停止检查使用的指标;None 表示使用 ranking_metric。 + stop_guard_threshold: metric_threshold 模式的目标指标阈值。 + stop_guard_split: 停止检查读取的指标分割,train 或 validation。 + stop_guard_larger_is_better: metric_threshold 模式下指标是否越大越好。 + auto_routing: 是否根据任务复杂度在基础与强模型后端之间自动路由。 + strong_llm_provider: 复杂任务使用的后端;默认沿用 llm_provider。 + strong_llm_model: 复杂任务使用的模型。None 表示仅使用基础模型。 + context: 与数据准备 Agent 共享的数据和工作区上下文。 + skill_manager: Skill 注册表。交互式会话应将其自定义目录放在工作区中。 + """ + super().__init__( + llm_provider=llm_provider, + llm_model=llm_model, + tools=tools, + skills=skills, + verbose=verbose, + tool_parser=tool_parser, + save_path=save_path, + run_id=run_id, + local_sample_size=local_sample_size, + max_refinement_depth=max_refinement_depth, + global_width=global_width, + max_restart_loop=max_restart_loop, + restart_top_k=restart_top_k, + llm_max_tokens=llm_max_tokens, + max_workers=max_workers, + validation_fraction=validation_fraction, + split_by=split_by, + split_ood_variable=split_ood_variable, + split_random_state=split_random_state, + ranking_metric=ranking_metric, + larger_is_better=larger_is_better, + force_initial_diagnostics=force_initial_diagnostics, + auto_routing=auto_routing, + strong_llm_provider=strong_llm_provider, + strong_llm_model=strong_llm_model, + context=context, + skill_manager=skill_manager, + ) + + # 工作区 + self.use_workspace = use_workspace + self.workspace_files = workspace_files + + # 交互界面 + if not isinstance(interaction_manager, SRInteractionManager): + raise TypeError("interaction_manager must be an SRInteractionManager") + self.interaction_manager = interaction_manager + self.pause_on_truncated_response = pause_on_truncated_response + self.tool_free_stop_review_rounds = tool_free_stop_review_rounds + self.stop_guard_mode = stop_guard_mode + self.stop_guard_metric = stop_guard_metric + self.stop_guard_threshold = stop_guard_threshold + self.stop_guard_split = stop_guard_split + self.stop_guard_larger_is_better = stop_guard_larger_is_better + self._validate_stop_settings() + self._last_iteration_had_tool_calls = True + self._last_response_was_truncated = False + self._forced_interruption_pending = False + self._pending_stop_at_boundary = False + self._stop_check_L: int | None = None + self._stop_review_apis: dict[tuple[str, str], BaseAPI] = {} + self._response_followup_messages: list[Message] = [] + self.initial_messages: list[PendingMessage] = [] + self.prompt_overrides: dict[str, str] = {} + self.variable_descriptions: dict[str, str] = {} + self.runtime_settings_supplier: Callable[[], dict[str, Any] | None] | None = None + self.runtime_settings_committer: Callable[[dict[str, Any]], None] | None = None + self._bind_tool_cancellation() + + def on_buffer_messages_added(self, messages: list[Message], **coordinate: int) -> None: + """Publish each system or user message when it enters the buffer. + + Args: + messages: Newly appended messages. + **coordinate: Optional R/C/L search coordinate. + """ + for message in messages: + if message.get("role") not in {"system", "user"}: + continue + payload: dict[str, Any] = {"message": message} + if coordinate: + payload["coord"] = coordinate + self.interaction_manager.publish_event("prompt_added", payload) + + # Runtime settings and tool context + + def _take_runtime_settings(self) -> dict[str, Any] | None: + return self.runtime_settings_supplier() if self.runtime_settings_supplier else None + + def _commit_runtime_settings(self, settings: dict[str, Any]) -> None: + if self.runtime_settings_committer is not None: + self.runtime_settings_committer(settings) + + def _bind_tool_cancellation(self) -> None: + """Share the hard-interrupt event with every active tool instance.""" + for tool in self.tool_box.tools if self.tool_box is not None else []: + tool.cancel_event = self.interaction_manager.cancellation_signal + + def _validate_stop_settings(self) -> None: + """Validate settings that control model-requested safe stopping.""" + if ( + isinstance(self.tool_free_stop_review_rounds, bool) + or not isinstance(self.tool_free_stop_review_rounds, int) + or not 0 <= self.tool_free_stop_review_rounds <= 1000 + ): + raise ValueError("tool_free_stop_review_rounds must be between 0 and 1000") + if self.stop_guard_mode not in { + "none", "best_in_topk", "metric_threshold", "budget_exhausted", + }: + raise ValueError(f"Unsupported stop_guard_mode: {self.stop_guard_mode}") + if self.stop_guard_split not in {"train", "validation"}: + raise ValueError("stop_guard_split must be train or validation") + if self.stop_guard_metric is not None and ( + not isinstance(self.stop_guard_metric, str) or not self.stop_guard_metric.strip() + ): + raise ValueError("stop_guard_metric must be null or a non-empty string") + if self.stop_guard_threshold is not None: + if isinstance(self.stop_guard_threshold, bool) or not isinstance( + self.stop_guard_threshold, (int, float) + ) or not math.isfinite(float(self.stop_guard_threshold)): + raise ValueError("stop_guard_threshold must be null or a finite number") + if self.stop_guard_mode == "metric_threshold" and self.stop_guard_threshold is None: + raise ValueError(f"{self.stop_guard_mode} requires stop_guard_threshold") + + def initialize_with_context(self, context: AgentContext) -> None: + """Initialize from context and attach the active hard-interrupt event.""" + super().initialize_with_context(context) + if hasattr(self, "interaction_manager"): + self._bind_tool_cancellation() + + @contextmanager + def prepare_tool_context(self, tool_context: AgentContext) -> Iterator[AgentContext]: + """Add interaction resources to the tool context for the duration of a run. + + Args: + tool_context: Shared context used to initialize tools. + + Yields: + Context enriched with a temporary workspace manager when enabled. + """ + if not self.use_workspace: + yield tool_context + return + + if tool_context.workspace is not None: + yield tool_context + return + + from ..runtime.workspace import Workspace + + workspace = Workspace(tempfile.mkdtemp(prefix="sr_workspace_")) + for source in self.workspace_files or (): + workspace.mount(source) + _logger.note(f"Workspace initialized at: {workspace.path}") + tool_context.workspace = workspace + yield tool_context + + # Interactive search-boundary hooks + + def prepare_iteration(self, buffer: list[Message], R: int, L: int, C: int) -> str | None: + """Apply queued human guidance before the prompt is constructed. + + Args: + buffer: Conversation history buffer. + R: One-based restart index. + L: One-based refinement-step index. + C: One-based conversation-branch index. + + Returns: + str | None: The operation result. + """ + self.interaction_manager.publish_event("search_position_changed", {"R": R, "C": C, "L": L}) + with self.interaction_manager.wait() as boundary_messages: + messages = [*self.initial_messages, *boundary_messages] + self.initial_messages.clear() + if data_change := self.refresh_data(): + self._append_buffer_messages( + buffer, + [self.build_data_refresh_message(data_change)], + R=R, + C=C, + L=L, + ) + for message in messages: + prompt = { + "role": "user", + "content": f"[Human guidance injected during the run]\n{message.content}", + } + self._append_buffer_messages(buffer, [prompt], R=R, C=C, L=L) + if settings := self._take_runtime_settings(): + self._apply_runtime_settings(settings) + return self.interaction_manager.consume_search_transition() + + @staticmethod + def build_data_refresh_message(change: dict[str, Any]) -> dict[str, str]: + """Turn a structured data revision into guidance for the next model turn.""" + descriptions = change["variable_descriptions"] + description_text = ( + "\nVariable descriptions:\n" + + "\n".join(f"- {name}: {description}" for name, description in descriptions.items()) + if descriptions else "" + ) + return { + "role": "user", + "content": ( + "[Structured data updated by the data-preparation agent]\n" + f"Data revision changed from {change['previous_revision']} to {change['revision']}. " + f"The target is {change['target']!r}; available features are {change['features']}. " + "Reassess earlier evidence against the updated variables and continue the investigation." + f"{description_text}" + ), + } + + def _apply_runtime_settings(self, settings: dict[str, Any]) -> None: + """Apply frontend-requested model and capability changes at a safe boundary.""" + try: + tool_names = settings.get("tools") + requested_tools = ( + set(self.available_tool_classes) if tool_names is None else set(tool_names) + ) + if unknown_tools := requested_tools - self.available_tool_classes.keys(): + raise ValueError(f"Unknown tools: {', '.join(sorted(unknown_tools))}") + self.tool_cls_list = [ + tool_cls for name, tool_cls in self.available_tool_classes.items() + if name in requested_tools + ] + registered_skills = self.skill_manager.load_skills() + self.skill_manager.register_tool_docs([ + tool_cls for tool_cls in self.tool_cls_list + if (doc := tool_cls.get_doc()) is not None + and doc["name"] not in registered_skills + ]) + available_skills = self.skill_manager.load_skills() + skill_names = settings.get("skills") + requested_skills = set(available_skills) if skill_names is None else set(skill_names) + if unknown_skills := requested_skills - available_skills.keys(): + raise ValueError(f"Unknown skills: {', '.join(sorted(unknown_skills))}") + requested_skills.update( + doc["name"] + for tool_cls in self.tool_cls_list + if (doc := tool_cls.get_doc()) is not None + ) + self.enabled_skills = requested_skills + self.llm_provider = settings["llm_provider"] + self.llm_model = settings["llm_model"] + for name in ( + "local_sample_size", + "max_refinement_depth", + "global_width", + "max_restart_loop", + "restart_top_k", + "llm_max_tokens", + "max_workers", + "validation_fraction", + "split_by", + "split_ood_variable", + "split_random_state", + "ranking_metric", + "larger_is_better", + "force_initial_diagnostics", + "pause_on_truncated_response", + "tool_free_stop_review_rounds", + "stop_guard_mode", + "stop_guard_metric", + "stop_guard_threshold", + "stop_guard_split", + "stop_guard_larger_is_better", + "auto_routing", + "tool_parser", + ): + if name in settings: + setattr(self, name, settings[name]) + self._validate_stop_settings() + self.strong_llm_provider = ( + self.llm_provider + if settings.get("strong_llm_provider") is None + else settings["strong_llm_provider"] + ) + self.strong_llm_model = settings.get("strong_llm_model") + if self.force_initial_diagnostics: + required_tools = {"statistics_analysis", "relationship_analysis", "read_skill"} + if missing := required_tools - requested_tools: + raise ValueError( + "force_initial_diagnostics requires enabled tools: " + + ", ".join(sorted(missing)) + ) + if "discover-symbolic-laws" not in self.enabled_skills: + raise ValueError( + "force_initial_diagnostics requires the discover-symbolic-laws skill" + ) + self.context.args.validation_fraction = self.validation_fraction + self.context.args.split_by = self.split_by + self.context.args.split_ood_variable = self.split_ood_variable + self.context.args.split_random_state = self.split_random_state + self.context.invalidate_splits() + self.context.args.llm_provider = self.llm_provider + self.context.args.llm_model = self.llm_model + self.context.args.llm_max_tokens = self.llm_max_tokens + self.context.args.enabled_skills = sorted(self.enabled_skills) + self.initialize_with_context(self.context) + self._bind_tool_cancellation() + self.model_router.base_provider = self.llm_provider + self.model_router.base_model = self.llm_model + self.model_router.enabled = self.auto_routing + self.model_router.strong_provider = self.strong_llm_provider + self.model_router.strong_model = self.strong_llm_model + self.run_state.ranking_metric = self.ranking_metric + self.run_state.larger_is_better = self.larger_is_better + self._strong_api = None + self._stop_review_apis.clear() + self._commit_runtime_settings(settings) + self.interaction_manager.publish_event("settings_applied", settings) + except Exception as exc: + self.interaction_manager.publish_event("settings_failed", {"error": str(exc)}) + + def finish_iteration(self, buffer: list[Message], R: int, L: int, C: int) -> str | None: + """Keep interactive runs open and yield tool-free responses to the human. + + Args: + buffer: Conversation history buffer. + R: One-based restart index. + L: One-based refinement-step index. + C: One-based conversation-branch index. + + Returns: + str | None: The operation result. + """ + if self._forced_interruption_pending or self.interaction_manager.is_interrupting: + prompt = {"role": "user", "content": "用户强制中止"} + self._append_buffer_messages(buffer, [prompt], R=R, C=C, L=L) + self._forced_interruption_pending = False + return None + if getattr(self, "_pending_stop_at_boundary", False): + self._pending_stop_at_boundary = False + self.interaction_manager.request_pause() + elif ( + not self._last_iteration_had_tool_calls + and not self._last_response_was_truncated + and getattr(self, "tool_free_stop_review_rounds", 1) > 0 + and self.interaction_manager.state == "running" + and not self.interaction_manager.status().get("pending_messages") + and self.interaction_manager.status().get("pending_transition") is None + ): + should_stop, review_reason = self._review_tool_free_stop(buffer, R=R, L=L, C=C) + if should_stop: + rejection = self._stop_rejection_reason(L=L) + if rejection is None: + self.interaction_manager.request_pause() + else: + self._append_buffer_messages(buffer, [{ + "role": "user", + "content": ( + "[Stop request rejected]\n" + f"{rejection} Continue the symbolic-regression search." + ), + }], R=R, C=C, L=L) + else: + _logger.info( + f"Tool-free response will continue after stop review: {review_reason}" + ) + self._last_response_was_truncated = False + return None + + def _recent_agent_rounds(self, buffer: list[Message]) -> list[Message]: + """Return a plain-message suffix containing the configured number of Agent turns.""" + assistant_indices = [ + index for index, message in enumerate(buffer) if message.get("role") == "assistant" + ] + if not assistant_indices: + return [] + start = assistant_indices[-min(self.tool_free_stop_review_rounds, len(assistant_indices))] + fields = {"role", "content", "reasoning", "tool_calls", "name"} + return [ + {key: value for key, value in message.items() if key in fields} + for message in buffer[start:] + ] + + @staticmethod + def _parse_stop_review(content: str) -> tuple[bool, str]: + """Parse the review model's strict JSON decision conservatively.""" + try: + start = content.index("{") + end = content.rindex("}") + 1 + payload = json.loads(content[start:end]) + decision = payload.get("should_stop") + reason = str(payload.get("reason", "")).strip() + if not isinstance(decision, bool): + raise ValueError("should_stop is not boolean") + return decision, reason + except (ValueError, TypeError, json.JSONDecodeError) as exc: + return False, f"invalid stop-review response: {exc}" + + def _review_tool_free_stop( + self, buffer: list[Message], *, R: int, L: int, C: int, + ) -> tuple[bool, str]: + """Ask a tool-free BaseAPI call whether the Agent intended to stop.""" + route = self._last_model_route + provider = route.provider if route is not None else self.llm_provider + model = route.model if route is not None else self.llm_model + key = (provider, model) + api = self._stop_review_apis.get(key) + if api is None: + api = BaseAPI.create( + provider, + model=model, + environment=getattr(self.context.args, "api_environment", None), + ) + self._stop_review_apis[key] = api + recent = self._recent_agent_rounds(buffer) + messages = [{ + "role": "system", + "content": ( + "Decide whether the symbolic-regression Agent intends to hand control back " + "to the user now. Return JSON only: " + '{"should_stop": true|false, "reason": "brief explanation"}. ' + "Answer false when it is planning, analyzing, describing a next action, or " + "otherwise appears to have unfinished autonomous work. Answer true only for " + "a final answer, an explicit request for user input, or an explicit decision to stop." + ), + }, { + "role": "user", + "content": "Recent Agent rounds:\n" + json.dumps(recent, ensure_ascii=False), + }] + try: + with self.interaction_manager.cancellable(api.cancel): + result = api(messages, n=1) + responses = list(result) + usage = {"token": result.token_usage, "price": result.money_usage} + for name, value in usage.get("token", {}).items(): + self.token_counter.add(name, value) + for name, value in usage.get("price", {}).items(): + self.money_counter.add(name, value) + content = responses[0].content if responses else "" + decision, reason = self._parse_stop_review(content) + if self.save_path is not None: + with open(Path(self.save_path) / "stop_reviews.jsonl", "a", encoding="utf-8") as stream: + json.dump({ + "progress": self.format_progress(R, L, C), + "provider": provider, + "model": model, + "rounds": recent, + "response": content, + "should_stop": decision, + "reason": reason, + "usage": usage, + }, stream, ensure_ascii=False) + stream.write("\n") + return decision, reason + except Exception as exc: + _logger.warning(f"Stop review failed; continuing the search: {exc}") + return False, f"stop review failed: {exc}" + + @staticmethod + def _result_metric_values( + result: ToolCallResult, metric: str, split: str, + ) -> list[float]: + """Extract finite metric values from one candidate-producing tool result.""" + candidates = [result.result, *result.result.get("all_formulas", [])] + values = [] + for candidate in candidates: + value = ( + candidate.get("data_split_results", {}) + .get(split, {}) + .get("metrics", {}) + .get(metric) + ) + try: + numeric = float(value) + except (TypeError, ValueError): + continue + if math.isfinite(numeric): + values.append(numeric) + return values + + def _stop_metric_values( + self, metric: str, split: str, extra_results: list[ToolCallResult] | None = None, + ) -> list[float]: + """Collect stop-check metrics from retained and same-response candidates.""" + values = [] + for record in self.run_state.ranked_candidates(): + try: + value = float(record.metric(metric, split)) + except (TypeError, ValueError): + continue + if math.isfinite(value): + values.append(value) + for result in extra_results or []: + values.extend(self._result_metric_values(result, metric, split)) + return values + + def _topk_ranking_values( + self, extra_results: list[ToolCallResult] | None = None, + ) -> dict[str, float]: + """Return the best ranking-metric value retained for each distinct formula.""" + candidates: list[CandidateRecord | dict[str, Any]] = list( + self.run_state.ranked_candidates() + ) + for result in extra_results or []: + if result.result.get("is_candidate"): + candidates.append(result.result) + candidates.extend( + candidate + for candidate in result.result.get("all_formulas", []) + if isinstance(candidate, dict) + ) + values: dict[str, float] = {} + for index, candidate in enumerate(candidates): + formula = ( + candidate.formula + if isinstance(candidate, CandidateRecord) + else candidate.get("formula") + ) + _, value = self.get_ranking_metric(candidate) + try: + numeric = float(value) + except (TypeError, ValueError): + continue + if not math.isfinite(numeric): + continue + key = str(formula) if formula is not None else f"" + previous = values.get(key) + if previous is None or ( + numeric > previous if self.larger_is_better else numeric < previous + ): + values[key] = numeric + return values + + def _stop_rejection_reason( + self, *, L: int, extra_results: list[ToolCallResult] | None = None, + ) -> str | None: + """Return why stopping is forbidden, or ``None`` when it is allowed.""" + if self.stop_guard_mode == "none": + return None + if self.stop_guard_mode == "budget_exhausted": + if L < self.max_refinement_depth: + return ( + f"The configured search budget is not exhausted: current round L={L}, " + f"required L={self.max_refinement_depth}." + ) + return None + if self.stop_guard_mode == "best_in_topk": + values_by_formula = self._topk_ranking_values(extra_results) + if not values_by_formula: + return ( + f"topk_records contains no candidate with a finite ranking metric " + f"({self.ranking_metric}), so stopping is not allowed." + ) + ordered = sorted( + values_by_formula.items(), + key=lambda item: item[1], + reverse=self.larger_is_better, + ) + if len(ordered) == 1: + return None + best_formula, best = ordered[0] + runner_up_formula, runner_up = ordered[1] + strictly_better = best > runner_up if self.larger_is_better else best < runner_up + if strictly_better: + return None + direction = ">" if self.larger_is_better else "<" + return ( + f"No result in topk_records strictly beats every other formula on " + f"{self.ranking_metric}: {best_formula!r} and {runner_up_formula!r} are tied " + f"at {best:.12g}; stopping requires a unique best value ({direction} all others)." + ) + metric = self.stop_guard_metric or self.ranking_metric + values = self._stop_metric_values( + metric, self.stop_guard_split, extra_results=extra_results, + ) + if not values: + return ( + f"No candidate has a finite {self.stop_guard_split} {metric} value, " + "so the configured stopping condition is not satisfied." + ) + threshold = float(self.stop_guard_threshold) + best = max(values) if self.stop_guard_larger_is_better else min(values) + passed = best >= threshold if self.stop_guard_larger_is_better else best <= threshold + if passed: + return None + direction = ">=" if self.stop_guard_larger_is_better else "<=" + return ( + f"The best {self.stop_guard_split} {metric} is {best:.12g}; stopping requires " + f"{metric} {direction} {threshold:.12g}." + ) + + def build_response_followup_messages( + self, + response_list: list[APICallSample], + results_list: list[list[ToolCallResult]], + *, + R: int, + L: int, + C: int, + ) -> list[Message]: + """Consume notices generated while receiving the current response.""" + messages = self._response_followup_messages + self._response_followup_messages = [] + return messages + + # Initial-prompt customization hooks + + def create_initial_system_prompt(self, restart_records: list[CandidateRecord]) -> str: + """Create the interactive system prompt with capability-safe tool guidance. + + Args: + restart_records: Ranked candidates used to set the next objective. + + Returns: + Interactive system-prompt text. + """ + mse_goal = self._build_mse_goal(restart_records) + return ( + "You are a Symbolic Regression Agent working with a human researcher. " + "Your goal is to discover simple, interpretable mathematical formulas that explain " + "the relationship between feature variables and the target variable.\n\n" + "Guidelines:\n" + "- Explore data thoroughly before proposing formulas.\n" + "- Prefer simple, interpretable expressions over complex ones.\n" + f"- {mse_goal}\n" + f"- {self._TOOL_USAGE_GUIDANCE}" + ) + + @classmethod + def normalize_system_prompt(cls, prompt: str) -> str: + """Remove obsolete generated guidance that advertises workspace-only tools. + + Args: + prompt: Stored or newly submitted system prompt. + + Returns: + System prompt without legacy workspace guidance. Capability-neutral guidance is + appended when the removed paragraph came from an older generated prompt. + """ + marker = cls._LEGACY_WORKSPACE_GUIDANCE + start = prompt.find(marker) + if start < 0: + return prompt + end = start + len(marker) + for suffix in ( + " Use workspace_shell for bounded file operations and workspace_code_executor for Python analysis.", + " Use workspace_shell for bounded file operations.", + " Use workspace_code_executor for Python analysis.", + ): + if prompt.startswith(suffix, end): + end += len(suffix) + break + before = prompt[:start].rstrip() + after = prompt[end:].lstrip() + replacement = f"- {cls._TOOL_USAGE_GUIDANCE}" + return "\n".join(part for part in (before, replacement, after) if part) + + def customize_initial_prompts(self, messages: list[Message], *, X: dict[str, Any], y: dict[str, Any]) -> list[Message]: + """Apply UI-provided descriptions and prompt overrides. + + Args: + messages: Initial system and user messages. + X: Feature arrays keyed by variable name. + y: Target arrays keyed by variable name. + + Returns: + Customized initial messages. + """ + descriptions = getattr(self, "variable_descriptions", {}) + rows = [f"- {name}: {descriptions[name]}" for name in [*X, *y] if descriptions.get(name)] + if rows: + messages[1]["content"] += "\n\nVariable descriptions:\n" + "\n".join(rows) + overrides = getattr(self, "prompt_overrides", {}) + for message in messages: + if message.get("role") in overrides: + content = overrides[message["role"]] + if message["role"] == "system": + content = self.normalize_system_prompt(content) + message["content"] = content + return messages + + # Streaming model and tool events + + def request_llm(self, prompt: list[Message], R: int, L: int, C: int) -> tuple[list[APICallSample], Usage]: + """Request the model while publishing frontend-neutral progress events. + + Args: + prompt: Prompt messages sent to the model. + R: One-based restart index. + L: One-based refinement-step index. + C: One-based conversation-branch index. + + Returns: + Parsed responses and usage, including partial responses after interruption. + """ + coord = {"R": R, "C": C, "L": L} + self.interaction_manager.publish_event("context", {"messages": prompt, "coord": coord}) + route = self.model_router.route( + task_score=self._task_route_score, + task_reasons=self._task_route_reasons, + refinement_step=L, + ) + tool_schemas = { + tool.metadata.name: self.tool_schema(tool.metadata.name) + for tool in self.tool_box.tools + if getattr(tool, "metadata", None) is not None + } + response_ids = { + K: f"{self.run_state.run_id}:{R}:{C}:{L}:{K}" + for K in range(1, self.local_sample_size + 1) + } + for K, response_id in response_ids.items(): + self.interaction_manager.publish_event("assistant_started", { + "response_id": response_id, + "coord": coord | {"K": K}, + "tool_schemas": tool_schemas, + "provider": route.provider, + "model": route.model, + }) + last_stream_emit: dict[int, float] = {} + latest_stream_updates: dict[int, dict[str, Any]] = {} + + def callback(update: dict[str, Any]) -> None: + K = max(1, min(int(update.get("sample", 1)), self.local_sample_size)) + latest_stream_updates[K] = update + now = time.monotonic() + if update.get("type") == "delta" and now - last_stream_emit.get(K, 0.0) < 0.08: + return + last_stream_emit[K] = now + self.interaction_manager.publish_event("assistant_delta", { + **update, + "response_id": response_ids[K], + "coord": coord | {"K": K}, + "tool_schemas": tool_schemas, + "provider": route.provider, + "model": route.model, + }) + + interrupted = False + response_error: str | None = None + self._last_response_was_truncated = False + try: + with self.interaction_manager.cancellable(self.api.cancel): + responses, usage = super().request_llm( + prompt, + R=R, + L=L, + C=C, + callback=callback, + ) + except InterruptedError: + interrupted = True + response_error = "用户强制中止" + self._forced_interruption_pending = True + responses = [] + for K in range(1, self.local_sample_size + 1): + update = latest_stream_updates.get(K, {}) + message = { + "role": "assistant", + "content": update.get("content", ""), + } + if update.get("reasoning"): + message["reasoning"] = update["reasoning"] + responses.append(APICallSample( + content=message["content"], + message_extra={key: value for key, value in message.items() if key != "content"}, + )) + usage = {"token": {}, "price": {}} + except Exception as exc: + for K, response_id in response_ids.items(): + self.interaction_manager.publish_event("assistant_failed", { + **latest_stream_updates.get(K, {}), + "response_id": response_id, + "coord": coord | {"K": K}, + "provider": route.provider, + "model": route.model, + "error": str(exc), + }) + raise + self._last_iteration_had_tool_calls = any(response.tool_calls for response in responses) + cumulative_usage = { + "token": self.token_counter.named_count, + "price": self.money_counter.named_count, + } + for K, response in enumerate(responses, 1): + content = response.content + calls = response.tool_calls + message = response.message + self.interaction_manager.publish_event( + "assistant_failed" if response_error else "assistant_completed", + { + "response_id": response_ids[K], + "content": content, + "reasoning": message.get("reasoning", ""), + "message": message, + "tool_calls": calls, + "tool_schemas": tool_schemas, + "coord": coord | {"K": K}, + "usage": usage, + "cumulative_usage": cumulative_usage, + "provider": route.provider, + "model": route.model, + **({"error": response_error, "interrupted": interrupted} if response_error else {}), + }, + ) + return responses, usage + + def tool_schema(self, name: str) -> dict[str, Any]: + """Return the schema exposed by one initialized tool. + + Args: + name: Registered name. + + Returns: + dict[str, Any]: The operation result. + """ + return next( + ( + { + "description": tool.metadata.description, + "parameters": tool.metadata.parameters or {}, + } + for tool in self.tool_box.tools + if tool.metadata.name == name + ), + {}, + ) + + def execute_action(self, actions: list[ToolCall]) -> list[ToolCallResult]: + """Execute tools serially with safe control boundaries and UI events. + + Args: + actions: Tool calls to execute. + + Returns: + Tool results in call order. + """ + results: list[ToolCallResult | None] = [None] * len(actions) + finish_indices = [] + for index, action in enumerate(actions): + if action.name == "finish_search" and any( + tool.metadata.name == "finish_search" for tool in self.tool_box.tools + ): + finish_indices.append(index) + continue + tool_schema = self.tool_schema(action.name) + self.interaction_manager.publish_event("tool_started", {"call": action, "tool_schema": tool_schema}) + started_at = time.monotonic() + try: + tool = self.tool_box[action.name] + except KeyError: + tool = None + if tool is None: + result = super().execute_action([action])[0] + else: + with self.interaction_manager.cancellable(tool.cancel): + result = super().execute_action([action])[0] + self.interaction_manager.publish_event("tool_completed", { + "call": action, + "tool_schema": tool_schema, + "duration_seconds": time.monotonic() - started_at, + "result": result, + }) + results[index] = result + ordinary_results = [result for result in results if result is not None] + for index in finish_indices: + action = actions[index] + tool = self.tool_box["finish_search"] + tool_schema = self.tool_schema(action.name) + self.interaction_manager.publish_event( + "tool_started", {"call": action, "tool_schema": tool_schema}, + ) + started_at = time.monotonic() + timestamp = time.time() + self.tools_counter.add(action.name) + rejection = self._stop_rejection_reason( + L=self._stop_check_L or 1, + extra_results=ordinary_results, + ) + payload = ( + {"status": "stopped", "reason": str(action.params.get("reason", "")).strip()} + if rejection is None + else {"status": "rejected", "reason": rejection} + ) + result = ToolCallResult( + ok=True, + result=payload, + result_str=tool.format_result_dict(payload), + meta_data={ + "timestamp": timestamp, + "execution_time": time.monotonic() - started_at, + "tool": action.name, + }, + ) + if rejection is None: + self._pending_stop_at_boundary = True + self.interaction_manager.publish_event("tool_completed", { + "call": action, + "tool_schema": tool_schema, + "duration_seconds": time.monotonic() - started_at, + "result": result, + }) + results[index] = result + if any(result is None for result in results): + raise RuntimeError("Tool execution did not produce one result per call") + return [result for result in results if result is not None] + + def execute_tool_calls( + self, response_list: list[APICallSample], R: int, L: int, C: int, + ) -> list[list[ToolCallResult]]: + """Expose the current refinement round to the finish-search stop check.""" + self._stop_check_L = L + try: + return super().execute_tool_calls(response_list, R=R, L=L, C=C) + finally: + self._stop_check_L = None + + def collect_candidates(self, *args: Any, **kwargs: Any) -> list[CandidateRecord]: + """Update scientific state and publish its current ranked view. + + Args: + *args: Arguments forwarded to the base candidate collector. + **kwargs: Keyword arguments forwarded to the base candidate collector. + + Returns: + Candidates ranked under the configured metric. + """ + records = super().collect_candidates(*args, **kwargs) + self.interaction_manager.publish_event("topk_updated", {"records": [record.display_dict() for record in records]}) + return records + + def record_tool_calls( + self, + tool_calls: list[ToolCall], + results: list[ToolCallResult], + R: int, + L: int, + C: int, + forced: bool = False, + ) -> None: + """Persist tool calls and expose framework-enforced calls to the UI. + + Args: + tool_calls: Tool calls returned by the model. + results: Result records to process. + R: One-based restart index. + L: One-based refinement-step index. + C: One-based conversation-branch index. + forced: Whether the framework, rather than the model, initiated the call. + """ + super().record_tool_calls(tool_calls, results, R=R, L=L, C=C, forced=forced) + if forced: + for call, result in zip(tool_calls, results): + self.interaction_manager.publish_event("tool_completed", { + "call": call, + "tool_schema": self.tool_schema(call.name), + "result": result, + "forced": True, + }) + + def execute_action_parallel(self, actions: list[ToolCall], max_workers: int) -> list[ToolCallResult]: + """Reject parallel execution in interactive mode. + + Args: + actions: Tool calls to execute. + max_workers: Maximum number of parallel workers. + + Raises: + NotImplementedError: Always, because interactive workspace tools are not + guaranteed to be read-only. + """ + raise NotImplementedError( + "Parallel execution is not supported in interactive mode, " + "since workspace tools cannot guarantee read-only access. " + "Please set max_workers=0 to disable parallel execution when using interactive tools." + ) diff --git a/src/sr_harness/api/__init__.py b/src/sr_harness/api/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d25749484b11c1751d67569c0a6f3eef111224b5 --- /dev/null +++ b/src/sr_harness/api/__init__.py @@ -0,0 +1,22 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +from .base_api import BaseAPI +from ..core import APICallSummary +from .manual_api import ManualAPI +from .openai_api import OpenAIAPI +from .gemini_api import GeminiAPI +from .deepseek_api import DeepSeekAPI +from .openrouter_api import OpenRouterAPI +from .lmstudio_api import LMStudioAPI +from .siliconflow_api import SiliconFlowAPI + +__all__ = [ + "APICallSummary", + "BaseAPI", + "DeepSeekAPI", + "GeminiAPI", + "LMStudioAPI", + "ManualAPI", + "OpenAIAPI", + "OpenRouterAPI", + "SiliconFlowAPI", +] diff --git a/src/sr_harness/api/base_api.py b/src/sr_harness/api/base_api.py new file mode 100644 index 0000000000000000000000000000000000000000..1e6e5006ddec70a13483639f6c1a9916d2b41ade --- /dev/null +++ b/src/sr_harness/api/base_api.py @@ -0,0 +1,537 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +"""Base class and shared tool-call support for LLM provider adapters.""" + +from __future__ import annotations + +import json +import logging +import time +import threading +import traceback +import uuid +from abc import ABC, abstractmethod +from dataclasses import dataclass, field +import os +from pathlib import Path +from typing import Any, Callable, Generator, Mapping +from requests.utils import should_bypass_proxies + +from ..core import APICallSample, APICallSummary, ToolCall +from ..parser import BaseParser +from ..utils import FactoryMixin +from .error_filter import screen_frontend_error + +_logger = logging.getLogger(f"sr_harness.{__name__}") +_api_log_lock = threading.Lock() + +ProgressCallback = Callable[[dict[str, Any]], None] + + +@dataclass(slots=True) +class ProviderSampleResult: + """One provider sample plus the accounting needed by the batch caller.""" + + response: APICallSample + token_usage: dict[str, int | float] = field(default_factory=dict) + money_usage: dict[str, int | float] = field(default_factory=dict) + raw_response: Any = None + error: str | None = None + + +class BaseAPI(ABC, FactoryMixin): + """Common request, parser, and tool-call behavior for LLM providers.""" + + def __init__( + self, + model: str | None = None, + tool_box: BaseParser | None = None, + environment: Mapping[str, str] | None = None, + save_path: str | Path | None = None, + ) -> None: + self.model = model + if tool_box is not None and not isinstance(tool_box, BaseParser): + raise TypeError("tool_box must be a BaseParser instance or None") + self.tool_box = tool_box + self.environment = environment if environment is not None else {} + self.save_path = Path(save_path) if save_path is not None else None + self._cancel_requested = threading.Event() + + @property + @abstractmethod + def model_list(self) -> list[str]: + """Return model identifiers accepted by this provider adapter.""" + raise NotImplementedError + + def get_env( + self, + name: str, + default: str | None = None, + *, + required: bool = False, + ) -> str | None: + """Read a provider setting and optionally require a non-None value.""" + value = self.environment.get(name, os.environ.get(name, default)) + if required and value is None: + raise KeyError(name) + return value + + def proxy_url(self, url: str | None = None) -> str | None: + """Return this API instance's session proxy unless ``url`` bypasses it.""" + if url and should_bypass_proxies( + url, no_proxy=self.get_env("NO_PROXY") or self.get_env("no_proxy") + ): + return None + return ( + self.get_env("HTTPS_PROXY") + or self.get_env("https_proxy") + or self.get_env("HTTP_PROXY") + or self.get_env("http_proxy") + ) + + def report_progress( + self, + callback: ProgressCallback | None, + update: dict[str, Any], + ) -> None: + """Publish one optional progress update.""" + if callback is not None: + callback(update) + + def raise_if_cancelled(self) -> None: + """Raise at an API-owned cancellation boundary.""" + if self._cancel_requested.is_set(): + raise InterruptedError("Model API request was cancelled") + + def wait_before_retry(self, delay: float) -> None: + """Wait for retry backoff while remaining immediately cancellable.""" + if self._cancel_requested.wait(delay): + raise InterruptedError("Model API request was cancelled") + + def _request_samples( + self, + messages: list[dict[str, Any]], + n: int = 1, + callback: ProgressCallback | None = None, + **kwargs: Any, + ) -> Generator[APICallSample, None, dict[str, Any]]: + """Request ``n`` samples, using one independent request per sample by default.""" + attempts = 3 + results: list[ProviderSampleResult] = [] + description = f"{type(self).__name__}({self.model})" + for sample_index in range(1, n + 1): + for attempt in range(1, attempts + 1): + try: + self.raise_if_cancelled() + sample_result = self._request_sample( + messages, + sample_index=sample_index, + callback=callback, + **kwargs, + ) + self.raise_if_cancelled() + break + except InterruptedError: + raise + except Exception as error: + self.raise_if_cancelled() + public_error = self.error_message(error, description=description) + if attempt == attempts: + self.report_progress(callback, { + "type": "failed", + "sample": sample_index, + "error": public_error, + }) + result = self.aggregate_sample_results(results) + result["ok"] = False + result["error"] = public_error + return result + self.report_progress(callback, { + "type": "retry", + "sample": sample_index, + "attempt": attempt, + "error": public_error, + }) + delay = self.retry_delay(error, attempt) + _logger.info( + f"Retrying {description} in {delay:g}s " + f"(attempt {attempt}/{attempts})." + ) + self.wait_before_retry(delay) + if not isinstance(sample_result, ProviderSampleResult): + raise TypeError( + "_request_sample() must return ProviderSampleResult, " + f"not {type(sample_result).__name__}" + ) + results.append(sample_result) + yield sample_result.response + if sample_result.error: + self.report_progress(callback, { + "type": "failed", + "sample": sample_index, + "error": sample_result.error, + }) + return self.aggregate_sample_results(results) + return self.aggregate_sample_results(results) + + def _request_sample( + self, + messages: list[dict[str, Any]], + *, + sample_index: int, + callback: ProgressCallback | None = None, + **kwargs: Any, + ) -> ProviderSampleResult: + """Perform one request attempt; only ``_request_samples`` should call this hook.""" + raise NotImplementedError( + f"{type(self).__name__} must either implement _request_sample() or reimplement _request_samples()" + ) + + def error_message(self, error: BaseException, *, description: str | None = None) -> str: + """Log one raw provider error and prepare its frontend representation.""" + label = description or f"{type(self).__name__}({self.model})" + formatted_error = "".join(traceback.format_exception(error)).rstrip() + _logger.error(f"Error requesting {label}:\n{formatted_error}") + message, findings = screen_frontend_error(error, self.environment) + if findings: + _logger.warning( + f"Withheld {label} error details from the frontend after detecting: " + f"{', '.join(findings)}" + ) + return message + + @staticmethod + def retry_delay(error: Exception, attempt: int) -> float: + """Honor a provider Retry-After hint, or use bounded backoff.""" + headers = getattr(getattr(error, "response", None), "headers", None) or {} + retry_after = headers.get("retry-after") or headers.get("Retry-After") + if retry_after is None: + body = getattr(error, "body", None) + if isinstance(body, dict): + error_body = body.get("error", body) + metadata = error_body.get("metadata", {}) if isinstance(error_body, dict) else {} + retry_headers = metadata.get("headers", {}) if isinstance(metadata, dict) else {} + retry_after = retry_headers.get("Retry-After") or retry_headers.get("retry-after") + try: + return max(1.0, min(float(retry_after), 300.0)) + except (TypeError, ValueError): + return min(float(2 ** (attempt - 1)), 30.0) + + def openai_chat_completion( + self, + client: Any, + payload: dict[str, Any], + *, + sample: int, + callback: ProgressCallback | None = None, + ) -> tuple[Any, dict[str, Any], dict[str, Any], str]: + """Request one OpenAI-compatible completion and normalize its shape.""" + if callback is not None: + return self.stream_openai_chat_completion( + client, + payload, + sample=sample, + callback=callback, + ) + completion = client.chat.completions.create(**payload) + response = completion.to_dict() + message_object = completion.choices[0].message + message = ( + message_object.to_dict() if hasattr(message_object, "to_dict") else dict(message_object) + ) + return completion, response, message, message.get("content") or "" + + def stream_openai_chat_completion( + self, + client: Any, + payload: dict[str, Any], + *, + sample: int, + callback: ProgressCallback, + ) -> tuple[Any, dict[str, Any], dict[str, Any], str]: + """Consume an OpenAI-compatible stream and emit provider-neutral snapshots.""" + stream_payload = { + **payload, + "stream": True, + "stream_options": {"include_usage": True}, + } + stream = client.chat.completions.create(**stream_payload) + content_parts: list[str] = [] + reasoning_parts: list[str] = [] + reasoning_details: list[Any] = [] + raw_chunks: list[dict[str, Any]] = [] + raw_tool_calls: dict[int, dict[str, Any]] = {} + usage = None + finish_reason = None + self.report_progress(callback, {"type": "start", "sample": sample}) + for chunk in stream: + self.raise_if_cancelled() + chunk_dict = chunk.to_dict() if hasattr(chunk, "to_dict") else {} + raw_chunks.append(chunk_dict) + if getattr(chunk, "usage", None) is not None: + usage = chunk.usage + choices = getattr(chunk, "choices", None) or [] + if not choices: + continue + choice = choices[0] + if getattr(choice, "finish_reason", None) is not None: + finish_reason = choice.finish_reason + delta = choice.delta + if text := getattr(delta, "content", None): + content_parts.append(text) + reasoning_delta = ( + getattr(delta, "reasoning", None) or getattr(delta, "reasoning_content", None) or "" + ) + new_details = getattr(delta, "reasoning_details", None) or [] + if new_details: + normalized_details = [ + item.to_dict() if hasattr(item, "to_dict") else item for item in new_details + ] + reasoning_details.extend(normalized_details) + if not reasoning_delta: + reasoning_delta = "".join( + (item.get("text") or "") if isinstance(item, dict) else "" + for item in normalized_details + ) + if reasoning_delta: + reasoning_parts.append(reasoning_delta) + for tool_delta in getattr(delta, "tool_calls", None) or []: + index = int(getattr(tool_delta, "index", 0) or 0) + current = raw_tool_calls.setdefault( + index, + { + "id": None, + "type": "function", + "function": {"name": "", "arguments": ""}, + }, + ) + if getattr(tool_delta, "id", None): + current["id"] = tool_delta.id + function = getattr(tool_delta, "function", None) + if function is not None: + if getattr(function, "name", None): + current["function"]["name"] += function.name + if getattr(function, "arguments", None): + current["function"]["arguments"] += function.arguments + self.report_progress(callback, { + "type": "delta", + "sample": sample, + "content": "".join(content_parts), + "reasoning": "".join(reasoning_parts), + "tool_calls": [raw_tool_calls[key] for key in sorted(raw_tool_calls)], + }) + content = "".join(content_parts) + reasoning = "".join(reasoning_parts) + message: dict[str, Any] = {"role": "assistant", "content": content} + if reasoning: + message["reasoning"] = reasoning + if reasoning_details: + message["reasoning_details"] = reasoning_details + if raw_tool_calls: + message["tool_calls"] = [raw_tool_calls[key] for key in sorted(raw_tool_calls)] + self.report_progress(callback, { + "type": "complete", + "sample": sample, + "content": content, + "reasoning": reasoning, + "tool_calls": message.get("tool_calls", []), + "finish_reason": finish_reason, + }) + completion = type("StreamCompletion", (), {"usage": usage})() + return completion, {"chunks": raw_chunks, "finish_reason": finish_reason}, message, content + + def parse_tool_calls(self, message: dict[str, Any], content: str) -> list[ToolCall]: + """Parse one assistant message using the configured tool-call mode.""" + if self.tool_box is None: + return [] + if not self.tool_box.native_tool_calls: + return self.tool_box.parse_response(content) + return self.tool_box.parse_response(message.get("tool_calls") or []) + + @staticmethod + def openai_token_usage(completion: Any, *, other_key: str = "others") -> dict[str, int]: + """Extract token counters from an OpenAI-compatible completion.""" + usage = getattr(completion, "usage", None) + if usage is None: + return {} + prompt = int(getattr(usage, "prompt_tokens", 0) or 0) + answer = int(getattr(usage, "completion_tokens", 0) or 0) + result = {"prompt": prompt, "answer": answer} + total = int(getattr(usage, "total_tokens", prompt + answer) or 0) + if (other := total - prompt - answer) > 0: + result[other_key] = other + return result + + @staticmethod + def aggregate_sample_results(results: list[ProviderSampleResult]) -> dict[str, Any]: + """Build the aggregate result for independently requested samples.""" + token_usage: dict[str, int | float] = {} + money_usage: dict[str, int | float] = {} + for result in results: + for key, value in result.token_usage.items(): + token_usage[key] = token_usage.get(key, 0) + value + for key, value in result.money_usage.items(): + money_usage[key] = money_usage.get(key, 0) + value + error = next((result.error for result in results if result.error), None) + return { + "ok": error is None, + "error": error, + "token_usage": token_usage, + "money_usage": money_usage, + "extra": { + "responses": [ + result.raw_response for result in results if result.raw_response is not None + ], + }, + } + + @staticmethod + def _build_response( + message: dict[str, Any], + tool_calls: list[ToolCall], + content: str | None = None, + ) -> APICallSample: + """Build a response while retaining enough fields to reconstruct ``message``.""" + message_extra = dict(message) + message_content = message_extra.pop("content", content) + raw_tool_calls = message_extra.get("tool_calls") + normalized_raw_tool_calls = [call.raw for call in tool_calls if isinstance(call.raw, dict)] + if raw_tool_calls == normalized_raw_tool_calls and raw_tool_calls != []: + message_extra.pop("tool_calls") + return APICallSample( + content=message_content, + tool_calls=tool_calls, + message_extra=message_extra, + ) + + @abstractmethod + def format_response( + self, + message: Any, + tool_calls: list[ToolCall], + content: str | None = None, + ) -> APICallSample: + """Convert one provider message into a normalized API-call sample.""" + raise NotImplementedError + + def __call__( + self, + messages: list[dict[str, Any]] | str, + callback: ProgressCallback | None = None, + **kwargs: Any, + ) -> APICallSummary: + """Request the provider and wrap its result generator.""" + if isinstance(messages, str): + messages = [{"role": "user", "content": messages}] + if callback is not None: + kwargs["callback"] = callback + if not isinstance(n := kwargs.get("n", 1), int) or n < 1: + raise ValueError("n must be a positive integer") + generator = self._normalize_request( + self._request_samples(messages, **kwargs), + requested_samples=n, + ) + return APICallSummary(generator) + + def _normalize_request( + self, + generator: Generator[APICallSample, None, dict[str, Any]], + requested_samples: int, + ) -> Generator[APICallSample, None, dict[str, Any]]: + """Normalize provider records, capture safe failures, and write call logs.""" + call_id = uuid.uuid4().hex + completed_samples = 0 + try: + while True: + response = next(generator) + if not isinstance(response, APICallSample): + raise TypeError( + "Provider generators must yield APICallSample instances, " + f"not {type(response).__name__}" + ) + if completed_samples >= requested_samples: + raise ValueError( + f"Provider yielded more than the requested n={requested_samples} samples" + ) + completed_samples += 1 + self._write_call_log( + call_id, + "response", + { + "sample": completed_samples, + "response": response.message, + }, + ) + yield response + except StopIteration as stop: + result = stop.value + if not isinstance(result, dict): + raise TypeError("Provider must return an API result dictionary") + required = {"ok", "error", "token_usage", "money_usage", "extra"} + if missing := sorted(required - result.keys()): + raise ValueError( + "Provider API result is missing required fields: " + ", ".join(missing) + ) + if unexpected := sorted(result.keys() - required): + raise ValueError( + "Provider API result has unsupported fields; put them in extra: " + + ", ".join(unexpected) + ) + if not isinstance(result["ok"], bool): + raise TypeError("Provider API result field 'ok' must be bool") + if result["error"] is not None and not isinstance(result["error"], str): + raise TypeError("Provider API result field 'error' must be str or None") + if result["ok"] != (result["error"] is None): + raise ValueError("Provider API result fields 'ok' and 'error' are inconsistent") + for field in ("token_usage", "money_usage", "extra"): + if not isinstance(result[field], dict): + raise TypeError(f"Provider API result field {field!r} must be dict") + if completed_samples < requested_samples and result["error"] is None: + raise ValueError( + f"Provider returned {completed_samples} of {requested_samples} " + "requested responses without reporting an error" + ) + result["extra"].update( + { + "requested_samples": requested_samples, + "completed_samples": completed_samples, + } + ) + self._write_call_log(call_id, "result", result) + return result + finally: + self._cancel_requested.clear() + + def _write_call_log( + self, + call_id: str, + record_type: str, + payload: dict[str, Any], + ) -> None: + """Append one final-response or result record when API logging is enabled.""" + if self.save_path is None: + return + path = ( + self.save_path + if self.save_path.suffix == ".jsonl" + else self.save_path / "api_calls.jsonl" + ) + record = { + "type": record_type, + "call_id": call_id, + "timestamp": time.time(), + "provider": type(self).__name__, + "model": self.model, + **payload, + } + try: + path.parent.mkdir(parents=True, exist_ok=True) + with _api_log_lock, path.open("a", encoding="utf-8") as stream: + json.dump(record, stream, ensure_ascii=False, default=str) + stream.write("\n") + except OSError as error: + _logger.warning(f"Unable to append API call log {path}: {error}") + + def cancel(self) -> str | None: + """Request interruption at the next API-owned cancellation boundary.""" + self._cancel_requested.set() + return None diff --git a/src/sr_harness/api/deepseek_api.py b/src/sr_harness/api/deepseek_api.py new file mode 100644 index 0000000000000000000000000000000000000000..20b8dfc900d6b5617c49255b1126bb1e535bc296 --- /dev/null +++ b/src/sr_harness/api/deepseek_api.py @@ -0,0 +1,128 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +import httpx +from openai import DefaultHttpxClient, OpenAI +from typing import Any +from .base_api import BaseAPI, ProgressCallback, ProviderSampleResult +from .utils import RemoteModelCatalog +from ..core import APICallSample, ToolCall + + +@BaseAPI.register("deepseek") +class DeepSeekAPI(BaseAPI): + """DeepSeek adapter accepting models in its live provider catalog.""" + + def __init__(self, model: str = "deepseek-chat", **kwargs: Any) -> None: + super().__init__(model=model, **kwargs) + self._model_catalog = RemoteModelCatalog( + lambda url: httpx.Client(proxy=self.proxy_url(url), trust_env=False) + ) + + def format_response( + self, message: dict[str, Any], tool_calls: list[ToolCall], content: str | None = None + ) -> APICallSample: + """Convert one DeepSeek message into the public response contract.""" + return self._build_response(message, tool_calls, content) + + @property + def model_list(self) -> list[str]: + """Return the current DeepSeek model catalog.""" + endpoint = self.get_env("DEEPSEEK_ENDPOINT", "https://api.deepseek.com") + return self._model_catalog.get( + f"{endpoint.rstrip('/')}/models", + description="DeepSeek model catalog", + api_key=self.get_env("DEEPSEEK_API_KEY", required=True), + ) + + def _request_sample( + self, + messages: list[dict[str, Any]], + *, + sample_index: int, + max_tokens=4096, + temperature=1, + callback: ProgressCallback | None = None, + ) -> ProviderSampleResult: + endpoint = self.get_env("DEEPSEEK_ENDPOINT", "https://api.deepseek.com") + client = OpenAI( + api_key=self.get_env("DEEPSEEK_API_KEY", required=True), + base_url=endpoint, + http_client=DefaultHttpxClient( + proxy=self.proxy_url(endpoint), + trust_env=False, + ), + ) + payload = { + "model": self.model, + "messages": [ + { + key: value + for key, value in message.items() + if not (key == "tool_calls" and value == []) + } + for message in messages + ], + "max_tokens": max_tokens, + "temperature": temperature, + } + if self.tool_box is None: + pass + elif not self.tool_box.native_tool_calls: + description = ( + "Use the following tools when a tool call is needed. " + "Return tool calls in the specified format.\n\n" + f"{self.tool_box.format_tools()}" + ) + if payload["messages"][0]["role"] in {"system", "developer"}: + first = payload["messages"][0] + payload["messages"][0] = { + **first, + "content": f"{first['content']}\n\n{description}", + } + else: + payload["messages"].insert(0, {"role": "system", "content": description}) + else: + tools = self.tool_box.format_tools() + if not isinstance(tools, list): + raise TypeError("Native tool parser must return JSON tool descriptions") + payload["tools"] = tools + payload["tool_choice"] = "auto" + + completion, raw_response, message, content = self.openai_chat_completion( + client, + payload, + sample=sample_index, + callback=callback, + ) + tool_calls = self.parse_tool_calls(message, content) + token_usage = self.openai_token_usage(completion, other_key="other") + money_usage = { + "prompt": 0.28 / 1e6 * token_usage.get("prompt", 0), + "answer": 0.42 / 1e6 * token_usage.get("answer", 0), + } + if "other" in token_usage: + money_usage["other"] = 0.42 / 1e6 * token_usage["other"] + choices = raw_response.get("choices") or [{}] + finish_reason = raw_response.get("finish_reason") or choices[0].get("finish_reason") + if finish_reason == "length": + partial_message = dict(message) + partial_message.pop("tool_calls", None) + return ProviderSampleResult( + response=self.format_response(partial_message, [], content), + token_usage=token_usage, + money_usage=money_usage, + raw_response=raw_response, + error=( + f"DeepSeekAPI({self.model}) exhausted max_tokens={max_tokens}; " + "increase the Agent's maximum output length and retry." + ), + ) + if not (tool_calls or content.strip()): + raise ValueError( + f"DeepSeekAPI({self.model}) returned empty content and no usable tool calls." + ) + return ProviderSampleResult( + response=self.format_response(message, tool_calls, content), + token_usage=token_usage, + money_usage=money_usage, + raw_response=raw_response, + ) diff --git a/src/sr_harness/api/error_filter.py b/src/sr_harness/api/error_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..77a367ea52fd04c28b67c81cc5a410413507c5ef --- /dev/null +++ b/src/sr_harness/api/error_filter.py @@ -0,0 +1,42 @@ +"""Temporary, weakly coupled screening for errors shown to frontend users.""" + +from __future__ import annotations + +import os +from collections.abc import Mapping + + +_PRIVATE_PATH_MARKERS = ("yuzihan",) +_WITHHELD_MESSAGE = ( + "The model API request failed. Its detailed error was written to the server log " + "because it may contain sensitive information." +) + + +def screen_frontend_error( + error: BaseException, + environment: Mapping[str, str] | None = None, +) -> tuple[str, tuple[str, ...]]: + """Return the raw error unless a temporary sensitive marker is detected.""" + message = str(error).strip() or type(error).__name__ + findings: list[str] = [] + chain: list[BaseException] = [] + current: BaseException | None = error + while current is not None and current not in chain: + chain.append(current) + current = current.__cause__ or current.__context__ + inspected = "\n".join(str(item) for item in chain) + lowered = inspected.casefold() + if any(marker.casefold() in lowered for marker in _PRIVATE_PATH_MARKERS): + findings.append("private-path marker") + + values = dict(os.environ) + if environment is not None: + values.update(environment) + for name, value in values.items(): + if not name.upper().endswith("API_KEY") or len(value) < 16: + continue + if value[-3:] in inspected: + findings.append(f"{name} suffix") + + return (_WITHHELD_MESSAGE if findings else message), tuple(sorted(set(findings))) diff --git a/src/sr_harness/api/gemini_api.py b/src/sr_harness/api/gemini_api.py new file mode 100644 index 0000000000000000000000000000000000000000..c6a03e53b6bda568cf944f9012e7cb6e43f9dc8f --- /dev/null +++ b/src/sr_harness/api/gemini_api.py @@ -0,0 +1,162 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +import httpx +from typing import Any, Generator, List, Dict +from google import genai +from google.genai import types +from .base_api import BaseAPI +from ..core import APICallSample, ToolCall + + +@BaseAPI.register("gemini") +class GeminiAPI(BaseAPI): + """Google Gemini adapter for the explicitly listed SDK workflows.""" + + def __init__(self, model: str = "gemini-2.5-pro", **kwargs: Any) -> None: + super().__init__(model=model, **kwargs) + + def cancel(self) -> str: + """Report that the current synchronous SDK request cannot be preempted.""" + return ( + "GeminiAPI does not support force-interrupting an active non-streaming request. " + "The Agent will pause at its next safe boundary." + ) + + def format_response( + self, message: dict[str, Any], tool_calls: list[ToolCall], content: str | None = None + ) -> APICallSample: + """Convert one Gemini message into one API-call sample.""" + return self._build_response(message, tool_calls, content) + + @property + def model_list(self) -> list[str]: + """Return the Gemini models explicitly supported by this adapter.""" + return [ + "gemini-2.5-pro", + "gemini-2.5-flash", + "gemini-2.5-flash-lite-preview-06-17", + "gemini-2.0-flash", + "gemini-2.0-flash-lite", + ] + + def _request_samples( + self, messages: List[Dict[str, str]], n=1, callback=None + ) -> Generator[APICallSample, None, dict[str, Any]]: + ## Ensure this is a generator + yield from [] + messages = [dict(message) for message in messages] + if self.tool_box is None: + pass + elif not self.tool_box.native_tool_calls: + description = ( + "Use the following tools when a tool call is needed. " + "Return tool calls in the specified format.\n\n" + f"{self.tool_box.format_tools()}" + ) + if messages[0]["role"] in {"system", "developer"}: + first = messages[0] + messages[0] = { + **first, + "content": f"{first['content']}\n\n{description}", + } + else: + messages.insert(0, {"role": "system", "content": description}) + else: + raise NotImplementedError( + "GeminiAPI does not support parser='openai' native tool calls." + ) + api_key = self.get_env("GEMINI_API_KEY") + config = types.GenerateContentConfig( + candidate_count=n, + thinking_config=types.ThinkingConfig( + thinking_budget=0, + include_thoughts=True, + ), + ) + if self.model in ["gemini-2.0-flash", "gemini-2.0-flash-lite"]: + config.thinking_config = None + client = genai.Client( + api_key=api_key, + http_options=types.HttpOptions( + httpx_client=httpx.Client( + proxy=self.proxy_url(), + trust_env=False, + ), + ), + ) + self.report_progress(callback, {"type": "start", "sample": 1}) + try: + response = client.models.generate_content( + model=self.model, + contents=messages, + config=config, + ) + except InterruptedError: + raise + except Exception as error: + public_error = self.error_message(error) + self.report_progress(callback, { + "type": "failed", + "sample": 1, + "error": public_error, + }) + return { + "ok": False, + "error": public_error, + "token_usage": {}, + "money_usage": {}, + "extra": {}, + } + usage = response.usage_metadata + prompt_tokens = usage.prompt_token_count + reason_tokens = usage.thoughts_token_count or 0 + answer_tokens = usage.total_token_count - prompt_tokens - reason_tokens + token_usage = { + "prompt": prompt_tokens, + "answer": answer_tokens, + "reason": reason_tokens, + } + price_usage = {"total": 0.0} + details = [] + for candidate in response.candidates: + for part in candidate.content.parts: + if not (content := part.text): + continue + elif part.thought: + continue + else: + message = {"role": "assistant", "content": content} + tool_call = self.parse_tool_calls(message, content) + details.append( + { + "content": content, + "tool_call": tool_call, + "token_usage": usage, + "price_usage": price_usage, + "response": candidate.to_json_dict(), + "message": message, + } + ) + sample_response = self.format_response(message, tool_call, content) + sample = len(details) + if callback is not None: + self.report_progress(callback, { + "type": "complete", + "sample": sample, + "content": sample_response.content, + "reasoning": sample_response.reasoning, + "tool_calls": [call.raw for call in sample_response.tool_calls], + }) + if sample < n: + self.report_progress(callback, { + "type": "start", + "sample": sample + 1, + }) + yield sample_response + break + return { + "ok": True, + "error": None, + "token_usage": token_usage, + "money_usage": price_usage, + "extra": {"responses": [detail["response"] for detail in details]}, + } diff --git a/src/sr_harness/api/lmstudio_api.py b/src/sr_harness/api/lmstudio_api.py new file mode 100644 index 0000000000000000000000000000000000000000..35a1ac8cc631c84d2373a9643b2d4f52d8f65a50 --- /dev/null +++ b/src/sr_harness/api/lmstudio_api.py @@ -0,0 +1,214 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +from __future__ import annotations + +import logging +from typing import Any, Dict, Generator, List +from urllib.parse import urlsplit, urlunsplit + +import requests +from dotenv import load_dotenv + +from .base_api import BaseAPI +from ..core import APICallSample, ToolCall + +_logger = logging.getLogger(f"sr_harness.{__name__}") + + +@BaseAPI.register("lmstudio") +class LMStudioAPI(BaseAPI): + """LLM API adapter for an LM Studio server. + + ``LMSTUDIO_ENDPOINT`` may point at LM Studio's native ``/api/v1/chat`` + endpoint, as recommended by LM Studio. SRAgent needs multi-turn messages + and custom function tools, so requests are sent to the OpenAI-compatible + ``/v1/chat/completions`` endpoint on the same server. + """ + + def __init__(self, model: str = "qwen_qwen3-4b-instruct-2507", **kwargs: Any) -> None: + super().__init__(model=model, **kwargs) + + def cancel(self) -> str: + """Report that the current synchronous HTTP request cannot be preempted.""" + return ( + "LMStudioAPI does not support force-interrupting an active non-streaming request. " + "The Agent will pause at its next safe boundary." + ) + + def format_response( + self, message: dict[str, Any], tool_calls: list[ToolCall], content: str | None = None + ) -> APICallSample: + """Convert one LM Studio message into one API-call sample.""" + return self._build_response(message, tool_calls, content) + + @property + def model_list(self) -> list[str]: + """Return the default LM Studio model configured for this adapter.""" + return ["qwen_qwen3-4b-instruct-2507"] + + @staticmethod + def normalize_endpoint(endpoint: str) -> str: + """Return the OpenAI-compatible chat-completions URL. + + Args: + endpoint: The endpoint value. + + Returns: + str: The operation result. + """ + endpoint = endpoint.strip() + parts = urlsplit(endpoint) + if parts.scheme not in {"http", "https"} or not parts.netloc: + raise ValueError(f"Invalid LMSTUDIO_ENDPOINT: {endpoint!r}") + + path = ( + parts.path.rstrip("/").removesuffix("/api/v1/chat").removesuffix("/v1/chat/completions") + + "/v1/chat/completions" + ) + return urlunsplit((parts.scheme, parts.netloc, path, "", "")) + + def _request_samples( + self, + messages: List[Dict[str, str]], + n: int = 1, + max_tokens: int = 4096, + temperature: float = 1.0, + top_p: float = 1.0, + callback=None, + ) -> Generator[APICallSample, None, dict[str, Any]]: + yield from [] + load_dotenv() + + endpoint = self.normalize_endpoint(self.get_env("LMSTUDIO_ENDPOINT", required=True)) + api_key = self.get_env("LMSTUDIO_API_KEY", required=True) + payload = { + "model": self.model, + "messages": [dict(message) for message in messages], + "n": n, + "top_p": top_p, + "max_tokens": max_tokens, + "temperature": temperature, + "stream": False, + } + if self.tool_box is None: + pass + elif not self.tool_box.native_tool_calls: + description = ( + "Use the following tools when a tool call is needed. " + "Return tool calls in the specified format.\n\n" + f"{self.tool_box.format_tools()}" + ) + if payload["messages"][0]["role"] in {"system", "developer"}: + first = payload["messages"][0] + payload["messages"][0] = { + **first, + "content": f"{first['content']}\n\n{description}", + } + else: + payload["messages"].insert(0, {"role": "system", "content": description}) + else: + tools = self.tool_box.format_tools() + if not isinstance(tools, list): + raise TypeError("Native tool parser must return JSON tool descriptions") + payload["tools"] = tools + payload["tool_choice"] = "auto" + + # LM Studio is normally on the local network. Ignore shell proxy + # variables so a loopback proxy cannot intercept or block the request. + session = requests.Session() + session.trust_env = False + timeout = float(self.get_env("LMSTUDIO_TIMEOUT", "300")) + headers = { + "Authorization": f"Bearer {api_key}", + "Content-Type": "application/json", + } + + max_retry = 3 + self.report_progress(callback, {"type": "start", "sample": 1}) + for attempt in range(1, max_retry + 1): + try: + response = session.post(endpoint, headers=headers, json=payload, timeout=timeout) + response.raise_for_status() + response_dict = response.json() + choices = response_dict.get("choices") or [] + if not choices: + raise ValueError(f"LMStudioAPI({self.model}) returned no choices.") + break + except InterruptedError: + raise + except Exception as error: + public_error = self.error_message(error) + if attempt == max_retry: + self.report_progress(callback, { + "type": "failed", + "sample": 1, + "error": public_error, + }) + return { + "ok": False, + "error": public_error, + "token_usage": {}, + "money_usage": {}, + "extra": {}, + } + if callback is not None: + self.report_progress(callback, { + "type": "retry", + "sample": 1, + "attempt": attempt, + "error": public_error, + }) + delay = min(float(2 ** (attempt - 1)), 30.0) + _logger.info( + f"Retrying LMStudioAPI({self.model}) in {delay:g}s " + f"(attempt {attempt}/{max_retry})." + ) + self.wait_before_retry(delay) + + details = [] + for sample, choice in enumerate(choices, 1): + message = choice.get("message") or {} + content = message.get("content") or "" + tool_call = self.parse_tool_calls(message, content) + if not (content.strip() or tool_call): + _logger.warning(f"LMStudioAPI({self.model}) returned an empty choice.") + details.append({"content": content, "tool_call": tool_call, "message": message}) + sample_response = self.format_response(message, tool_call, content) + if callback is not None: + self.report_progress(callback, { + "type": "complete", + "sample": sample, + "content": sample_response.content, + "reasoning": sample_response.reasoning, + "tool_calls": [call.raw for call in sample_response.tool_calls], + }) + if sample < len(choices): + self.report_progress(callback, { + "type": "start", + "sample": sample + 1, + }) + yield sample_response + + raw_usage = response_dict.get("usage") or {} + prompt_tokens = int(raw_usage.get("prompt_tokens") or 0) + completion_tokens = int(raw_usage.get("completion_tokens") or 0) + reasoning_tokens = int( + (raw_usage.get("completion_tokens_details") or {}).get("reasoning_tokens") or 0 + ) + token_usage = { + "prompt": prompt_tokens, + "answer": max(completion_tokens - reasoning_tokens, 0), + } + if reasoning_tokens: + token_usage["reason"] = reasoning_tokens + total_tokens = int(raw_usage.get("total_tokens") or prompt_tokens + completion_tokens) + accounted = prompt_tokens + completion_tokens + if total_tokens > accounted: + token_usage["other"] = total_tokens - accounted + + return { + "ok": True, + "error": None, + "token_usage": token_usage, + "money_usage": {"total": 0.0}, + "extra": {"responses": [response_dict]}, + } diff --git a/src/sr_harness/api/manual_api.py b/src/sr_harness/api/manual_api.py new file mode 100644 index 0000000000000000000000000000000000000000..49b5a2b27845d9fa8b45f09e79178930d373274d --- /dev/null +++ b/src/sr_harness/api/manual_api.py @@ -0,0 +1,97 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +import logging +import tempfile +from pathlib import Path +from typing import Any, Generator, List, Dict +from .base_api import BaseAPI +from ..core import APICallSample, ToolCall + +_logger = logging.getLogger(f"sr_harness.{__name__}") + + +@BaseAPI.register("manual") +class ManualAPI(BaseAPI): + """Interactive manual-response provider adapter.""" + + def __init__(self, model="manual", save_path=None, **kwargs): + super().__init__(model=model, **kwargs) + self.save_path = Path(save_path or tempfile.gettempdir()) + + def cancel(self) -> str: + """Report that terminal input cannot be preempted through the web control.""" + return ( + "ManualAPI does not support force-interrupting terminal input. " + "The Agent will pause at its next safe boundary." + ) + + def format_response( + self, message: dict[str, Any], tool_calls: list[ToolCall], content: str | None = None + ) -> APICallSample: + """Convert one manually entered message into one API-call sample.""" + return self._build_response(message, tool_calls, content) + + @property + def model_list(self) -> list[str]: + """Return the synthetic model identifier used by the manual provider.""" + return ["manual"] + + def _request_samples( + self, messages: List[Dict[str, str]], n=1, callback=None + ) -> Generator[APICallSample, None, dict[str, Any]]: + import pyperclip, tiktoken + + prompt = "\n---\n".join(f"[role: {msg['role']}] {msg['content']}" for msg in messages) + + # Copy the prompt to clipboard and save it to a file for manual input + pyperclip.copy(prompt) + prompt_path = self.save_path / "prompt.md" + prompt_path.write_text(prompt, encoding="utf-8") + _logger.note( + f"Prompt copied to clipboard and saved to {prompt_path}. " + f"Please send it into any LLM and return the response content for {n} times." + ) + details = [] + for idx in range(1, n + 1): + self.report_progress(callback, {"type": "start", "sample": idx}) + # Wait for user input or clipboard content + content = input( + f"Please enter the generated content {idx}/{n} (press Enter to use clipboard): " + ) + if not content.strip(): + content = pyperclip.paste() + # Calculate token usage + encoding = tiktoken.encoding_for_model("gpt-3.5") + prompt_tokens = len(encoding.encode(prompt)) + answer_tokens = len(encoding.encode(content)) + token_usage = {"prompt": prompt_tokens, "answer": answer_tokens} + tool_call = self.parse_tool_calls({"role": "assistant", "content": content}, content) + message = {"role": "assistant", "content": content} + details.append( + { + "content": content, + "tool_call": tool_call, + "token_usage": token_usage, + "message": message, + } + ) + sample_response = self.format_response(message, tool_call, content) + if callback is not None: + self.report_progress(callback, { + "type": "complete", + "sample": idx, + "content": sample_response.content, + "reasoning": sample_response.reasoning, + "tool_calls": [call.raw for call in sample_response.tool_calls], + }) + yield sample_response + token_usage = {"prompt": 0, "answer": 0} + for detail in details: + token_usage["prompt"] += detail["token_usage"]["prompt"] + token_usage["answer"] += detail["token_usage"]["answer"] + return { + "ok": True, + "error": None, + "token_usage": token_usage, + "money_usage": {"prompt": 0, "answer": 0}, + "extra": {}, + } diff --git a/src/sr_harness/api/openai_api.py b/src/sr_harness/api/openai_api.py new file mode 100644 index 0000000000000000000000000000000000000000..6778a68be2e3448dc84b5965f1c1b90275cf7774 --- /dev/null +++ b/src/sr_harness/api/openai_api.py @@ -0,0 +1,528 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +import logging +from copy import deepcopy +from openai import AzureOpenAI, DefaultHttpxClient +from openai.types.responses import Response +from openai.types.chat import ChatCompletion +from collections import defaultdict +from typing import Any, Generator, List, Dict +from .base_api import BaseAPI, ProgressCallback +from ..core import APICallSample, ToolCall + +_logger = logging.getLogger(f"sr_harness.{__name__}") + + +@BaseAPI.register("openai") +class OpenAIAPI(BaseAPI): + """Azure OpenAI adapter for the gpt-4o-mini and gpt-5-mini workflows.""" + + def __init__(self, model: str = "gpt-5-mini", **kwargs: Any) -> None: + super().__init__(model=model, **kwargs) + self.dummy_message = 'Please proofread the message above and say "I have received it."' + + def cancel(self) -> str: + """Report that the current synchronous SDK request cannot be preempted.""" + return ( + "OpenAIAPI does not support force-interrupting an active non-streaming request. " + "The Agent will pause at its next safe boundary." + ) + + def format_response( + self, message: Any, tool_calls: list[ToolCall], content: str | None = None + ) -> APICallSample: + """Convert one OpenAI or Azure message into one API-call sample.""" + if hasattr(message, "to_dict"): + message = message.to_dict() + elif hasattr(message, "model_dump"): + message = message.model_dump() + elif not isinstance(message, dict): + raise TypeError(f"Unsupported OpenAI message type: {type(message).__name__}") + return self._build_response(message, tool_calls, content) + + @property + def model_list(self) -> list[str]: + """Return the OpenAI and Azure models explicitly supported by this adapter.""" + return ["gpt-4o-mini", "gpt-5-mini"] + + def _request_samples( + self, + messages: List[Dict[str, str]], + n=1, + max_tokens=4096, + temperature=1.0, + top_p=1.0, + use_chat_completions=False, + callback: ProgressCallback | None = None, + ) -> Generator[APICallSample, None, dict[str, Any]]: + """ + Keyword Args: + model (str): The model name to use. Default is 'gpt-4o-mini'. + max_tokens (int): The maximum number of tokens to generate. Default is 1024. + temperature (float): Sampling temperature. Default is 1.0. + top_p (float): Nucleus sampling probability. Default is 1.0. + n (int): Number of completions to generate. Default is 1. + """ + if self.model == "gpt-4o-mini" and not use_chat_completions: + use_chat_completions = True + _logger.warning( + "Turn to use create_chat_completions for gpt-4o-mini model to save token cost." + ) + + if use_chat_completions: + results = yield from self.create_chat_completions( + messages, + n=n, + max_tokens=max_tokens, + temperature=temperature, + top_p=top_p, + callback=callback, + ) + return results + else: + results = yield from self.create_responses( + messages, + n=n, + max_tokens=max_tokens, + temperature=temperature, + top_p=top_p, + callback=callback, + ) + return results + + def build_native_tool_description(self, use_chat_completions: bool = False) -> List[Dict]: + """Build native tool description. + + Args: + use_chat_completions: The use chat completions value. + + Returns: + List[Dict]: The operation result. + """ + tools = self.tool_box.format_tools() + if not isinstance(tools, list): + raise TypeError("Native tool parser must return JSON tool descriptions") + if use_chat_completions: + return tools + return [ + { + "type": "function", + "name": tool["function"]["name"], + "description": tool["function"].get("description", ""), + "parameters": tool["function"].get( + "parameters", {"type": "object", "properties": {}} + ), + } + for tool in tools + ] + + def create_responses( + self, + messages: List[Dict[str, str]], + n: int = 1, + max_tokens: int = 4096, + temperature: float = 1.0, + top_p: float = 1.0, + callback: ProgressCallback | None = None, + ) -> Generator[APICallSample, None, dict[str, Any]]: + """Create responses. + + Args: + messages: Conversation messages in provider-compatible order. + n: The n value. + max_tokens: The max tokens value. + temperature: The temperature value. + top_p: The top p value. + + Returns: + Generator yielding call samples and returning aggregate metadata. + """ + ## Ensure this is a generator + yield from [] + client = AzureOpenAI( + api_version=self.get_env("OPENAI_API_VERSION", required=True), + azure_endpoint=(endpoint := self.get_env("OPENAI_ENDPOINT", required=True)), + api_key=self.get_env("OPENAI_API_KEY", required=True), + http_client=DefaultHttpxClient( + proxy=self.proxy_url(endpoint), + trust_env=False, + ), + ) + payload = { + "input": deepcopy(messages), # 因为后面可能要 pop, 所以 deepcopy 一下 + "reasoning": {"summary": "auto"}, + "model": self.model, + "top_p": top_p, + "max_output_tokens": max_tokens, + "temperature": temperature, + # "prompt_cache_retention": "24h" # 官网上说有这个参数可以延长 cache 保存时间,但实际用起来会报错 + # "n": n, # OpenAI Response API 不支持 parameter n + } + if self.tool_box is None: + pass + elif not self.tool_box.native_tool_calls: + description = ( + "Use the following tools when a tool call is needed. " + "Return tool calls in the specified format.\n\n" + f"{self.tool_box.format_tools()}" + ) + if payload["input"][0]["role"] in {"system", "developer"}: + first = payload["input"][0] + payload["input"][0] = { + **first, + "content": f"{first['content']}\n\n{description}", + } + else: + payload["input"].insert(0, {"role": "system", "content": description}) + else: + payload["tools"] = self.build_native_tool_description() + payload["tool_choice"] = "auto" + if payload["input"][0]["role"] == "system": + ## instruction 无法在多轮对话中保留,不好用 + # payload['instructions'] = payload['input'].pop(0)['content'] + ## 改用据说效果与 instruction 等价的 developer 角色 + payload["input"][0]["role"] = "developer" + + if n == 1: + self.report_progress(callback, {"type": "start", "sample": 1}) + try: + response = client.responses.create(**payload) + response_dict = response.to_dict() + usage = self.parse_usage(response) + message_object = response.choices[0].message + message = ( + message_object.to_dict() + if hasattr(message_object, "to_dict") + else message_object.model_dump() + ) + content = response.output_text + tool_call = self.parse_tool_calls(message, content) + sample_response = self.format_response(message, tool_call, content) + if callback is not None: + self.report_progress(callback, { + "type": "complete", + "sample": 1, + "content": sample_response.content, + "reasoning": sample_response.reasoning, + "tool_calls": [call.raw for call in sample_response.tool_calls], + }) + yield sample_response + results = { + "ok": True, + "error": None, + "token_usage": usage.get("token", {}), + "money_usage": usage.get("price", {}), + "extra": {"responses": [response_dict]}, + } + except InterruptedError: + raise + except Exception as e: + public_error = self.error_message(e) + self.report_progress(callback, { + "type": "failed", + "sample": 1, + "error": public_error, + }) + return { + "ok": False, + "error": public_error, + "token_usage": {}, + "money_usage": {}, + "extra": {}, + } + return results + else: + self.report_progress(callback, {"type": "start", "sample": 1}) + try: + responses = [] + details = [] + ## 构造 payload 将除最后一条 message 之外的所有前置信息输入模型 + assert payload["input"][-1]["role"] == "user", ( + "When n > 1, the last message must be from user." + ) + last_message = payload["input"].pop(-1) + payload["input"].append({"role": "user", "content": self.dummy_message}) + response = client.responses.create(**payload) + usage = self.parse_usage(response) + responses.append(response) + ## 构造 child payload 多次输入最后一条 message 以获得多条回复并尽量增加 cached input token 的命中率 + child_payload = deepcopy(payload) + child_payload["previous_response_id"] = response.id + child_payload["input"] = [last_message] + for idx in range(1, n + 1): + child_response = client.responses.create(**child_payload) + responses.append(child_response) + child_response_dict = child_response.to_dict() + message = child_response.choices[0].message.to_dict() + content = message["content"] + tool_call = self.parse_tool_calls(message, content) + sample_response = self.format_response(message, tool_call, content) + if callback is not None: + self.report_progress(callback, { + "type": "complete", + "sample": idx, + "content": sample_response.content, + "reasoning": sample_response.reasoning, + "tool_calls": [call.raw for call in sample_response.tool_calls], + }) + if idx < n: + self.report_progress(callback, { + "type": "start", + "sample": idx + 1, + }) + yield sample_response + new_usage = self.parse_usage(child_response) + for k, v in new_usage["token"].items(): + usage["token"][k] = usage["token"].get(k, 0) + v + for k, v in new_usage["price"].items(): + usage["price"][k] = usage["price"].get(k, 0) + v + details.append( + { + "content": content, + "tool_call": tool_call, + "token_usage": dict(new_usage.get("token", {})), + "price_usage": dict(new_usage.get("price", {})), + "response": child_response_dict, + } + ) + results = { + "ok": True, + "error": None, + "token_usage": usage.get("token", {}), + "money_usage": usage.get("price", {}), + "extra": {"responses": [resp.to_dict() for resp in responses]}, + } + except InterruptedError: + raise + except Exception as e: + public_error = self.error_message(e) + self.report_progress(callback, { + "type": "failed", + "sample": min(len(details) + 1, n), + "error": public_error, + }) + return { + "ok": False, + "error": public_error, + "token_usage": {}, + "money_usage": {}, + "extra": {}, + } + return results + + def create_chat_completions( + self, + messages: List[Dict[str, str]], + n: int = 1, + max_tokens: int = 4096, + temperature: float = 1.0, + top_p: float = 1.0, + callback: ProgressCallback | None = None, + ) -> Generator[APICallSample, None, dict[str, Any]]: + """Create chat completions. + + Args: + messages: Conversation messages in provider-compatible order. + n: The n value. + max_tokens: The max tokens value. + temperature: The temperature value. + top_p: The top p value. + + Returns: + Generator yielding call samples and returning aggregate metadata. + """ + ## Ensure this is a generator + yield from [] + client = AzureOpenAI( + api_version=self.get_env("OPENAI_API_VERSION", required=True), + azure_endpoint=(endpoint := self.get_env("OPENAI_OLDTIME_ENDPOINT", required=True)), + api_key=self.get_env("OPENAI_API_KEY", required=True), + http_client=DefaultHttpxClient( + proxy=self.proxy_url(endpoint), + trust_env=False, + ), + ) + payload = { + "messages": deepcopy(messages), + "n": n, + "model": (model := self.model), + "top_p": top_p, + "max_tokens": max_tokens, + "temperature": temperature, + } + if self.tool_box is None: + pass + elif not self.tool_box.native_tool_calls: + description = ( + "Use the following tools when a tool call is needed. " + "Return tool calls in the specified format.\n\n" + f"{self.tool_box.format_tools()}" + ) + if payload["messages"][0]["role"] in {"system", "developer"}: + first = payload["messages"][0] + payload["messages"][0] = { + **first, + "content": f"{first['content']}\n\n{description}", + } + else: + payload["messages"].insert(0, {"role": "system", "content": description}) + else: + tools = self.tool_box.format_tools() + if not isinstance(tools, list): + raise TypeError("Native tool parser must return JSON tool descriptions") + payload["tools"] = tools + payload["tool_choice"] = "auto" + assert model == "gpt-4o-mini", "Only gpt-4o-mini model is supported in chat_completions." + + self.report_progress(callback, {"type": "start", "sample": 1}) + try: + response = client.chat.completions.create(**payload) + details = [] + for idx, choice in enumerate(response.choices, 1): + response_dict = {"choices": [{"message": choice.message.to_dict()}]} + message = choice.message.to_dict() + content = message["content"] + tool_call = self.parse_tool_calls(message, content) + details.append( + { + "content": content, + "tool_call": tool_call, + "token_usage": {}, + "price_usage": {}, + "response": response_dict, + } + ) + sample_response = self.format_response(message, tool_call, content) + if callback is not None: + self.report_progress(callback, { + "type": "complete", + "sample": idx, + "content": sample_response.content, + "reasoning": sample_response.reasoning, + "tool_calls": [call.raw for call in sample_response.tool_calls], + }) + if idx < len(response.choices): + self.report_progress(callback, { + "type": "start", + "sample": idx + 1, + }) + yield sample_response + usage = self.parse_chat_completions_usage(response) + for detail in details: + detail["token_usage"] = dict(usage.get("token", {})) + detail["price_usage"] = dict(usage.get("price", {})) + results = { + "ok": True, + "error": None, + "token_usage": usage.get("token", {}), + "money_usage": usage.get("price", {}), + "extra": {"responses": [response.to_dict()]}, + } + except InterruptedError: + raise + except Exception as e: + public_error = self.error_message(e) + self.report_progress(callback, { + "type": "failed", + "sample": 1, + "error": public_error, + }) + return { + "ok": False, + "error": public_error, + "token_usage": {}, + "money_usage": {}, + "extra": {}, + } + return results + + def parse_usage(self, response: Response) -> Dict: + """Parse usage. + + Args: + response: Provider response object. + + Returns: + Dict: The operation result. + """ + usage = {"token": defaultdict(float), "price": defaultdict(float)} + if response.model.startswith("gpt-5-mini"): + usage["token"]["cached"] = ( + cached_tokens := response.usage.input_tokens_details.cached_tokens + ) + usage["token"]["prompt"] = ( + prompt_tokens := response.usage.input_tokens - cached_tokens + ) + usage["token"]["reason"] = ( + reason_tokens := response.usage.output_tokens_details.reasoning_tokens + ) + usage["token"]["answer"] = ( + answer_tokens := response.usage.output_tokens - reason_tokens + ) + if ( + other := response.usage.total_tokens + - cached_tokens + - prompt_tokens + - reason_tokens + - answer_tokens + ) != 0: + usage["token"]["other"] = other + usage["price"]["cached"] = 0.025 * cached_tokens / 1e6 + usage["price"]["prompt"] = 0.25 * prompt_tokens / 1e6 + usage["price"]["reason"] = 2.0 * reason_tokens / 1e6 + usage["price"]["answer"] = 2.0 * answer_tokens / 1e6 + elif response.model.startswith("gpt-4o-mini"): + cached_tokens = 0 + usage["token"]["prompt"] += (prompt_tokens := response.usage.prompt_tokens) + usage["token"]["reason"] += ( + reason_tokens := response.usage.completion_tokens_details.reasoning_tokens + ) + usage["token"]["answer"] += ( + answer_tokens := response.usage.completion_tokens - reason_tokens + ) + if ( + other := response.usage.total_tokens + - cached_tokens + - prompt_tokens + - reason_tokens + - answer_tokens + ) != 0: + usage["token"]["other"] = other + usage["price"]["prompt"] += 0.15 * prompt_tokens / 1e6 + usage["price"]["reason"] += 0.60 * reason_tokens / 1e6 + usage["price"]["answer"] += 0.60 * answer_tokens / 1e6 + else: + raise NotImplementedError( + f"Usage parsing for model {response.model} is not implemented." + ) + return usage + + def parse_chat_completions_usage(self, response: ChatCompletion) -> Dict: + """Parse chat completions usage. + + Args: + response: Provider response object. + + Returns: + Dict: The operation result. + """ + usage = {"token": defaultdict(float), "price": defaultdict(float)} + if response.model.startswith("gpt-4o-mini"): + usage["token"]["prompt"] += (prompt_tokens := response.usage.prompt_tokens) + usage["token"]["reason"] += ( + reason_tokens := response.usage.completion_tokens_details.reasoning_tokens + ) + usage["token"]["answer"] += ( + answer_tokens := response.usage.completion_tokens - reason_tokens + ) + if ( + other := response.usage.total_tokens - prompt_tokens - reason_tokens - answer_tokens + ) > 0: + usage["token"]["other"] = other + usage["price"]["prompt"] += 0.15 * prompt_tokens / 1e6 + usage["price"]["reason"] += 0.60 * reason_tokens / 1e6 + usage["price"]["answer"] += 0.60 * answer_tokens / 1e6 + else: + raise NotImplementedError( + f"Usage parsing for model {response.model} is not implemented." + ) + return usage diff --git a/src/sr_harness/api/openrouter_api.py b/src/sr_harness/api/openrouter_api.py new file mode 100644 index 0000000000000000000000000000000000000000..4b3e9e8122e4ca820caacf80128aeecae4d42afd --- /dev/null +++ b/src/sr_harness/api/openrouter_api.py @@ -0,0 +1,145 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +import httpx +from openai import DefaultHttpxClient, OpenAI +from dotenv import load_dotenv +from typing import Any +from .base_api import BaseAPI, ProgressCallback, ProviderSampleResult +from .utils import RemoteModelCatalog +from ..core import APICallSample, ToolCall + + +@BaseAPI.register("openrouter") +class OpenRouterAPI(BaseAPI): + """OpenRouter adapter accepting text-generation models in its live catalog.""" + + def __init__(self, model: str = "qwen/qwen3.6-plus", **kwargs: Any) -> None: + super().__init__(model=model, **kwargs) + self._model_catalog = RemoteModelCatalog( + lambda url: httpx.Client(proxy=self.proxy_url(url), trust_env=False) + ) + + def format_response( + self, message: dict[str, Any], tool_calls: list[ToolCall], content: str | None = None + ) -> APICallSample: + """Convert one OpenRouter message into the public response contract.""" + return self._build_response(message, tool_calls, content) + + @property + def model_list(self) -> list[str]: + """Return the current OpenRouter text-generation model catalog.""" + endpoint = self.get_env("OPENROUTER_ENDPOINT", "https://openrouter.ai/api/v1") + + def supports_text_output(record: dict[str, Any]) -> bool: + architecture = record.get("architecture") + if not isinstance(architecture, dict): + return True + output_modalities = architecture.get("output_modalities") + return not isinstance(output_modalities, list) or "text" in output_modalities + + return self._model_catalog.get( + f"{endpoint.rstrip('/')}/models", + description="OpenRouter model catalog", + api_key=self.get_env("OPENROUTER_API_KEY"), + include=supports_text_output, + ) + + def _request_sample( + self, + messages: list[dict[str, Any]], + *, + sample_index: int, + max_tokens=4096, + temperature=1.0, + top_p=1.0, + callback: ProgressCallback | None = None, + ) -> ProviderSampleResult: + load_dotenv() + api_key = self.get_env("OPENROUTER_API_KEY", required=True) + endpoint = self.get_env("OPENROUTER_ENDPOINT", "https://openrouter.ai/api/v1") + client = OpenAI( + base_url=endpoint, + api_key=api_key, + http_client=DefaultHttpxClient( + proxy=self.proxy_url(endpoint), + trust_env=False, + ), + ) + payload = { + "model": self.model, + "messages": [dict(message) for message in messages], + "top_p": top_p, + "max_tokens": max_tokens, + "temperature": temperature, + } + if self.model == "openai/gpt-oss-120b": + # Keep benchmark inference reproducible across OpenRouter calls. The + # default router otherwise mixes providers with different weight + # quantizations (for example bf16 and fp8) in one experiment. + payload["extra_body"] = { + "provider": { + "order": ["AkashML"], + "allow_fallbacks": False, + } + } + if self.tool_box is None: + pass + elif not self.tool_box.native_tool_calls: + description = ( + "Use the following tools when a tool call is needed. " + "Return tool calls in the specified format.\n\n" + f"{self.tool_box.format_tools()}" + ) + if payload["messages"][0]["role"] in {"system", "developer"}: + first = payload["messages"][0] + payload["messages"][0] = { + **first, + "content": f"{first['content']}\n\n{description}", + } + else: + payload["messages"].insert(0, {"role": "system", "content": description}) + else: + tools = self.tool_box.format_tools() + if not isinstance(tools, list): + raise TypeError("Native tool parser must return JSON tool descriptions") + payload["tools"] = tools + payload["tool_choice"] = "auto" + + completion, raw_response, message, content = self.openai_chat_completion( + client, + payload, + sample=sample_index, + callback=callback, + ) + tool_calls = self.parse_tool_calls(message, content) + choices = raw_response.get("choices") or [{}] + finish_reason = raw_response.get("finish_reason") or choices[0].get("finish_reason") + token_usage = self.openai_token_usage(completion) + usage = getattr(completion, "usage", None) + money_usage = {"total": getattr(usage, "cost", 0)} if usage is not None else {} + if finish_reason == "length": + partial_message = dict(message) + partial_message.pop("tool_calls", None) + error = ( + f"OpenRouterAPI({self.model}) exhausted max_tokens={max_tokens}; " + "the response was truncated before the model completed its turn. " + "Increase the Agent's maximum output length and retry. " + f"模型已耗尽 max_tokens={max_tokens},响应在本轮完成前被截断;" + "请增大 Agent 的最大输出长度后重试。" + ) + return ProviderSampleResult( + response=self.format_response(partial_message, [], content), + token_usage=token_usage, + money_usage=money_usage, + raw_response=raw_response, + error=error, + ) + if not (tool_calls or content.strip()): + raise ValueError( + f"OpenRouterAPI({self.model}) returned empty content and no usable tool calls." + ) + return ProviderSampleResult( + response=self.format_response(message, tool_calls, content), + token_usage=token_usage, + money_usage=money_usage, + raw_response=raw_response, + ) diff --git a/src/sr_harness/api/siliconflow_api.py b/src/sr_harness/api/siliconflow_api.py new file mode 100644 index 0000000000000000000000000000000000000000..322a0326053a49edaceb0dba82e7e50017909b15 --- /dev/null +++ b/src/sr_harness/api/siliconflow_api.py @@ -0,0 +1,341 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +import httpx +import logging +import requests +from dotenv import load_dotenv +from typing import Any, Callable, Dict, Generator, List + +from .base_api import BaseAPI, ProgressCallback, ProviderSampleResult +from .utils import RemoteModelCatalog +from ..core import APICallSample, ToolCall + +_logger = logging.getLogger(f"sr_harness.{__name__}") + + +class _SiliconFlowRequestFailed(RuntimeError): + """Carry one SiliconFlow request failure already prepared for the frontend.""" + + +@BaseAPI.register("siliconflow") +class SiliconFlowAPI(BaseAPI): + """SiliconFlow adapter for the Qwen3-8B and Deepseek-V3 workflows.""" + + def __init__(self, model: str = "Qwen3-8B", **kwargs: Any) -> None: + super().__init__(model=model, **kwargs) + self._model_catalog = RemoteModelCatalog( + lambda url: httpx.Client(proxy=self.proxy_url(url), trust_env=False) + ) + + def cancel(self) -> str: + """Report that the current synchronous HTTP request cannot be preempted.""" + return ( + "SiliconFlowAPI does not support force-interrupting an active non-streaming " + "request. The Agent will pause at its next safe boundary." + ) + + def format_response( + self, message: dict[str, Any], tool_calls: list[ToolCall], content: str | None = None + ) -> APICallSample: + """Convert one SiliconFlow message into one API-call sample.""" + return self._build_response(message, tool_calls, content) + + @property + def model_list(self) -> list[str]: + """Return the current SiliconFlow chat-model catalog.""" + chat_endpoint = self.get_env( + "SILICONFLOW_ENDPOINT", + "https://api.siliconflow.cn/v1/chat/completions", + ) + normalized_endpoint = chat_endpoint.rstrip("/") + default_models_endpoint = normalized_endpoint.removesuffix("/chat/completions") + "/models" + models_endpoint = self.get_env( + "SILICONFLOW_MODELS_ENDPOINT", + default_models_endpoint, + ) + return self._model_catalog.get( + models_endpoint, + description="SiliconFlow chat-model catalog", + api_key=self.get_env("SILICONFLOW_API_KEY", required=True), + params={"sub_type": "chat"}, + ) + + def _post_json( + self, + url: str, + headers: dict[str, str], + payload: dict[str, Any], + *, + description: str, + sample: int | None = None, + validate: Callable[[dict[str, Any]], None] | None = None, + callback: ProgressCallback | None = None, + ) -> dict[str, Any]: + """POST one SiliconFlow request with provider-local retry handling.""" + for attempt in range(1, 4): + try: + proxy = self.proxy_url(url) + response = requests.request( + "POST", + url, + json=payload, + headers=headers, + proxies={"http": proxy, "https": proxy} if proxy else None, + ) + if response.status_code != 200: + response.raise_for_status() + data = response.json() + if validate is not None: + validate(data) + return data + except InterruptedError: + raise + except Exception as error: + public_error = self.error_message(error, description=description) + if attempt == 3: + update = {"type": "failed", "error": public_error} + if sample is not None: + update["sample"] = sample + self.report_progress(callback, update) + raise _SiliconFlowRequestFailed(public_error) from error + update = { + "type": "retry", + "attempt": attempt, + "error": public_error, + } + if sample is not None: + update["sample"] = sample + self.report_progress(callback, update) + delay = self.retry_delay(error, attempt) + _logger.info( + f"Retrying {description} in {delay:g}s (attempt {attempt}/3)." + ) + self.wait_before_retry(delay) + raise AssertionError("unreachable") + + @staticmethod + def _validate_chat_response(response: dict[str, Any]) -> None: + choices = response.get("choices") or [] + if not choices or any( + not ( + ((choice.get("message") or {}).get("content") or "").strip() + or (choice.get("message") or {}).get("tool_calls") + ) + for choice in choices + ): + raise ValueError("SiliconFlow returned an empty chat completion.") + + def _request_samples( + self, + messages: List[Dict[str, str]], + n=1, + max_tokens=1024, + temperature=1.0, + top_p=1.0, + callback: ProgressCallback | None = None, + ) -> Generator[APICallSample, None, dict[str, Any]]: + yield from [] + load_dotenv() + url = self.get_env( + "SILICONFLOW_ENDPOINT", + "https://api.siliconflow.cn/v1/chat/completions", + ) + headers = { + "Authorization": f"Bearer {self.get_env('SILICONFLOW_API_KEY', required=True)}", + "Content-Type": "application/json", + } + payload = { + "messages": [dict(message) for message in messages], + "n": n, + "stop": [], + "top_k": 50, + "top_p": top_p, + "min_p": 0.05, + "stream": False, + "thinking_budget": 1024, + "max_tokens": max_tokens, + "temperature": temperature, + "frequency_penalty": 0.5, + } + if self.tool_box is None: + pass + elif not self.tool_box.native_tool_calls: + description = ( + "Use the following tools when a tool call is needed. " + "Return tool calls in the specified format.\n\n" + f"{self.tool_box.format_tools()}" + ) + if payload["messages"][0]["role"] in {"system", "developer"}: + first = payload["messages"][0] + payload["messages"][0] = { + **first, + "content": f"{first['content']}\n\n{description}", + } + else: + payload["messages"].insert(0, {"role": "system", "content": description}) + else: + tools = self.tool_box.format_tools() + if not isinstance(tools, list): + raise TypeError("Native tool parser must return JSON tool descriptions") + payload["tools"] = tools + payload["tool_choice"] = "auto" + model = self.model + try: + if model == "Qwen3-8B": + results = yield from self._request_qwen3_8b(url, headers, payload, callback) + elif model == "Deepseek-V3": + results = yield from self._request_deepseek_v3(url, headers, payload, callback) + else: + raise ValueError(f"Model {model} not supported in SiliconFlowAPI.") + except _SiliconFlowRequestFailed as error: + return { + "ok": False, + "error": str(error), + "token_usage": {}, + "money_usage": {}, + "extra": {}, + } + return results + + def _request_qwen3_8b( + self, + url: str, + headers: dict[str, str], + payload: dict[str, Any], + callback: ProgressCallback | None, + ) -> Generator[APICallSample, None, dict[str, Any]]: + """Run the ``qwen3 8b`` operation. + + Args: + url: The url value. + headers: The headers value. + payload: Serializable event payload. + + Returns: + Generator yielding call samples and returning aggregate metadata. + """ + yield from [] + payload = { + "model": "Qwen/Qwen3-8B", + "enable_thinking": True, + **payload, + } + self.report_progress(callback, {"type": "start", "sample": 1}) + responses = self._post_json( + url, + headers, + payload, + description=f"SiliconFlowAPI({self.model})", + sample=1, + validate=self._validate_chat_response, + callback=callback, + ) + for sample, choice in enumerate(responses["choices"], 1): + content = choice["message"].get("content") or "" + tool_call = self.parse_tool_calls(choice["message"], content) + sample_response = self.format_response(choice["message"], tool_call, content) + if callback is not None: + self.report_progress(callback, { + "type": "complete", + "sample": sample, + "content": sample_response.content, + "reasoning": sample_response.reasoning, + "tool_calls": [call.raw for call in sample_response.tool_calls], + }) + if sample < len(responses["choices"]): + self.report_progress(callback, { + "type": "start", + "sample": sample + 1, + }) + yield sample_response + prompt_tokens = responses["usage"]["prompt_tokens"] + reason_tokens = ( + responses["usage"].get("completion_tokens_details", {}).get("reasoning_tokens", 0) + ) + answer_tokens = responses["usage"]["completion_tokens"] - reason_tokens + token_usage = { + "prompt": prompt_tokens, + "answer": answer_tokens, + "reason": reason_tokens, + } + if ( + other := responses["usage"]["total_tokens"] + - prompt_tokens + - answer_tokens + - reason_tokens + ) != 0: + token_usage["other"] = other + return { + "ok": True, + "error": None, + "token_usage": token_usage, + "money_usage": {"prompt": 0.0, "answer": 0.0, "reason": 0.0}, + "extra": {"responses": [responses]}, + } + + def _request_deepseek_v3( + self, + url: str, + headers: dict[str, str], + payload: dict[str, Any], + callback: ProgressCallback | None, + ) -> Generator[APICallSample, None, dict[str, Any]]: + """Run the ``deepseek v3`` operation. + + Args: + url: The url value. + headers: The headers value. + payload: Serializable event payload. + + Returns: + Generator yielding call samples and returning aggregate metadata. + """ + yield from [] + payload = { + "model": "deepseek-ai/DeepSeek-V3", + **payload, + } + n, payload["n"] = payload["n"], 1 + model = payload["model"] + details = [] + for idx in range(1, n + 1): + self.report_progress(callback, {"type": "start", "sample": idx}) + response = self._post_json( + url, + headers, + payload, + description=f"SiliconFlowAPI({model})", + sample=idx, + validate=self._validate_chat_response, + callback=callback, + ) + prompt_tokens = response["usage"]["prompt_tokens"] + answer_tokens = response["usage"]["completion_tokens"] + token_usage = {"prompt": prompt_tokens, "answer": answer_tokens} + if (other := response["usage"]["total_tokens"] - prompt_tokens - answer_tokens) > 0: + token_usage["other"] = other + price_usage = { + "prompt": 2 / 7.0 * prompt_tokens / 1e6, + "answer": 8 / 7.0 * answer_tokens / 1e6, + } + message = response["choices"][0]["message"] + content = message["content"] or "" + tool_call = self.parse_tool_calls(message, content) + sample_response = self.format_response(message, tool_call, content) + details.append( + ProviderSampleResult( + response=sample_response, + token_usage=token_usage, + money_usage=price_usage, + raw_response=response, + ) + ) + if callback is not None: + self.report_progress(callback, { + "type": "complete", + "sample": idx, + "content": sample_response.content, + "reasoning": sample_response.reasoning, + "tool_calls": [call.raw for call in sample_response.tool_calls], + }) + yield sample_response + return self.aggregate_sample_results(details) diff --git a/src/sr_harness/api/utils.py b/src/sr_harness/api/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9eb1ca4f864c6bbecfde74f7d2c47eabc844d846 --- /dev/null +++ b/src/sr_harness/api/utils.py @@ -0,0 +1,67 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +"""Small infrastructure helpers shared by API provider adapters.""" + +from __future__ import annotations + +import time +from typing import Any, Callable, Mapping + + +class RemoteModelCatalog: + """Fetch and briefly cache one provider's remote model catalog.""" + + def __init__( + self, + http_client: Callable[[str], Any], + *, + cache_seconds: float = 300.0, + ) -> None: + self._http_client = http_client + self._cache_seconds = cache_seconds + self._models: list[str] | None = None + self._cached_at = 0.0 + + def get( + self, + url: str, + *, + description: str, + api_key: str | None = None, + params: Mapping[str, str] | None = None, + include: Callable[[dict[str, Any]], bool] | None = None, + ) -> list[str]: + """Return a model list, propagating failures without caching them.""" + now = time.monotonic() + if self._models is not None and now - self._cached_at < self._cache_seconds: + return list(self._models) + + headers = {"Authorization": f"Bearer {api_key}"} if api_key else None + with self._http_client(url) as client: + response = client.get( + url, + headers=headers, + params=dict(params or {}), + timeout=10.0, + ) + response.raise_for_status() + payload = response.json() + + records = payload.get("data") if isinstance(payload, dict) else None + if not isinstance(records, list): + raise ValueError(f"{description} response does not contain a data list") + models = sorted( + { + model_id.strip() + for record in records + if isinstance(record, dict) + and (include is None or include(record)) + and isinstance((model_id := record.get("id")), str) + and model_id.strip() + } + ) + if not models: + raise ValueError(f"{description} returned no model identifiers") + + self._models = models + self._cached_at = now + return list(models) diff --git a/src/sr_harness/cli/README.zh.md b/src/sr_harness/cli/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..f2a5df2ea6b8b26eb9579f4855ba72b2da1236b0 --- /dev/null +++ b/src/sr_harness/cli/README.zh.md @@ -0,0 +1,5 @@ +本目录提供面向用户的命令行脚本。每个脚本都应该实现 `setup_parser(parser)` 和 `main(args)`;前者负责配置命令行参数,后者执行已经解析的参数并返回退出码。 + +模型检查点的下载与上传属于开发维护操作,相关独立脚本位于仓库根目录的 `scripts/` 中。 + +> CLI 快速开始与完整参数入口:[`docs/index.md`](../../../docs/index.md) diff --git a/src/sr_harness/cli/__init__.py b/src/sr_harness/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ea527305034e9eb4f28d15ec7468888b917d2a21 --- /dev/null +++ b/src/sr_harness/cli/__init__.py @@ -0,0 +1,78 @@ +"""Unified command-line entry point for SRHarness.""" +from __future__ import annotations +import argparse +import importlib + +__all__ = ["entrypoint"] + + +COMMANDS = { + "run": ("run", "Launch the SRHarness interactive workbench."), + "synthetic": ("synthetic", "Run SRHarness on a synthetic symbolic-regression problem."), + "benchmark": ("benchmark", "Evaluate SRHarness and baseline algorithms on LLM-SRBench."), + "tool": ("tool", "Inspect or invoke an SRHarness tool."), +} + + +class _CommandParser(argparse.ArgumentParser): + def __init__(self, *args, module_name: str | None = None, **kwargs) -> None: + super().__init__(*args, **kwargs) + self._module_name = module_name + self._is_configured = module_name is None + + def parse_known_args(self, args=None, namespace=None): + if not self._is_configured: + self._is_configured = True + module = importlib.import_module(f"{__package__}.{self._module_name}") + module.setup_parser(self) + return super().parse_known_args(args, namespace) + + +def setup_parser(parser: argparse.ArgumentParser | None = None) -> argparse.ArgumentParser: + """Configure the command-line argument parser. + + Args: + parser: Argument parser to configure. + + Returns: + argparse.ArgumentParser: The operation result. + """ + if parser is None: + parser = argparse.ArgumentParser(prog="sr-harness", description="SRHarness command-line interface.") + + subparsers = parser.add_subparsers( + dest="command", + metavar="COMMAND", + parser_class=_CommandParser, + ) + for name, (module_name, help_text) in COMMANDS.items(): + subparsers.add_parser(name, help=help_text, module_name=module_name) + return parser + + +def main(args: argparse.Namespace) -> int: + """Run the command and return its process exit code. + + Args: + args: Parsed command-line arguments. + + Returns: + int: The operation result. + """ + module_name = COMMANDS[args.command][0] + module = importlib.import_module(f"{__package__}.{module_name}") + return module.main(args) + + +def entrypoint() -> int: + """Run the installed command-line entry point. + + Returns: + int: The operation result. + """ + parser = setup_parser() + args = parser.parse_args() + if args.command is None: + parser.print_help() + return 0 + return main(args) diff --git a/src/sr_harness/cli/benchmark.py b/src/sr_harness/cli/benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..64c8161fe74a3c7618a3bcc17ef2474e19ca5e3d --- /dev/null +++ b/src/sr_harness/cli/benchmark.py @@ -0,0 +1,705 @@ +""" +LLM-SRBench 评估脚本 (浓缩版) + +将 benchmark 评估流程整合为单个脚本: + 1) 数据读取与预处理 + 2) 调用符号回归函数 (placeholder) + 3) 评估结果 + 4) 汇总多次运行的结果 + +Usage: + # 测试单个问题 + sr-harness benchmark --exp_name test_my_algorithm --datasets lsrtransform --problem_names II.6.15b_1_0 + # 测试单个数据集 + sr-harness benchmark --exp_name test_my_algorithm --datasets bio_pop_growth + # 测试一系列问题 + sr-harness benchmark --problem_names MatSci2 MatSci19 CRK28 BPG1 PO6 + # 测试特定算法 + sr-harness benchmark --algorithm linear --exp_name test_linear_fitting +""" + +from __future__ import annotations + +import re +import time +import json +import h5py +import shlex +import dotenv +import logging +import argparse +import datasets +import numpy as np +import sr_harness_engine as engine +from sr_harness_engine.tree import transform +from pathlib import Path +from datetime import datetime +from socket import gethostname +from typing import Callable, Dict, List +from scipy.stats import kendalltau +from scipy.optimize import least_squares +from sklearn.metrics import mean_absolute_percentage_error +from sr_harness.utils import ( + add_minus_flags, + get_symbolic_acc, + log_exception, + sanitize_filename, + save_args, + seed_all, + setup_logging, + tag2ansi, +) +from sr_harness._vendor.llmsr_bench.core import SEDTask, SRResult, Problem +from sr_harness._vendor.llmsr_bench.algorithms import get_update_parser, get_algorithm, list_algorithms + +DATASET_SPLITS = { + "lsrtransform": "lsr_transform", + "bio_pop_growth": "lsr_synth_bio_pop_growth", + "chem_react": "lsr_synth_chem_react", + "matsci": "lsr_synth_matsci", + "phys_osc": "lsr_synth_phys_osc", +} + +dotenv.load_dotenv() # Load environment variables from .env file if present +SCRIPT_NAME = "benchmark" +_logger = logging.getLogger(f"sr_harness.{SCRIPT_NAME}") + + +def setup_parser(parser: argparse.ArgumentParser | None = None) -> argparse.ArgumentParser: + """Configure the command-line argument parser. + + Args: + parser: Argument parser to configure. + + Returns: + argparse.ArgumentParser: The operation result. + """ + if parser is None: + parser = argparse.ArgumentParser( + prog="sr-harness benchmark", + description="LLM-SRBench Evaluation Script.", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + else: + parser.description = "LLM-SRBench Evaluation Script." + parser.formatter_class = argparse.ArgumentDefaultsHelpFormatter + parser.add_argument("--algorithm", required=True, choices=list_algorithms(), help=( + "Symbolic-regression algorithm to evaluate." + )) + parser.add_argument("--name", default=f"{SCRIPT_NAME}", help=( + "Experiment task name used when auto-generating exp_name." + )) + parser.add_argument("--exp_name", default=None, help=( + "Experiment name. Defaults to a timestamped name." + )) + parser.add_argument("--save_dir", default=f"./logs/{SCRIPT_NAME}", help=( + "Root directory for logs and run artifacts." + )) + parser.add_argument("--seed", type=int, default=-1, help=( + "Random seed. Default -1 means using current system time." + )) + parser.add_argument("--save_path", default=None, help=( + "Path to save agent logs and artifacts. Default is auto-generated from --save_dir and --exp_name." + )) + parser.add_argument("--verbose", action=argparse.BooleanOptionalAction, default=False, help=( + "Enable verbose agent logging." + )) + parser.add_argument("--debug", action=argparse.BooleanOptionalAction, default=False, help=( + "Enable debug mode (verbose + raise caught exceptions)." + )) + parser.add_argument("--data_root", type=str, default=str(Path("data") / "llm-srbench-data"), help=( + "HDF5 数据文件所在目录" + )) + parser.add_argument("--datasets", type=str, default=None, nargs="+", choices=list(DATASET_SPLITS.keys()), help=( + "数据集名称, 默认评估全部数据集" + )) + parser.add_argument("--problem_names", type=str, default=None, nargs="+", help=( + "仅评估指定问题(方程)ID, 默认评估全部问题" + )) + parser.add_argument("--skip_existing", action=argparse.BooleanOptionalAction, default=False, help=( + "如果结果文件已存在则跳过评估" + )) + parser.add_argument("--skip_successful", action=argparse.BooleanOptionalAction, default=True, help=( + "如果结果文件已存在且成功则跳过评估" + )) + parser.add_argument("--anonymize", action=argparse.BooleanOptionalAction, default=False, help=( + "Anonymize agent-facing variables as x1..xn and target as y." + )) + # 解析 --algorithm 参数以获取对应的 update_parser + algorithm_probe = argparse.ArgumentParser(add_help=False) + algorithm_probe.add_argument("--algorithm", choices=list_algorithms()) + probe_args, _ = algorithm_probe.parse_known_args() + if probe_args.algorithm and (update_parser_fn := get_update_parser(probe_args.algorithm)): + parser = update_parser_fn(parser) + add_minus_flags(parser) + return parser + + +def load_problems(dataset_name: str, data_root: str, hf_repo_id = "nnheui/llm-srbench") -> List[Problem]: + """Load problems. + + Args: + dataset_name: The dataset name value. + data_root: The data root value. + hf_repo_id: The hf repo id value. + + Returns: + List[Problem]: The operation result. + """ + split_name = DATASET_SPLITS[dataset_name] + + # 尝试从本地 parquet 文件加载公式元信息 + data_dir = Path(data_root) / "data" + if not data_dir.exists(): + _logger.note(f"Local parquet not found. Downloading from {hf_repo_id}... (If you wait too long, consider downloading it manually)") + ds = datasets.load_dataset(hf_repo_id, split=split_name, cache_dir='./data/hf_cache') + elif not (data_path := data_dir.glob(f"{split_name}-*.parquet").__iter__().__next__()).exists(): + _logger.note(f"Local parquet not found. Downloading from {hf_repo_id}... (If you wait too long, consider downloading it manually)") + ds = datasets.load_dataset(hf_repo_id, split=split_name, cache_dir='./data/hf_cache') + else: + _logger.note(f"Loading parquet from local: {data_path}") + ds = datasets.load_dataset("parquet", data_files=str(data_path), split="train") + + # 从 HDF5 读取数值样本 + h5file_path = Path(data_root) / "lsr_bench_data.hdf5" + problems = [] + with h5py.File(h5file_path, "r") as f: + for entry in ds: + name = entry["name"] + # HDF5 路径: /lsr_transform/ 或 /lsr_synth// + if split_name == "lsr_transform": + h5_path = f"/lsr_transform/{name}" + else: + h5_path = f"/lsr_synth/{dataset_name}/{name}" + + expression = entry["expression"] + samples = {k: v[...].astype(np.float64) for k, v in f[h5_path].items()} + + # expression 中有一些 P(t) 这样的写法,需要将它替换成 P + for symbol in entry['symbols']: + try: + expression = re.sub(rf"\b{re.escape(symbol)}\b\(t\)", symbol, expression) + except Exception as e: + _logger.warning(f"Failed to replace {symbol}(t) -> {symbol} in {entry['expression']!r}") + + # expression 中有一些 pi, e 这样的常数, 需要将它替换成数值 + for key, var in {'pi': np.pi, 'e': np.e}.items(): + if key not in entry['symbols']: + try: + expression = re.sub(rf"\b{key}\b", str(var), expression) + except Exception as e: + _logger.warning(f"Failed to replace {key} -> {var} in {entry['expression']!r}") + + expression = expression.replace("^", "**") + + # Chemical Reaction 数据集中存在一些错误设置的数值常数,替换为 __C0, __C1, ... 以便后续重新确定数值常数 + if dataset_name == 'chem_react': + # 0.18997742423620262_z, 0.547523655303147_s, .5_alpha, 1e-3_k -> __C0, __C1, __C2, __C3 + expression = re.sub( + r"(? 0 else float("nan"), + } + if not (metrics['r2'] > 0.99): + _logger.warning( + f"[{dataset_name}] {name} has low R^2 ({metrics['r2']:.4f}) between gt_expression and train samples " + f"(MAE={metrics['mae']:.4e}, MAPE={metrics['mape']:.4e}, RMSE={metrics['rmse']:.4e}). " + f"This problem is NOT skipped, but the results may be unreliable." + ) + + problems.append(Problem( + dataset_identifier=dataset_name, + equation_idx=name, + symbols=entry["symbols"], + symbol_descs=entry["symbol_descs"], + symbol_properties=entry["symbol_properties"], + raw_expression=entry["expression"], + gt_expression=gt_expression, + samples=samples, + )) + return problems + + +def anonymize_problem(problem: Problem) -> Problem: + """Return an agent-facing anonymized copy of a benchmark problem. + + Args: + problem: The problem value. + + Returns: + Problem: The operation result. + """ + + target = problem.symbols[0] + features = problem.symbols[1:] + feature_mapping = {name: f"x{i}" for i, name in enumerate(features, start=1)} | {target: "y"} + + anonymized_symbols = [feature_mapping[sym] for sym in problem.symbols] + anonymized_symbol_descs = ["target variable", *[f"input variable {i}" for i in range(1, len(features) + 1)]] + + anonymized_expression = transform( + problem.gt_expression, + lambda node: ( + engine.Variable(feature_mapping[node.name]) + if isinstance(node, engine.Variable) else node + ), + ) + anonymized_expression_str = anonymized_expression.to_str() + _logger.debug( + f"[{problem.equation_idx} @ {problem.dataset_identifier}]" + f"Anonymization enabled. " + f"Variable mapping: {feature_mapping}\n" + f"Original formula: {target} = {problem.gt_expression}\n" + f"Anonymized formula: {anonymized_symbols[0]} = {anonymized_expression_str}\n" + ) + + anonymized_problem = Problem( + dataset_identifier=problem.dataset_identifier, + equation_idx=problem.equation_idx, + symbols=anonymized_symbols, + symbol_descs=anonymized_symbol_descs, + symbol_properties=problem.symbol_properties, + gt_expression=anonymized_expression, + raw_expression="", + samples=problem.samples, + ) + return anonymized_problem + + +def compute_metrics(y_pred: np.ndarray, y_true: np.ndarray) -> Dict[str, float]: + """Compute metrics. + + Args: + y_pred: Predicted target values. + y_true: Observed target values. + + Returns: + Dict[str, float]: The operation result. + """ + mask = ~np.isnan(y_pred) # 原始的 LLM-SRBench 就是这么做的,可能导致潜在的问题,但为了保持一致,我们也采用相同的过滤方式。 + y_pred, y_true = y_pred[mask], y_true[mask] + if len(y_true) == 0: + return { + "mse": float("nan"), "nmse": float("nan"), "r2": float("nan"), + "kdt": float("nan"), "mape": float("nan"), "num_valid_points": 0 + } + else: + var = np.var(y_true) + mse = float(np.mean((y_true - y_pred) ** 2)) + nmse = float(mse / var) if var > 0 else float("nan") + r2 = float(1 - nmse) + kdt = float(kendalltau(y_true, y_pred)[0]) if len(y_true) > 1 else float("nan") + mape = float(mean_absolute_percentage_error(y_true, y_pred)) + acc01 = np.mean(np.abs(y_true - y_pred) <= 0.1 * np.abs(y_true)) + return { + "mse": mse, "nmse": nmse, "r2": r2, "acc01": acc01, + "kdt": kdt, "mape": mape, "num_valid_points": len(y_true), + } + + +def evaluate_problem(args, problem: Problem, sr_fn: Callable, exp_path: Path) -> Dict: + """Run the ``evaluate problem`` operation. + + Args: + args: Parsed command-line arguments. + problem: The problem value. + sr_fn: The sr fn value. + exp_path: The exp path value. + + Returns: + Dict: The operation result. + """ + task = problem.create_task() + + start_time = time.time() + result = sr_fn(args, task) + search_time = time.time() - start_time + + # ID test + X_id = problem.test_samples[:, 1:] + y_id = problem.test_samples[:, 0] + id_metrics = compute_metrics(y_pred=result.predict(X_id), y_true=y_id) + + # OOD test (if available) + ood_metrics = None + if problem.ood_test_samples is not None: + X_ood = problem.ood_test_samples[:, 1:] + y_ood = problem.ood_test_samples[:, 0] + ood_metrics = compute_metrics(y_pred=result.predict(X_ood), y_true=y_ood) + + # Symbolic Accurate + try: + data = {sym: problem.test_samples[:, i] for i, sym in enumerate(problem.symbols)} + f_true = problem.gt_expression + f_pred = engine.parse(result.expression.replace("^", "**").replace("np.", "").replace("math.", "")) + symbolic_acc = get_symbolic_acc( + f_true, + f_pred, + data, + return_details=True, + llm_provider=getattr(args, "llm_provider", None), + llm_model=getattr(args, "llm_model", None), + ) + foo = lambda x: tag2ansi(('[green bold]EQUIVALENT[reset]' if x is True else '[red bold]NOT EQUIVALENT[reset]' if x is False else f'[gray bold]{x!r}[reset]')) + _logger.note(tag2ansi( + f"[{problem.equation_idx}] The predicted formula is judged to be {foo(symbolic_acc['equivalent'])} since {symbolic_acc.get('reason')}:\n" + f" f_true = [green]{f_true.to_str()}[reset]\n" + f" f_pred = [red]{f_pred.to_str()}[reset]" + f"Manually modify [green bold]{exp_path}[reset] if you want to override the symbolic accuracy judgment." + )) + except Exception as e: + symbolic_acc = { + "equivalent": None, + "reason": f"symbolic accuracy check failed: [{type(e).__name__}] {e}", + } + _logger.warning(f"[{problem.equation_idx}] Symbolic accuracy check failed: {log_exception(e)}") + + benchmark_result = { + "equation_id": problem.equation_idx, + "dataset_identifier": problem.dataset_identifier, + "gt_expression": problem.gt_expression.to_str(), + "discovered_expression": result.expression, + "num_train": len(problem.train_samples), + "num_test": len(problem.test_samples), + "search_time": search_time, + "id_metrics": id_metrics, + "ood_metrics": ood_metrics, + "symbolic_acc": symbolic_acc['equivalent'], + "symbolic_acc_detail": symbolic_acc['reason'], + } + if result.metadata: + benchmark_result.update(result.metadata) + return benchmark_result + + +def log_result(result: Dict): + """Run the ``log result`` operation. + + Args: + result: Result mapping to format or update. + """ + lines = [] + lines.append(f'[gray]{"=" * 50}') + lines.append(f"[blue bold]Problem {result['equation_id']} @ {result.get('dataset_identifier', 'Unknown')} evaluated.[reset]") + lines.append(f'[gray]{"-" * 50}') + lines.append(f"[blue]GT: [green]{result['gt_expression']}[reset]") + lines.append(f"[blue]Discovered: [red]{result['discovered_expression']}[reset]") + if (symbolic_acc := result.get("symbolic_acc")) is None: + lines.append(f"[blue]Symbolic Accurate:[reset] [gray]N/A[reset]") + elif symbolic_acc: + lines.append(f"[blue]Symbolic Accurate:[reset] [green]Yes[reset]") + else: + lines.append(f"[blue]Symbolic Accurate:[reset] [red]No[reset]") + if 'id_metrics' in result and result['id_metrics'] is not None: + lines.append( + f"[blue]In-Domain: R2={result['id_metrics'].get('r2', float('nan')):.6f}, " + f"MSE={result['id_metrics'].get('mse', float('nan')):.6f}, " + f"NMSE={result['id_metrics'].get('nmse', float('nan')):.6f}, " + f"MAPE={result['id_metrics'].get('mape', float('nan')):.6f}, " + f"Acc@0.1={result['id_metrics'].get('acc01', float('nan')):.6f}, " + f"Valid Points={result['id_metrics'].get('num_valid_points', 0)}" + ) + if 'ood_metrics' in result and result['ood_metrics'] is not None: + lines.append( + f"[blue]Out-of-Domain: R2={result['ood_metrics']['r2']:.6f}, " + f"MSE={result['ood_metrics']['mse']:.6f}, " + f"NMSE={result['ood_metrics']['nmse']:.6f}, " + f"MAPE={result['ood_metrics']['mape']:.6f}, " + f"Acc@0.1={result['ood_metrics']['acc01']:.6f}, " + f"Valid Points={result['ood_metrics']['num_valid_points']}" + ) + lines.append(f"[blue]Search time:[reset] {result['search_time']:.2f}s") + lines.append(f'[gray]{"=" * 50}') + return tag2ansi("\n".join(lines)) + + +def aggregate_results(results: List[Dict]) -> Dict: + """Run the ``aggregate results`` operation. + + Args: + results: Result records to process. + + Returns: + Dict: The operation result. + """ + + def safe_mean(key, group): + vals = [r[group][key] for r in results if r[group] is not None and not np.isnan(r[group][key])] + return float(np.mean(vals)) if vals else float("nan") + + n = len(results) + + # R² 达标率 + r2_thresholds = [0.5, 0.9, 0.99, 0.999] + r2_hit_rates = {} + for thr in r2_thresholds: + hits = sum(1 for r in results if r["id_metrics"] is not None and r["id_metrics"]["r2"] >= thr) + r2_hit_rates[f"r2>={thr}"] = {"count": hits, "rate": hits / n if n > 0 else 0} + + summary = { + "dataset": "|".join(sorted({r.get("dataset_identifier") for r in results} - {None})), + "total_problems": n, + "avg_search_time": float(np.mean([r["search_time"] for r in results])), + "avg_symbolic_acc": float(np.mean([r.get("symbolic_acc") is True for r in results])), + "r2_hit_rates": r2_hit_rates, + } + summary["id_metrics"] = { + "avg_mse": safe_mean("mse", "id_metrics"), + "avg_nmse": safe_mean("nmse", "id_metrics"), + "avg_r2": safe_mean("r2", "id_metrics"), + "avg_acc01": safe_mean("acc01", "id_metrics"), + "avg_kdt": safe_mean("kdt", "id_metrics"), + "avg_mape": safe_mean("mape", "id_metrics"), + "avg_num_valid_points": safe_mean("num_valid_points", "id_metrics"), + } + if any(r["ood_metrics"] is not None for r in results): + summary["ood_metrics"] = { + "avg_mse": safe_mean("mse", "ood_metrics"), + "avg_nmse": safe_mean("nmse", "ood_metrics"), + "avg_r2": safe_mean("r2", "ood_metrics"), + "avg_acc01": safe_mean("acc01", "ood_metrics"), + "avg_kdt": safe_mean("kdt", "ood_metrics"), + "avg_mape": safe_mean("mape", "ood_metrics"), + "avg_num_valid_points": safe_mean("num_valid_points", "ood_metrics"), + } + return summary + +def conclude_results(results: List[Dict], llmsr_datasets: List[str], save_path: str): + # 汇总 + """Run the ``conclude results`` operation. + + Args: + results: Result records to process. + llmsr_datasets: The llmsr datasets value. + save_path: Optional output path. + """ + results = [r for r in results if r.get("dataset_identifier") in llmsr_datasets] + summary = aggregate_results(results) + + # 打印汇总 + lines = [] + lines.extend([ + f'[gray]{"=" * 50}[reset]', + f"[red bold]Summary of {'|'.join(llmsr_datasets)} ({summary['total_problems']} problems)[reset]", + f'[gray]{"-" * 50}[reset]', + f" [red]Avg R2 (In-Domain):[reset] {summary['id_metrics']['avg_r2']:.6f}", + f" [red]Avg MSE (In-Domain):[reset] {summary['id_metrics']['avg_mse']:.6f}", + f" [red]Avg NMSE (In-Domain):[reset] {summary['id_metrics']['avg_nmse']:.6f}", + f" [red]Avg MAPE (In-Domain):[reset] {summary['id_metrics']['avg_mape']:.6f}", + f" [red]Avg KDT (In-Domain):[reset] {summary['id_metrics']['avg_kdt']:.6f}", + f" [red]Avg Acc@0.1 (In-Domain):[reset] {summary['id_metrics']['avg_acc01']:.6f}", + f" [red]Avg Valid Points (In-Domain):[reset] {summary['id_metrics']['avg_num_valid_points']:.1f}", + ]) + if "ood_metrics" in summary: + lines.extend([ + f'[gray]{"-" * 50}[reset]', + f" [red]Avg R2 (Out-of-Domain):[reset] {summary['ood_metrics']['avg_r2']:.6f}", + f" [red]Avg MSE (Out-of-Domain):[reset] {summary['ood_metrics']['avg_mse']:.6f}", + f" [red]Avg NMSE (Out-of-Domain):[reset] {summary['ood_metrics']['avg_nmse']:.6f}", + f" [red]Avg MAPE (Out-of-Domain):[reset] {summary['ood_metrics']['avg_mape']:.6f}", + f" [red]Avg KDT (Out-of-Domain):[reset] {summary['ood_metrics']['avg_kdt']:.6f}", + f" [red]Avg Acc@0.1 (Out-of-Domain):[reset] {summary['ood_metrics']['avg_acc01']:.6f}", + f" [red]Avg Valid Points (Out-of-Domain):[reset] {summary['ood_metrics']['avg_num_valid_points']:.1f}", + ]) + lines.append(f'[gray]{"-" * 50}[reset]') + for thr, info in summary["r2_hit_rates"].items(): + lines.append(f" [red]{thr:>10}:[reset] {info['count']:>5}/{summary['total_problems']} ({info['rate']:.1%})") + lines.append(f'[gray]{"-" * 50}[reset]') + lines.append(f" [red]Avg Search Time:[reset] {summary['avg_search_time']:.2f}s") + lines.append(f" [red]Avg Symbolic Accurate Rate:[reset] {summary['avg_symbolic_acc']:.6f}") + lines.append(f'[gray]{"=" * 50}[reset]') + _logger.note(tag2ansi("\n" + "\n".join(lines))) + + # 保存汇总 + save_path.parent.mkdir(parents=True, exist_ok=True) + with open(save_path, "a", encoding="utf-8") as f: + json.dump(summary, f, indent=2, default=str, allow_nan=True) + _logger.note(f"Summary saved to {save_path}") + + +def run_benchmark(args: argparse.Namespace) -> int: + # 加载问题集 + """Run the ``run benchmark`` operation. + + Args: + args: Parsed command-line arguments. + + Returns: + int: The operation result. + """ + args.datasets = args.datasets or list(DATASET_SPLITS.keys()) + problems = [] + for dataset in args.datasets: + problems.extend(load_problems(dataset, args.data_root)) + _logger.note(f"Load {len(problems)} problems in total from datasets: {args.datasets}") + + if args.problem_names is not None: + if unknown_problems := set(args.problem_names) - set(p.equation_idx for p in problems): + _logger.warning(f"Unknown problems specified: {unknown_problems}") + problems = [p for p in problems if p.equation_idx in args.problem_names] + _logger.note(f"Filtered to {len(problems)} problems: {[p.equation_idx for p in problems]}") + if not problems: + _logger.error("No valid problems found after filtering. Check your --problem_names.") + return 1 + + # 将 agent-facing 问题匿名化。样本矩阵列顺序不变,只替换符号名和自然语言描述。 + if args.anonymize: + problems = [anonymize_problem(problem) for problem in problems] + _logger.note("Anonymization enabled for benchmark tasks.") + + # 获取算法的 run 函数 + sr_fn = get_algorithm(args.algorithm) + + # 逐个问题运行 SR 并评估 + results = [] + interrupted = False + for i, problem in enumerate(problems): + _logger.note(f"[{i+1}/{len(problems)}] {problem.equation_idx}: {problem.gt_expression.to_str()}") + exp_path = Path(args.save_path) / "results" / f"{problem.dataset_identifier}_{problem.equation_idx}.jsonl" + exp_path.parent.mkdir(parents=True, exist_ok=True) + if exp_path.exists(): + lines = [json.loads(line) for line in exp_path.read_text(encoding="utf-8").splitlines() if line.strip()] + successful_lines = [line for line in lines if 'error' not in line] + if args.skip_successful and successful_lines: + result = successful_lines[-1] + results.append(result) + _logger.info(tag2ansi( + f"Successful result already exists at {exp_path} ([red bold]{len(successful_lines)} successful records), skipping...\n" + f"Last successful result:\n{log_result(result)}" + )) + continue + if args.skip_existing and lines: + result = successful_lines[-1] if successful_lines else lines[-1] + results.append(result) + _logger.info(tag2ansi( + f"Result already exists at {exp_path} ([red bold]{len(lines)} records with [red bold]{len(successful_lines)} successful), skipping...\n" + f"Last result:\n{log_result(result)}" + )) + continue + + try: + result = evaluate_problem(args, problem, sr_fn, exp_path) + results.append(result) + _logger.note(f"\n{log_result(result)}") + with open(exp_path, "a", encoding="utf-8") as f: + f.write(json.dumps(result, default=str, allow_nan=True) + "\n") + _logger.note(f"Result saved to {exp_path}") + except KeyboardInterrupt: + _logger.warning("Evaluation interrupted by user.") + interrupted = True + break + except Exception as e: + _logger.error(f" ERROR: {log_exception(e)}") + result = { + "equation_id": problem.equation_idx, + "dataset_identifier": problem.dataset_identifier, + "gt_expression": problem.gt_expression.to_str(), + "discovered_expression": None, + "num_train": len(problem.train_samples), + "num_test": len(problem.test_samples), + "search_time": float("nan"), + "id_metrics": { + "mse": float("nan"), "nmse": float("nan"), "r2": float("nan"), + "kdt": float("nan"), "mape": float("nan"), "acc01": float("nan"), + "num_valid_points": 0 + }, + "ood_metrics": None, + "symbolic_acc": False, + "error": str(e), + } + results.append(result) + with open(exp_path, "a", encoding="utf-8") as f: + f.write(json.dumps(result, default=str, allow_nan=True) + "\n") + if args.debug: raise + + # 汇总结果 + for dataset in args.datasets: + conclude_results(results, [dataset], save_path=Path(args.save_path) / "summary" / f"{dataset}.json") + conclude_results(results, list(DATASET_SPLITS.keys()), save_path=Path(args.save_path) / "summary" / f"all.json") + if interrupted: + return 130 + return 1 if any("error" in result for result in results) else 0 + + +def main(args: argparse.Namespace) -> int: + """Run LLM-SRBench from CLI arguments. + + Args: + args: Parsed command-line arguments. + + Returns: + int: The operation result. + """ + if args.exp_name is None: + now = datetime.now() + args.exp_name = sanitize_filename( + f"{now:%Y%m%d}_{args.name}_{now:%H%M%S}_{gethostname()}" + ) + else: + args.exp_name = sanitize_filename(args.exp_name) + if args.debug: + args.verbose = True + if args.seed == -1: + args.seed = int(datetime.now().timestamp() * 1000) % (2**32 - 1) + seed_all(args.seed) + save_path = Path(args.save_path) if args.save_path else Path(args.save_dir) / args.exp_name + save_path.mkdir(parents=True, exist_ok=True) + args.save_path = str(save_path) + command = getattr(args, "invocation", ["sr-harness", "benchmark"]) + args.invocation = " ".join(map(shlex.quote, command)) + + setup_logging( + info_level="debug" if args.verbose else "info", + exp_name=args.exp_name, + save_path=save_path / "info.log", + force=True, + ) + + _logger.note(f"Args: {args}") + + save_args(args, save_path / "args.json") + + exit_code = run_benchmark(args) + _logger.note(tag2ansi(f"Experiment completed. Re-run the script with [green bold]{args.invocation}[reset]")) + return exit_code + + +if __name__ == "__main__": + raise SystemExit(main(setup_parser().parse_args())) diff --git a/src/sr_harness/cli/run.py b/src/sr_harness/cli/run.py new file mode 100644 index 0000000000000000000000000000000000000000..db4550c55d5afdca6921fc0e60fd1ed2aa8ae9d0 --- /dev/null +++ b/src/sr_harness/cli/run.py @@ -0,0 +1,195 @@ +from __future__ import annotations + +import argparse +import sys +import tempfile +from datetime import datetime +from pathlib import Path +from socket import gethostname + +from sr_harness.utils import sanitize_filename, setup_logging + + +SCRIPT_NAME = "run" + + +def setup_parser(parser: argparse.ArgumentParser | None = None) -> argparse.ArgumentParser: + """Configure the command-line argument parser. + + Args: + parser: Argument parser to configure. + + Returns: + argparse.ArgumentParser: The operation result. + """ + if parser is None: + parser = argparse.ArgumentParser( + prog="sr-harness run", + description="Serve the SRHarness interactive workbench.", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + else: + parser.description = "Serve the SRHarness interactive workbench." + parser.formatter_class = argparse.ArgumentDefaultsHelpFormatter + parser.add_argument("--name", default=SCRIPT_NAME, help=( + "Experiment task name used when auto-generating exp_name." + )) + parser.add_argument("--exp-name", default=None, help=( + "Experiment name. Defaults to a timestamped name." + )) + parser.add_argument("--save-dir", default=None, help=( + "Root directory for logs and run artifacts. When omitted together with " + "--save-path, a temporary directory is used." + )) + parser.add_argument("--save-path", default=None, help=( + "Path to save agent logs and artifacts. Default is auto-generated from " + "--save-dir and --exp-name." + )) + parser.add_argument("--host", default="127.0.0.1", help="Host to bind.") + parser.add_argument("--port", default=8000, type=int, help="Port to bind.") + parser.add_argument("--workspace-dir", default=None, metavar="DIRECTORY", help=( + "Directory that stores the conversation registry and per-conversation workspaces." + )) + parser.add_argument("--isolate-users", action="store_true", help=( + "Only show each browser the conversations created under its own persistent client cookie." + )) + parser.add_argument("--read-only", action="store_true", help=( + "Serve an existing conversation store without modifying it. All mutating APIs " + "are disabled; use a filesystem read-only mount for defense in depth." + )) + parser.add_argument("--verbose", action=argparse.BooleanOptionalAction, default=False, help=( + "Enable verbose server logging." + )) + parser.add_argument("--mount", nargs="+", default=[], metavar="PATH", help=( + "Files or directories to mount read-only at the workspace root. Source " + "basenames must be unique." + )) + return parser + + +def _resolve_workspace_dir( + workspace_dir: str | None, + mounts: list[str], + *, + create: bool = True, +) -> Path | None: + if workspace_dir is None: + return None + path = Path(workspace_dir).expanduser().resolve() + if path.exists() and not path.is_dir(): + raise NotADirectoryError(f"Workspace directory is not a directory: {path}") + if create: + path.mkdir(parents=True, exist_ok=True) + elif not path.is_dir(): + raise FileNotFoundError(f"Read-only workspace directory does not exist: {path}") + if mounts: + print( + "Read-only mount points will be created inside every new conversation workspace.", + file=sys.stderr, + ) + return path + + +def main(args: argparse.Namespace) -> int: + """Run the command and return its process exit code. + + Args: + args: Parsed command-line arguments. + + Returns: + int: The operation result. + """ + try: + import uvicorn + except ImportError as exc: + raise SystemExit("Please reinstall SRHarness with its default dependencies.") from exc + + from sr_harness.web.app import create_app + from sr_harness.web.conversations import ConversationRegistry + + if args.read_only and args.mount: + raise SystemExit("--read-only cannot be combined with --mount") + + if args.exp_name is None: + now = datetime.now() + args.exp_name = sanitize_filename( + f"{now:%Y%m%d}_{args.name}_{now:%H%M%S}_{gethostname()}" + ) + else: + args.exp_name = sanitize_filename(args.exp_name) + requested_save_path = Path(args.save_path).expanduser() if args.save_path else ( + Path(args.save_dir).expanduser() / args.exp_name if args.save_dir else None + ) + try: + workspace_dir = _resolve_workspace_dir( + args.workspace_dir, + args.mount, + create=not args.read_only, + ) + except (FileNotFoundError, NotADirectoryError) as exc: + raise SystemExit(str(exc)) from exc + if workspace_dir is None and requested_save_path is not None: + workspace_dir = requested_save_path.resolve() + if args.read_only: + if not workspace_dir.is_dir(): + raise SystemExit( + f"Read-only workspace directory does not exist: {workspace_dir}" + ) + else: + workspace_dir.mkdir(parents=True, exist_ok=True) + elif workspace_dir is None: + if args.read_only: + raise SystemExit("--read-only requires --save-path or --workspace-dir") + workspace_dir = Path(tempfile.mkdtemp(prefix="sr_harness_workspace_")).resolve() + print( + "\033[31mWarning: Workspaces will be created in a temporary directory; " + "conversation history may be lost. Specify --save-path and/or --workspace-dir.\033[0m", + file=sys.stderr, + ) + save_path = ( + requested_save_path.resolve() + if requested_save_path is not None + else workspace_dir if args.read_only else workspace_dir / "runs" / args.exp_name + ) + if args.read_only: + if not save_path.is_dir(): + raise SystemExit(f"Read-only save path does not exist: {save_path}") + else: + save_path.mkdir(parents=True, exist_ok=True) + args.save_path = str(save_path) + args.workspace_dir = str(workspace_dir) + + setup_logging( + info_level="debug" if args.verbose else "info", + exp_name=args.exp_name, + save_path=None if args.read_only else save_path / "info.log", + force=True, + ) + + conversations = ConversationRegistry( + workspace_dir, + workspace_files=args.mount, + isolate_users=args.isolate_users, + run_root=save_path / "runs", + persist_sessions=requested_save_path is not None and not args.read_only, + read_only=args.read_only, + ) + session = conversations.session_proxy + app = create_app( + save_path.parent, + session=session, + conversation_registry=conversations, + read_only=args.read_only, + ) + browser_host = "127.0.0.1" if args.host in ("0.0.0.0", "::") else args.host + url = f"http://{browser_host}:{args.port}" + print(f"SRHarness Interactive: {url}", flush=True) + try: + uvicorn.run(app, host=args.host, port=args.port) + finally: + conversations.close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(setup_parser().parse_args())) diff --git a/src/sr_harness/cli/synthetic.py b/src/sr_harness/cli/synthetic.py new file mode 100644 index 0000000000000000000000000000000000000000..f35757d6634f37fcfe83df93d1cb6c000f85ed9a --- /dev/null +++ b/src/sr_harness/cli/synthetic.py @@ -0,0 +1,369 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""Command-line entry point for running a small SRAgent experiment.""" + +from __future__ import annotations + +import json +import shlex +import logging +import argparse +import numpy as np +import sr_harness_engine as engine +from pathlib import Path +from datetime import datetime +from socket import gethostname +from sr_harness import SRAgent +from sr_harness.utils import add_minus_flags, format_pareto_front, log_exception, sanitize_filename, save_args, seed_all, setup_logging, tag2ansi + + +SCRIPT_NAME = "synthetic" +_logger = logging.getLogger(f"sr_harness.{SCRIPT_NAME}") + +AGENT_OPTION_NAMES = ( + "llm_provider", + "llm_model", + "tools", + "local_sample_size", + "max_refinement_depth", + "global_width", + "max_restart_loop", + "restart_top_k", + "llm_max_tokens", + "verbose", + "tool_parser", + "max_workers", + "validation_fraction", + "split_by", + "split_ood_variable", + "split_random_state", + "force_initial_diagnostics", + "auto_routing", + "strong_llm_provider", + "strong_llm_model", +) + + +def setup_parser(parser: argparse.ArgumentParser | None = None) -> argparse.ArgumentParser: + """Configure the command-line argument parser. + + Args: + parser: Argument parser to configure. + + Returns: + argparse.ArgumentParser: The operation result. + """ + if parser is None: + parser = argparse.ArgumentParser( + prog="sr-harness synthetic", + description="Run SRAgent on a synthetic symbolic-regression problem.", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + else: + parser.description = "Run SRAgent on a synthetic symbolic-regression problem." + parser.formatter_class = argparse.ArgumentDefaultsHelpFormatter + parser.add_argument("--name", default=f"{SCRIPT_NAME}", help=( + "Experiment task name used when auto-generating exp_name." + )) + parser.add_argument("--exp_name", default=None, help=( + "Experiment name. Defaults to a timestamped name." + )) + parser.add_argument("--save_dir", default=f"./logs/{SCRIPT_NAME}", help=( + "Root directory for logs and run artifacts." + )) + parser.add_argument("-f", "--equation", default="y = sin(x1 - x2)", help=( + "Target equation used to generate synthetic data." + )) + parser.add_argument("--problem_description", default=None, help=( + "Problem description passed to the agent. Defaults to one derived from --equation." + )) + parser.add_argument("--features", default=None, nargs="*", help=( + "Optional space-separated feature names. Defaults to variables parsed from --equation. " + "An explicit list may omit equation variables to make them latent and may include additional nuisance features." + )) + parser.add_argument("--n_samples", type=int, default=100, help="Number of samples.") + parser.add_argument("--seed", type=int, default=-1, help=( + "Random seed. Default -1 means using current system time." + )) + parser.add_argument("--x_low", type=float, default=0.0, help=( + "Lower bound of the random feature range used to generate synthetic data." + )) + parser.add_argument("--x_high", type=float, default=1.0, help=( + "Upper bound of the random feature range used to generate synthetic data." + )) + parser.add_argument("--noise_std_ratio", type=float, default=0.0, help=( + "Gaussian noise standard deviation added to the target." + )) + parser.add_argument("--llm_provider", default="openrouter", help="LLM provider name.") + parser.add_argument("--llm_model", default="deepseek/deepseek-v4-flash-0731", help="LLM model name.") + parser.add_argument("--strong_llm_provider", default=None, help=( + "Optional provider for the strong backend used by auto-routing. Defaults to --llm_provider." + )) + parser.add_argument("--strong_llm_model", default=None, help=( + "Optional strong model for complex tasks or escalation after two unsuccessful rounds." + )) + parser.add_argument("--tools", default=None, type=str, nargs='+', help=( + "Optional list of tools to use. Default is the symbolic-regression tool set." + )) + parser.add_argument("--ban_tools", default=[], type=str, nargs='+', help=( + "Optional list of tools to ban. Takes precedence over --tools." + )) + parser.add_argument("-K", "--local_sample_size", type=int, default=1, help=( + "Number of LLM samples to generate for each branch." + )) + parser.add_argument("-L", "--max_refinement_depth", type=int, default=30, help=( + "Maximum agent refinement depth." + )) + parser.add_argument("-C", "--global_width", type=int, default=1, help=( + "Number of independent branches per restart loop." + )) + parser.add_argument("-R", "--max_restart_loop", type=int, default=1, help=( + "Maximum number of best-solution restart loops." + )) + parser.add_argument("--restart_top_k", type=int, default=1, help=( + "Number of previous best formulas to inject into the next restart prompt." + )) + parser.add_argument("--llm_max_tokens", type=int, default=4096, help=( + "Maximum number of tokens to generate for each LLM response." + )) + parser.add_argument("--tool_parser", default="openai", choices=["openai", "text", "json", "xml"], help=( + "Tool response parser type." + )) + parser.add_argument("--save_path", default=None, help=( + "Path to save agent logs and artifacts. Default is auto-generated from --save_dir and --exp_name." + )) + parser.add_argument("--verbose", action=argparse.BooleanOptionalAction, default=False, help=( + "Enable verbose agent logging." + )) + parser.add_argument("--debug", action=argparse.BooleanOptionalAction, default=False, help=( + "Enable debug mode (verbose + raise caught exceptions)." + )) + parser.add_argument("--max_workers", type=int, default=0, help=( + "Maximum number of parallel workers for tool execution. 0 means no parallel execution." + )) + parser.add_argument("--validation_fraction", type=float, default=0.2, help=( + "Fraction of samples held out for validation." + )) + parser.add_argument("--split_by", choices=["random", "ood"], default="random", help=( + "Validation split strategy." + )) + parser.add_argument("--split_ood_variable", default=None, help=( + "Variable used to order samples for an OOD validation split. Required when --split_by=ood." + )) + parser.add_argument("--split_random_state", type=int, default=42, help=( + "Random seed used by the random validation split." + )) + parser.add_argument("--force_initial_diagnostics", action=argparse.BooleanOptionalAction, default=True, help=( + "Before each branch's first LLM request, run statistics_analysis, relationship_analysis, and read discover-symbolic-laws." + )) + parser.add_argument("--auto_routing", action=argparse.BooleanOptionalAction, default=True, help=( + "Automatically route LLM requests between the base backend and the optional " + "--strong_llm_provider/--strong_llm_model backend according to task complexity " + "and search progress. --no-auto_routing always uses the base backend." + )) + parser = add_minus_flags(parser) + return parser + + +def make_dataset(args): + """Run the ``make dataset`` operation. + + Args: + args: Parsed command-line arguments. + """ + if '=' in args.equation: + pass + elif 'target' in args.equation: + raise ValueError("It seems you provided an equation without '=', but it contains the word 'target'. Did you forget to format it like 'target = ...'?") + else: + args.equation = f'target = {args.equation}' + target, formula_str = args.equation.split('=') + target = target.strip() + formula_str = formula_str.strip() + formula = engine.parse(formula_str) + equation_features = sorted({ + var.name + for var in formula.iter_preorder() + if isinstance(var, engine.Variable) + }) + features = equation_features if args.features is None else list(args.features) + if len(features) != len(set(features)): + raise ValueError("--features must not contain duplicate names.") + if target in features: + raise ValueError(f"Target variable {target!r} must not appear in --features.") + + rng = np.random.default_rng(args.seed) + sampled_features = [ + *features, + *(name for name in equation_features if name not in features), + ] + sampled_data = { + name: rng.uniform(args.x_low, args.x_high, size=args.n_samples) + for name in sampled_features + } + target_values = formula.eval(sampled_data) + + if args.noise_std_ratio > 0: + target_values += rng.normal(0.0, args.noise_std_ratio * np.std(target_values), size=target_values.shape) + + data = {name: sampled_data[name] for name in features} + data[target] = target_values + + return features, target, formula, data + + +def build_agent_options(args: argparse.Namespace) -> dict: + """Build the validated SRAgent configuration for this run. + + Args: + args: Parsed command-line arguments. + + Returns: + dict: The operation result. + """ + options = {name: getattr(args, name) for name in AGENT_OPTION_NAMES} + selected_tools = SRAgent.DEFAULT_TOOLS if options["tools"] is None else options["tools"] + options["tools"] = [tool for tool in selected_tools if tool not in args.ban_tools] + if not 0 <= options["validation_fraction"] < 1: + raise ValueError("validation_fraction must be in [0, 1).") + if options["max_workers"] < 0: + raise ValueError("max_workers must be non-negative.") + return options + + +def run_experiment(args: argparse.Namespace) -> dict: + """Run the ``run experiment`` operation. + + Args: + args: Parsed command-line arguments. + + Returns: + dict: The operation result. + """ + features, target, formula, data = make_dataset(args) + + X = {name: data[name] for name in features} + y = {target: data[target]} + problem_description = args.problem_description or ( + f"Find the relationship {target} = f({', '.join(features)}). " + f"The synthetic target was generated from an unknown formula." + ) + agent_options = build_agent_options(args) + _logger.note( + f"Starting experiment {args.exp_name}\n" + f"Equation: {target} = {formula}\n" + f"Target variable: {target}; Feature variables: {', '.join(features)}\n" + f"Generated {args.n_samples} samples with seed {args.seed}\n" + ) + + agent = SRAgent(save_path=args.save_path, **agent_options) + + result = { + "start_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), + "duration_seconds": None, + "target_formula": f"{target} = {formula}", + "noise_std_ratio": args.noise_std_ratio, + "random_seed": args.seed, + "status": "not_started", + "progress": None, + "token_usage": None, + "money_usage": None, + "tools_usage": None, + "llm_model": f"{args.llm_model} @ {args.llm_provider}" + ( + f" [autorouting to {args.strong_llm_model or args.llm_model} @ " + f"{args.strong_llm_provider or args.llm_provider}]" + if args.auto_routing + else "" + ), + } + try: + result |= agent.run(X=X, y=y, problem_description=problem_description) + except KeyboardInterrupt as e: + _logger.note("Experiment interrupted by user.") + result |= getattr(e, "partial_result", {"status": "interrupted"}) + except Exception as e: + _logger.error(f"Experiment failed with an exception: {log_exception(e)}") + result |= getattr(e, "partial_result", {"status": "failed"}) + result["error"] = repr(e) + if args.debug: raise + finally: + result["duration_seconds"] = (datetime.now() - datetime.strptime(result["start_time"], "%Y-%m-%d %H:%M:%S")).total_seconds() + result["times_usage"] = agent.named_timer.to_str(mode='time', mode_of_detail='pace', mode_of_percent='by_time') + result["token_usage"] = agent.token_counter.to_str(mode='count', mode_of_detail=None, mode_of_percent=None) + result["money_usage"] = agent.money_counter.to_str(mode='count', mode_of_detail=None, mode_of_percent=None) + result["tools_usage"] = agent.tools_counter.to_str(mode='count', mode_of_detail='count', mode_of_percent='by_count') + # 打印日志 + log = '\n'.join([ + f"[red]{k.replace('_', ' ').title()}[reset]: {v}" + for k, v in result.items() + if k not in {"pareto_front", "candidates"} + ]) + candidates = result.get("candidates", []) + pareto = [ + {"formula": candidates[index]["formula"], **candidates[index]["details"]} + for index in result.get("pareto_front", []) + if 0 <= index < len(candidates) + ] + _logger.note(tag2ansi( + f'\n[gray]{"=" * 50}[reset]\n' + "[red bold]Symbolic Regression Result[reset]\n" + f"{log}\n" + f"\n[red bold]Pareto Front[reset]\n" + f"{format_pareto_front(pareto)}\n" + f'[gray]{"=" * 50}[reset]' + )) + # 保存文件 + result_path = Path(args.save_path) / "result.jsonl" + with open(result_path, "a", encoding="utf-8") as f: + json.dump(result, f, ensure_ascii=True) + f.write("\n") + _logger.note(f"Result saved to {result_path}") + return result + + +def main(args: argparse.Namespace) -> int: + """Run a synthetic SRAgent experiment from CLI arguments. + + Args: + args: Parsed command-line arguments. + + Returns: + int: The operation result. + """ + if args.exp_name is None: + now = datetime.now() + args.exp_name = sanitize_filename( + f"{now:%Y%m%d}_{args.name}_{now:%H%M%S}_{gethostname()}" + ) + else: + args.exp_name = sanitize_filename(args.exp_name) + if args.debug: + args.verbose = True + if args.seed == -1: + args.seed = int(datetime.now().timestamp() * 1000) % (2**32 - 1) + seed_all(args.seed) + save_path = Path(args.save_path) if args.save_path else Path(args.save_dir) / args.exp_name + save_path.mkdir(parents=True, exist_ok=True) + args.save_path = str(save_path) + command = getattr(args, "invocation", ["sr-harness", "synthetic"]) + args.invocation = " ".join(map(shlex.quote, command)) + + setup_logging( + info_level="debug" if args.verbose else "info", + exp_name=args.exp_name, + save_path=save_path / "info.log", + force=True, + ) + + _logger.note(f"Args: {args}") + + save_args(args, save_path / "args.json") + + result = run_experiment(args) + _logger.note(tag2ansi(f"Experiment completed. Re-run the script with [green bold]{args.invocation}[reset]")) + if result.get("status") == "interrupted": + return 130 + return 0 if result.get("status") in {"completed", "early_stopped"} else 1 + + +if __name__ == "__main__": + raise SystemExit(main(setup_parser().parse_args())) diff --git a/src/sr_harness/cli/tool.py b/src/sr_harness/cli/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..0aa69283f517a19335dbdb8b753cfdbf741dbee0 --- /dev/null +++ b/src/sr_harness/cli/tool.py @@ -0,0 +1,194 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""Command-line gateway for SRHarness tools.""" +from __future__ import annotations + +import json +import argparse +import numpy as np +import sr_harness.tools +from pathlib import Path +from typing import Any +from sr_harness.core import AgentContext +from sr_harness.tools import BaseTool + + +def load_json_text(text: str) -> dict[str, Any]: + """Load json text. + + Args: + text: Text to process. + + Returns: + dict[str, Any]: The operation result. + """ + value = json.loads(text) + if not isinstance(value, dict): + raise ValueError("Tool params must be a JSON object.") + return value + + +def load_params(params: str | None = None, params_file: str | None = None) -> dict[str, Any]: + """Load params. + + Args: + params: The params value. + params_file: The params file value. + + Returns: + dict[str, Any]: The operation result. + """ + loaded: dict[str, Any] = {} + if params_file: + loaded |= load_json_text(Path(params_file).read_text(encoding="utf-8")) + if params: + loaded |= load_json_text(params) + return loaded + + +def decode_npz_value(value: np.ndarray) -> Any: + """Run the ``decode npz value`` operation. + + Args: + value: Input value. + + Returns: + Any: The operation result. + """ + if value.shape == (): + return value.item() + return value + + +def load_context(path: str | Path, target: str | None = None) -> AgentContext: + """Load a BaseTool context from context.npz. + + Args: + path: Filesystem path. + target: Target name or target values. + + Returns: + dict[str, Any]: The operation result. + """ + path = Path(path) + if not path.exists(): + raise FileNotFoundError(f"Context file not found: {path}") + + with np.load(path, allow_pickle=True) as archive: + context = {key: decode_npz_value(archive[key]) for key in archive.files} + + if target is not None: + context["target"] = target + + if "data" in context: + data = context["data"] + if not isinstance(data, dict): + raise ValueError('context.npz field "data" must contain a dict[str, np.ndarray].') + if "target" not in context: + raise ValueError('context.npz with a "data" field must also contain a "target" field.') + context["target"] = str(context["target"]) + return AgentContext(data=data, target=str(context["target"])) + + if "target" not in context: + raise ValueError( + 'context.npz must either contain fields "data" and "target", ' + 'or contain a scalar "target" naming the target variable.' + ) + + target_name = str(context["target"]) + data = { + key: value + for key, value in context.items() + if key != "target" and isinstance(value, np.ndarray) + } + if target_name not in data: + raise ValueError( + f'Target variable "{target_name}" is not present as an array field in context.npz.' + ) + return AgentContext(data=data, target=target_name) + + +def setup_parser(parser: argparse.ArgumentParser | None = None) -> argparse.ArgumentParser: + """Configure the command-line argument parser. + + Args: + parser: Argument parser to configure. + + Returns: + argparse.ArgumentParser: The operation result. + """ + if parser is None: + parser = argparse.ArgumentParser( + prog="sr-harness tool", + description="Run SRHarness tools from the command line.", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + else: + parser.description = "Run SRHarness tools from the command line." + parser.formatter_class = argparse.ArgumentDefaultsHelpFormatter + subparsers = parser.add_subparsers(dest="tool_command", required=True) + + list_parser = subparsers.add_parser("list", help="List registered tool names.") + list_parser.add_argument("--json", action="store_true", help="Output tool names as JSON.") + + schema_parser = subparsers.add_parser("schema", help="Print a tool schema.") + schema_parser.add_argument("tool", nargs="?", help="Tool name. Omit to print all schemas.") + + call_parser = subparsers.add_parser("call", help="Call one registered tool.") + call_parser.add_argument("tool", help="Tool name.") + call_parser.add_argument("--context", default="context.npz", help=( + "Path to context.npz containing BaseTool context fields." + )) + call_parser.add_argument("--target", default=None, help="Override context target name.") + call_parser.add_argument("--params", default=None, help=( + 'Tool parameters as a JSON object, e.g. \'{"f": "sin(x1)"}\'.' + )) + call_parser.add_argument("--params-file", default=None, help="JSON file with tool parameters.") + return parser + + +def tool_class(name: str) -> type[BaseTool]: + """Run the ``tool class`` operation. + + Args: + name: Registered name. + + Returns: + type[BaseTool]: The operation result. + """ + return BaseTool.create(name, create_instance=False) + + +def main(args: argparse.Namespace) -> int: + """Run the command and return its process exit code. + + Args: + args: Parsed command-line arguments. + + Returns: + int: The operation result. + """ + if args.tool_command == "list": + if args.json: + print(json.dumps(list(BaseTool.REGISTRY_DICT), indent=2, ensure_ascii=False)) + else: + for idx, (name, tool_cls) in enumerate(BaseTool.REGISTRY_DICT.items()): + description = (tool_cls.metadata.description or "").strip() + print(f"[{idx:02d}] {name}: {description}") + elif args.tool_command == "schema": + schema = tool_class(args.tool).to_dict() if args.tool else BaseTool.to_tool_list() + print(json.dumps(schema, indent=2, ensure_ascii=False)) + elif args.tool_command == "call": + tool_cls = tool_class(args.tool) + context = load_context(args.context, target=args.target) + params = load_params(args.params, args.params_file) + result = tool_cls(context=context)(**params) + print(result.result_str) + if not result.ok: + return 1 + else: + raise ValueError(f"Unknown tool command: {args.tool_command}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(setup_parser().parse_args())) diff --git a/src/sr_harness/core/__init__.py b/src/sr_harness/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8f6210962510f6d0891ad8376776c312d6bc6514 --- /dev/null +++ b/src/sr_harness/core/__init__.py @@ -0,0 +1,41 @@ +"""Dependency-light domain types and runtime state for SRHarness.""" +from .api import APICallSample, APICallSummary +from .context import AgentContext +from .context_data import ( + ContextManifestError, + inspect_context_data, + load_context_data, + update_context_data_descriptions, +) +from .search import ( + CandidateRecord, + ParentLink, + ParentRelation, + SearchCoordinate, + SearchNode, + SearchResult, + SearchRunState, + json_value, +) +from .tool import ToolCall, ToolCallResult, ToolMetadata + +__all__ = [ + "APICallSample", + "APICallSummary", + "AgentContext", + "CandidateRecord", + "ContextManifestError", + "ParentLink", + "ParentRelation", + "SearchCoordinate", + "SearchNode", + "SearchResult", + "SearchRunState", + "ToolCall", + "ToolCallResult", + "ToolMetadata", + "inspect_context_data", + "json_value", + "load_context_data", + "update_context_data_descriptions", +] diff --git a/src/sr_harness/core/api.py b/src/sr_harness/core/api.py new file mode 100644 index 0000000000000000000000000000000000000000..1f585c8c1890ad4171824b219fd932374244f8a1 --- /dev/null +++ b/src/sr_harness/core/api.py @@ -0,0 +1,97 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Iterator + +from .tool import ToolCall + + +@dataclass(init=False) +class APICallSample: + """One complete assistant sample returned by a model provider. + + ``message_extra`` contains provider message fields not represented by the + normalized content and tool calls. The :attr:`message` + property reconstructs a provider-compatible assistant message without + retaining a duplicate raw message object. + """ + + content: str | None + _tool_calls: list[ToolCall] = field(default_factory=list, repr=False) + message_extra: dict[str, Any] = field(default_factory=dict) + + def __init__( + self, + content: str | None, + tool_calls: list[ToolCall] | None = None, + message_extra: dict[str, Any] | None = None, + ) -> None: + self.content = content + self._tool_calls = tool_calls if tool_calls is not None else [] + self.message_extra = dict(message_extra or {}) + + @property + def tool_calls(self) -> list[ToolCall]: + """Return the normalized tool calls used to construct this response.""" + return self._tool_calls + + @property + def reasoning(self) -> Any: + """Return provider reasoning without imposing one provider field name.""" + if "reasoning" in self.message_extra: + return self.message_extra["reasoning"] + return self.message_extra.get("reasoning_content") + + @property + def message(self) -> dict[str, Any]: + """Reconstruct the assistant message represented by this response.""" + message = {**self.message_extra, "content": self.content} + raw_tool_calls = [call.raw for call in self.tool_calls if isinstance(call.raw, dict)] + if raw_tool_calls and "tool_calls" not in message: + message["tool_calls"] = raw_tool_calls + message.setdefault("role", "assistant") + return message + + +@dataclass +class APICallSummary: + """ + Wrapper for LLM generator that captures the return value. + + Example: + >>> api = OpenAIAPI(model='gpt-4o-mini') + >>> result = api("Hello", n=3) # Returns APICallSummary + >>> for response in result: + ... print(response.content, response.tool_calls) + >>> print(result.ok, result.error) + >>> print(result.token_usage, result.money_usage) + """ + + gen: Iterator[APICallSample] + yielded: list[APICallSample] = field(default_factory=list, init=False) + ok: bool | None = field(default=None, init=False) + error: str | None = field(default=None, init=False) + token_usage: dict[str, float] = field(default_factory=dict, init=False) + money_usage: dict[str, float] = field(default_factory=dict, init=False) + extra: dict[str, Any] = field(default_factory=dict, init=False) + + def __iter__(self): + """Iterate over the generated contents.""" + try: + while True: + response = next(self.gen) + if not isinstance(response, APICallSample): + raise TypeError( + "API providers must yield APICallSample instances, " + f"not {type(response).__name__}" + ) + self.yielded.append(response) + yield response + except StopIteration as e: + result = e.value or {} + self.ok = bool(result.get("ok", True)) + self.error = result.get("error") + self.token_usage = dict(result.get("token_usage") or {}) + self.money_usage = dict(result.get("money_usage") or {}) + self.extra = dict(result.get("extra") or {}) diff --git a/src/sr_harness/core/context.py b/src/sr_harness/core/context.py new file mode 100644 index 0000000000000000000000000000000000000000..92cc2da6878d2147f52484709efa3f96ee9fc6ba --- /dev/null +++ b/src/sr_harness/core/context.py @@ -0,0 +1,316 @@ +"""Shared runtime context for agents, evaluators, and tools.""" +from __future__ import annotations + +import argparse +import threading +from typing import TYPE_CHECKING, Any +import numpy as np + +if TYPE_CHECKING: + from ..evaluator import DefaultEvaluator + from ..runtime.workspace import Workspace + +_DEFAULT_EVALUATOR = object() + + +class AgentContext: + """One authoritative context containing data, metadata, and runtime arguments. + + Args: + args: Runtime configuration shared by agents, evaluators, and tools. + data: Arrays keyed by variable or axis name. + target: Name of the current target variable. + variable_descriptions: Human-readable descriptions keyed by data name. + variable_axes: Axis names for every non-axis variable. + variable_structures: Relation variable used by each structured variable. + relation_names: Names of graph or hypergraph relation arrays. + num_nodes: Number of nodes for graph or hypergraph data. + evaluator: Evaluator instance used to fit, score, and split formulas. + workspace: Optional managed workspace available to tools. + """ + + def __init__(self, *, args: argparse.Namespace | None = None, data: dict[str, Any] | None = None, target: str | None = None, variable_descriptions: dict[str, str] | None = None, variable_axes: dict[str, tuple[str, ...]] | None = None, variable_structures: dict[str, str] | None = None, relation_names: set[str] | None = None, num_nodes: int | None = None, evaluator: DefaultEvaluator | object = _DEFAULT_EVALUATOR, workspace: Workspace | None = None) -> None: + if args is not None and not isinstance(args, argparse.Namespace): + raise TypeError("args must be an argparse.Namespace") + self.args = args if args is not None else argparse.Namespace() + defaults = { + "validation_fraction": 0.0, + "split_by": "random", + "split_random_state": 42, + "split_ood_variable": None, + "data_revision": 0, + } + for name, value in defaults.items(): + if not hasattr(self.args, name): + setattr(self.args, name, value) + self.workspace = workspace + if any(not isinstance(name, str) or not name for name in (data or {})): + raise TypeError("data keys must be non-empty strings") + self.data = {name: np.asarray(value) for name, value in (data or {}).items()} + self.target = target + if variable_descriptions is None: + self.variable_descriptions = {name: "" for name in self.data} + else: + self.variable_descriptions = dict(variable_descriptions) + if variable_axes is None: + self.variable_axes = {name: () for name in self.data} + else: + self.variable_axes = {name: tuple(axes) for name, axes in variable_axes.items()} + self.variable_structures = dict(variable_structures or {}) + self.relation_names = set(relation_names or self.variable_structures.values()) + self.num_nodes = num_nodes + from ..evaluator import DefaultEvaluator, GraphEvaluator + if evaluator is _DEFAULT_EVALUATOR: + evaluator = GraphEvaluator() if self.relation_names else DefaultEvaluator() + if not isinstance(evaluator, DefaultEvaluator): + raise TypeError("evaluator must be a DefaultEvaluator instance") + self.evaluator: DefaultEvaluator = evaluator + self._split_cache: dict[str, AgentContext] | None = None + self._lock = threading.RLock() + self._validate(allow_incomplete=not self.data or self.target is None) + + def _validate(self, *, allow_incomplete: bool = False) -> None: + names = set(self.data) + if not allow_incomplete and self.target not in names: + raise ValueError("target must name an entry in data") + if set(self.variable_descriptions) != names: + raise ValueError("variable_descriptions keys must equal data keys") + if any(not isinstance(value, str) for value in self.variable_descriptions.values()): + raise TypeError("variable descriptions must be strings") + if any( + not isinstance(axis, str) or not axis + for dimensions in self.variable_axes.values() + for axis in dimensions + ): + raise TypeError("variable_axes values must contain non-empty axis names") + non_axes = set(self.variable_axes) + axes = {axis for dimensions in self.variable_axes.values() for axis in dimensions} + if non_axes & axes or non_axes | axes != names: + raise ValueError("variable_axes keys and values must partition data keys") + for axis in axes: + if self.data[axis].ndim != 1: + raise ValueError(f"axis variable {axis!r} must be one-dimensional") + if (self.num_nodes is None) != (not self.relation_names): + raise ValueError("relation_names and num_nodes must appear together") + if self.num_nodes is not None and ( + isinstance(self.num_nodes, bool) + or not isinstance(self.num_nodes, int) + or self.num_nodes < 1 + ): + raise ValueError("num_nodes must be a positive integer") + for relation_name in self.relation_names: + if relation_name not in names: + raise ValueError("relation_names must reference entries in data") + relation = self.data[relation_name] + if relation.ndim != 2 or relation.shape[1] not in {2, 3}: + raise ValueError(f"relation variable {relation_name!r} must have shape (E, 2) or (H, 3)") + if relation.dtype.kind not in "iu": + raise ValueError(f"relation variable {relation_name!r} must contain integer endpoints") + if np.any(relation < 0) or np.any(relation >= self.num_nodes): + raise ValueError(f"relation variable {relation_name!r} endpoints must be in [0, {self.num_nodes})") + for variable, structure in self.variable_structures.items(): + if variable not in names or structure not in names: + raise ValueError("variable_structures must reference entries in data") + if variable == structure: + raise ValueError("a structured variable cannot reference itself") + if structure not in self.relation_names: + raise ValueError("variable_structures values must name relation variables") + relation = self.data[structure] + if relation.ndim != 2 or relation.shape[1] not in {2, 3}: + raise ValueError(f"structure variable {structure!r} must have shape (E, 2) or (H, 3)") + if self.data[variable].ndim == 0 or self.data[variable].shape[-1] != relation.shape[0]: + raise ValueError(f"structured variable {variable!r} must end in the relation dimension") + if relation.dtype.kind not in "iu": + raise ValueError(f"structure variable {structure!r} must contain integer endpoints") + if np.any(relation < 0) or np.any(relation >= self.num_nodes): + raise ValueError(f"structure variable {structure!r} endpoints must be in [0, {self.num_nodes})") + + def invalidate_splits(self) -> None: + """Discard cached training and validation context views.""" + with self._lock: + self._split_cache = None + + def _sync_builtin_evaluator(self) -> None: + from ..evaluator import DefaultEvaluator, GraphEvaluator + if type(self.evaluator) not in {DefaultEvaluator, GraphEvaluator}: + return + self.evaluator = GraphEvaluator() if self.relation_names else DefaultEvaluator() + + def _splits(self) -> dict[str, AgentContext]: + with self._lock: + if self.target is None: + raise ValueError("target must be configured before splitting AgentContext") + if self._split_cache is None: + splits = self.evaluator.split(self) + if set(splits) != {"train", "validation"}: + raise ValueError("DefaultEvaluator.split() must return train and validation contexts") + if any(not isinstance(split, AgentContext) for split in splits.values()): + raise TypeError("DefaultEvaluator.split() values must be AgentContext instances") + self._split_cache = splits + return self._split_cache + + def with_data(self, data: dict[str, np.ndarray]) -> AgentContext: + """Create a context view over data while preserving runtime configuration. + + Args: + data: Data mapping for the new context view. + + Returns: + A context sharing arguments and evaluator configuration with this context. + """ + return AgentContext( + args=self.args, data=data, target=self.target, + variable_descriptions={name: self.variable_descriptions[name] for name in data}, + variable_axes={name: axes for name, axes in self.variable_axes.items() if name in data}, + variable_structures={name: structure for name, structure in self.variable_structures.items() if name in data and structure in data}, + relation_names=self.relation_names & set(data), + num_nodes=self.num_nodes, evaluator=self.evaluator, workspace=self.workspace, + ) + + @property + def train_split(self) -> AgentContext: + """Return the cached training context, computing both splits if needed.""" + return self._splits()["train"] + + @property + def validation_split(self) -> AgentContext: + """Return the cached validation context, computing both splits if needed.""" + return self._splits()["validation"] + + def axis_names(self) -> tuple[str, ...]: + """Return axis-variable names in first-occurrence order.""" + return tuple(dict.fromkeys(axis for axes in self.variable_axes.values() for axis in axes)) + + def variable_names(self) -> tuple[str, ...]: + """Return names of non-axis variables in manifest order.""" + return tuple(self.variable_axes) + + def feature_names(self) -> tuple[str, ...]: + """Return selected non-axis variables other than the target.""" + return tuple(name for name in self.variable_axes if name != self.target) + + def commit_context_data(self, loaded: dict[str, Any]) -> dict[str, Any]: + """Replace live context data with a validated loader result. + + Args: + loaded: Mapping returned by :func:`load_context_data`. + + Returns: + New data revision and loaded variable names. + """ + values = {str(name): np.asarray(value) for name, value in loaded["data"].items()} + self.data = values + self.variable_descriptions = dict(loaded["variable_descriptions"]) + self.variable_axes = { + name: tuple(axes) for name, axes in loaded["variable_axes"].items() + } + self.variable_structures = dict(loaded["variable_structures"]) + self.relation_names = set(loaded["relation_names"]) + self.num_nodes = loaded["num_nodes"] + self._sync_builtin_evaluator() + self.target = self.target if self.target in values else None + self.invalidate_splits() + self.args.data_revision += 1 + self._validate(allow_incomplete=True) + return {"revision": self.args.data_revision, "variables": list(values)} + + def commit_data(self, data: dict[str, Any], *, target: str, features: list[str] | None = None, variable_descriptions: dict[str, str] | None = None) -> dict[str, Any]: + """Commit an ordinary aligned data selection to the live context. + + Args: + data: Available arrays keyed by column name. + target: Target column to retain. + features: Feature columns to retain. Defaults to no features. + variable_descriptions: Optional descriptions for retained columns. + + Returns: + A summary containing revision, selection, columns, and row count. + """ + selected = list(dict.fromkeys([*(features or []), target])) + if target not in data: + raise ValueError(f"target column does not exist: {target}") + arrays = {name: np.asarray(data[name]) for name in selected} + with self._lock: + self.data = arrays + self.target = target + self.variable_descriptions = {name: str((variable_descriptions or {}).get(name, "")) for name in arrays} + self.variable_axes = {name: () for name in arrays} + self.variable_structures = {} + self.relation_names = set() + self.num_nodes = None + self._sync_builtin_evaluator() + self.invalidate_splits() + self.args.data_revision += 1 + self._validate() + return {"revision": self.args.data_revision, "target": target, "features": list(self.feature_names()), "columns": list(arrays), "rows": len(arrays[target])} + + def add_features(self, features: dict[str, Any], *, descriptions: dict[str, str] | None = None) -> dict[str, Any]: + """Add aligned feature arrays while preserving the current target. + + Args: + features: New feature arrays keyed by name. + descriptions: Optional descriptions for the new features. + + Returns: + The commit summary produced for the updated data. + + Raises: + ValueError: If the context has no configured target. + """ + if self.target is None: + raise ValueError("target must be configured before adding features") + descriptions = self.variable_descriptions | { + name: (descriptions or {}).get(name, "") for name in features + } + return self.commit_data(self.data | features, target=self.target, features=[*self.feature_names(), *features], variable_descriptions=descriptions) + + def update_selection(self, *, target: str, features: list[str], variable_descriptions: dict[str, str] | None = None) -> dict[str, Any]: + """Select the variables used by symbolic regression. + + Args: + target: Target variable name. + features: Feature variable names. + variable_descriptions: Description updates to apply before selection. + + Returns: + New revision and selected target and features. + """ + keep_variables = set(features) | {target} + keep_axes = {axis for name, axes in self.variable_axes.items() if name in keep_variables for axis in axes} + keep = keep_variables | keep_axes + self.data = {name: value for name, value in self.data.items() if name in keep} + self.target = target + descriptions = self.variable_descriptions | dict(variable_descriptions or {}) + self.variable_descriptions = {name: descriptions.get(name, "") for name in self.data} + self.variable_axes = {name: axes for name, axes in self.variable_axes.items() if name in keep_variables} + self.variable_structures = {name: structure for name, structure in self.variable_structures.items() if name in self.data and structure in self.data} + self.relation_names &= set(self.data) + if not self.relation_names: + self.num_nodes = None + self._sync_builtin_evaluator() + self.invalidate_splits() + self.args.data_revision += 1 + self._validate() + return {"revision": self.args.data_revision, "target": target, "features": list(self.feature_names()), "selection_changed": True} + + def schema(self) -> dict[str, Any]: + """Return a serializable description of the active context data.""" + axes = set(self.axis_names()) + return { + "revision": self.args.data_revision, "num_nodes": self.num_nodes, + "target": self.target, "features": list(self.feature_names()), "columns": list(self.data), + "rows": len(self.data[self.target]) if self.target in self.data else 0, + "variable_descriptions": dict(self.variable_descriptions), + "variables": {name: {"shape": list(value.shape), "dtype": str(value.dtype), "axes": list(self.variable_axes.get(name, ())), "description": self.variable_descriptions[name], **({"kind": "relation"} if name in self.relation_names else {})} for name, value in self.data.items() if name not in axes}, + "axes": {name: {"size": len(self.data[name]), "dtype": str(self.data[name].dtype), "description": self.variable_descriptions[name]} for name in axes}, + } + + def __getstate__(self) -> dict[str, Any]: + state = self.__dict__.copy() + state.pop("_lock", None) + return state + + def __setstate__(self, state: dict[str, Any]) -> None: + self.__dict__.update(state) + self._lock = threading.RLock() + diff --git a/src/sr_harness/core/context_data.py b/src/sr_harness/core/context_data.py new file mode 100644 index 0000000000000000000000000000000000000000..531b7da4566c6c62dd14bfde956f4bbac58c759b --- /dev/null +++ b/src/sr_harness/core/context_data.py @@ -0,0 +1,518 @@ +"""Manifest-backed NumPy data stored in a workspace directory.""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +import tempfile +from typing import TYPE_CHECKING, Any + +import numpy as np + +if TYPE_CHECKING: + from ..runtime.workspace import Workspace + + +class ContextManifestError(ValueError): + """Raised when a context-data manifest cannot be validated.""" + + +class _ContextDataReader: + """Private implementation shared by the public loading functions.""" + + MANIFEST_NAME = "manifest.json" + REQUIRED_ROOT_FIELDS = {"variables", "axes"} + OPTIONAL_ROOT_FIELDS = {"num_nodes"} + REQUIRED_VARIABLE_FIELDS = {"file", "description", "axes"} + OPTIONAL_VARIABLE_FIELDS = {"kind", "structure"} + AXIS_SOURCE_FIELDS = {"values", "file", "size"} + AXIS_FIELDS = {"description", *AXIS_SOURCE_FIELDS} + + def __init__(self, directory: str | Path, *, workspace: Workspace | None = None): + self.directory = Path(directory).resolve() + self.workspace = workspace + + def inspect(self) -> dict[str, Any]: + """Validate the store and return diagnostics without raising. + + Returns: + A serializable report containing errors, warnings, and array summaries. + """ + errors: list[str] = [] + warnings: list[str] = [] + manifest = self._read_manifest(errors) + loaded = ( + self._validate_manifest(manifest, errors, warnings) + if manifest is not None + else None + ) + report: dict[str, Any] = { + "valid": not errors, + "path": str(self.directory), + "errors": errors, + "warnings": warnings, + "num_nodes": loaded["num_nodes"] if loaded is not None else None, + "variables": {}, + "axes": {}, + } + if loaded is not None: + report["variables"] = { + name: { + "file": manifest["variables"][name]["file"], + "shape": list(value.shape), + "dtype": str(value.dtype), + "axes": list(loaded["variable_axes"][name]), + **( + {"structure": loaded["variable_structures"][name]} + if name in loaded["variable_structures"] else {} + ), + **({"kind": "relation"} if name in loaded["relation_names"] else {}), + "description": loaded["variable_descriptions"][name], + } + for name, value in loaded["data"].items() + if name in manifest["variables"] + } + report["axes"] = { + name: { + "size": len(loaded["data"][name]), + "dtype": str(loaded["data"][name].dtype), + "storage": axis["storage"], + "description": loaded["variable_descriptions"][name], + } + for name, axis in loaded["axis_metadata"].items() + } + return report + + def load(self) -> dict[str, Any]: + """Validate and load all variables and axes. + + Returns: + An AgentContext-ready mapping containing arrays and metadata. + + Raises: + ContextManifestError: If the manifest or referenced arrays are invalid. + """ + errors: list[str] = [] + warnings: list[str] = [] + manifest = self._read_manifest(errors) + loaded = ( + self._validate_manifest(manifest, errors, warnings) + if manifest is not None else None + ) + if errors or loaded is None: + raise ContextManifestError("Invalid context.data:\n- " + "\n- ".join(errors)) + return loaded + + def _read_manifest(self, errors: list[str]) -> dict[str, Any] | None: + manifest_path = self.directory / self.MANIFEST_NAME + if not self.directory.is_dir(): + errors.append(f"directory does not exist: {self.directory}") + return None + if not manifest_path.is_file(): + errors.append(f"missing {self.MANIFEST_NAME}") + return None + + def reject_duplicates(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ContextManifestError(f"duplicate JSON key: {key}") + result[key] = value + return result + + try: + opener = self.workspace.safe_open if self.workspace is not None else open + with opener(manifest_path, "r", encoding="utf-8") as f: + manifest = json.load(f, object_pairs_hook=reject_duplicates) + except (ContextManifestError, json.JSONDecodeError, OSError) as exc: + errors.append(f"cannot read {self.MANIFEST_NAME}: {exc}") + return None + if not isinstance(manifest, dict): + errors.append("manifest root must be a JSON object") + return None + return manifest + + def _validate_manifest( + self, + manifest: dict[str, Any], + errors: list[str], + warnings: list[str], + ) -> dict[str, Any] | None: + self._check_fields( + "manifest", + manifest, + self.REQUIRED_ROOT_FIELDS, + errors, + optional=self.OPTIONAL_ROOT_FIELDS, + ) + variables = manifest.get("variables") + axes = manifest.get("axes") + num_nodes = manifest.get("num_nodes") + if "num_nodes" in manifest and ( + isinstance(num_nodes, bool) or not isinstance(num_nodes, int) or num_nodes < 1 + ): + errors.append("manifest.num_nodes must be a positive integer") + num_nodes = None + if not isinstance(variables, dict) or not variables: + errors.append("manifest.variables must be a non-empty object") + variables = {} + if not isinstance(axes, dict): + errors.append("manifest.axes must be an object") + axes = {} + + loaded_axes: dict[str, dict[str, Any]] = {} + referenced_files = {self.MANIFEST_NAME} + for name, spec in axes.items(): + location = f"axes.{name}" + if not self._valid_name(name): + errors.append(f"{location}: name must be non-empty and contain no path separators") + continue + if not isinstance(spec, dict): + errors.append(f"{location} must be an object") + continue + if "description" not in spec: + errors.append(f"{location} is missing fields: ['description']") + if extra := sorted(set(spec) - self.AXIS_FIELDS): + errors.append(f"{location} contains unsupported fields: {extra}") + description = self._description(location, spec, errors) + sources = self.AXIS_SOURCE_FIELDS & set(spec) + if len(sources) != 1: + errors.append(f"{location} must contain exactly one of values, file, or size") + continue + source = next(iter(sources)) + try: + if source == "values": + if not isinstance(spec["values"], list) or not spec["values"]: + raise ValueError("values must be a non-empty JSON array") + if any(isinstance(value, (list, dict)) for value in spec["values"]): + raise ValueError("values must contain scalar JSON values") + values = np.asarray(spec["values"]) + elif source == "size": + size = spec["size"] + if isinstance(size, bool) or not isinstance(size, int) or size < 1: + raise ValueError("size must be a positive integer") + values = np.arange(size) + else: + expected = f"{name}.npy" + if spec["file"] != expected: + raise ValueError(f"file must be {expected!r}") + referenced_files.add(expected) + values = self._load_array(expected) + if values.ndim != 1: + raise ValueError(f"axis array must be one-dimensional, got shape {values.shape}") + if values.ndim != 1: + raise ValueError("values must be one-dimensional") + loaded_axes[name] = {"values": values, "description": description, "storage": source} + except (OSError, ValueError) as exc: + errors.append(f"{location}: {exc}") + + loaded_values: dict[str, np.ndarray] = {} + variable_axes: dict[str, tuple[str, ...]] = {} + variable_structures: dict[str, str] = {} + relation_names: set[str] = set() + descriptions: dict[str, str] = {} + used_axes: set[str] = set() + for name, spec in variables.items(): + location = f"variables.{name}" + if not self._valid_name(name): + errors.append(f"{location}: name must be non-empty and contain no path separators") + continue + if not isinstance(spec, dict): + errors.append(f"{location} must be an object") + continue + self._check_fields( + location, + spec, + self.REQUIRED_VARIABLE_FIELDS, + errors, + optional=self.OPTIONAL_VARIABLE_FIELDS, + ) + description = self._description(location, spec, errors) + structure = spec.get("structure") + if structure is not None and not self._valid_name(structure): + errors.append(f"{location}.structure must name an A or T variable") + structure = None + kind = spec.get("kind") + if kind not in {None, "relation"}: + errors.append(f"{location}.kind must be 'relation' when provided") + kind = None + expected = f"{name}.npy" + if spec.get("file") != expected: + errors.append(f"{location}.file must be {expected!r}") + continue + declared_axes = spec.get("axes") + if not isinstance(declared_axes, list) or any( + not isinstance(axis, str) or not axis for axis in declared_axes + ): + errors.append(f"{location}.axes must be an array of non-empty axis names") + continue + missing_axes = [axis for axis in declared_axes if axis not in axes] + if missing_axes: + errors.append(f"{location}.axes references missing axes: {missing_axes}") + continue + referenced_files.add(expected) + try: + value = self._load_array(expected) + except (OSError, ValueError) as exc: + errors.append(f"{location}: {exc}") + continue + if value.ndim != len(declared_axes): + errors.append( + f"{location}: array has {value.ndim} dimensions but declares " + f"{len(declared_axes)} axes" + ) + continue + mismatches = [ + f"{axis}={len(loaded_axes[axis]['values'])} (data={value.shape[index]})" + for index, axis in enumerate(declared_axes) + if axis in loaded_axes and len(loaded_axes[axis]["values"]) != value.shape[index] + ] + if mismatches: + errors.append(f"{location}: axis length mismatch: {', '.join(mismatches)}") + continue + loaded_values[name] = value + variable_axes[name] = tuple(declared_axes) + if structure is not None: + variable_structures[name] = structure + if kind == "relation": + relation_names.add(name) + descriptions[name] = description + used_axes.update(declared_axes) + + unused_axes = sorted(set(axes) - used_axes) + if unused_axes: + errors.append(f"manifest.axes contains unreferenced axes: {unused_axes}") + + if bool(relation_names) != (num_nodes is not None): + errors.append("manifest.num_nodes and relation metadata must appear together") + for relation_name in relation_names: + location = f"variables.{relation_name}" + relation = loaded_values.get(relation_name) + if relation is None: + continue + if relation.ndim != 2 or relation.shape[1] not in {2, 3}: + errors.append( + f"{location}: relation must have shape (E, 2) or (H, 3), got {relation.shape}" + ) + continue + if relation.dtype.kind not in "iu": + errors.append(f"{location}: relation endpoints must use an integer dtype") + elif num_nodes is not None and (np.any(relation < 0) or np.any(relation >= num_nodes)): + errors.append(f"{location}: relation endpoints must be in [0, {num_nodes})") + for variable, structure in variable_structures.items(): + location = f"variables.{variable}.structure" + if variable == structure: + errors.append(f"{location}: a structured variable cannot reference itself") + continue + if structure not in loaded_values: + errors.append(f"{location} references missing variable {structure!r}") + continue + if structure not in relation_names: + errors.append(f"{location} must reference a variable with kind 'relation'") + continue + relation = loaded_values[structure] + if relation.ndim != 2 or relation.shape[1] not in {2, 3}: + errors.append( + f"{location}: {structure!r} must have shape (E, 2) or (H, 3), " + f"got {relation.shape}" + ) + continue + dependent = loaded_values.get(variable) + if dependent is not None and ( + dependent.ndim == 0 or dependent.shape[-1] != relation.shape[0] + ): + errors.append( + f"{location}: {variable!r} must end in a dimension of " + f"length {relation.shape[0]}" + ) + if relation.dtype.kind not in "iu": + errors.append(f"{location}: relation endpoints must use an integer dtype") + elif num_nodes is not None and (np.any(relation < 0) or np.any(relation >= num_nodes)): + errors.append(f"{location}: relation endpoints must be in [0, {num_nodes})") + actual_npy = {path.name for path in self.directory.glob("*.npy") if path.is_file()} + untracked = sorted(actual_npy - referenced_files) + if untracked: + warnings.append(f"unreferenced NPY files: {untracked}") + if errors: + return None + data = {**{name: axis["values"] for name, axis in loaded_axes.items()}, **loaded_values} + all_descriptions = {name: axis["description"] for name, axis in loaded_axes.items()} | descriptions + return { + "data": data, + "variable_descriptions": all_descriptions, + "variable_axes": variable_axes, + "variable_structures": variable_structures, + "relation_names": relation_names, + "num_nodes": num_nodes, + "axis_metadata": loaded_axes, + } + + def _load_array(self, filename: str) -> np.ndarray: + path = self.directory / filename + if not path.is_file() or path.parent != self.directory: + raise ValueError(f"missing array file: {filename}") + opener = self.workspace.safe_open if self.workspace is not None else open + with opener(path, "rb") as f: + value = np.load(f, allow_pickle=False) + if not isinstance(value, np.ndarray): + raise ValueError(f"{filename} does not contain one NPY array") + if value.dtype.hasobject: + raise ValueError(f"{filename} uses object dtype, which is not allowed") + return value + + @staticmethod + def _valid_name(name: Any) -> bool: + return ( + isinstance(name, str) + and bool(name.strip()) + and name not in {".", ".."} + and "/" not in name + and "\\" not in name + and "\0" not in name + ) + + @staticmethod + def _description(location: str, spec: dict[str, Any], errors: list[str]) -> str: + description = spec.get("description") + if not isinstance(description, str): + errors.append(f"{location}.description must be a string") + return "" + return description.strip() + + @staticmethod + def _check_fields( + location: str, + value: dict[str, Any], + expected: set[str], + errors: list[str], + *, + optional: set[str] | None = None, + ) -> None: + optional = optional or set() + missing = sorted(expected - set(value)) + extra = sorted(set(value) - expected - optional) + if missing: + errors.append(f"{location} is missing fields: {missing}") + if extra: + errors.append(f"{location} contains unsupported fields: {extra}") + + +def load_context_data(directory: str | Path, *, workspace: Workspace | None = None) -> dict[str, Any]: + """Validate and load one manifest-backed ``context.data`` directory. + + Args: + directory: Directory containing ``manifest.json`` and array files. + workspace: Workspace enforcing safe reads, when available. + + Returns: + An AgentContext-ready mapping containing arrays and metadata. + """ + return _ContextDataReader(directory, workspace=workspace).load() + + +def inspect_context_data(directory: str | Path, *, workspace: Workspace | None = None) -> dict[str, Any]: + """Return validation diagnostics without raising for manifest errors. + + Args: + directory: Directory containing ``manifest.json`` and array files. + workspace: Workspace enforcing safe reads, when available. + + Returns: + A serializable validation report. + """ + return _ContextDataReader(directory, workspace=workspace).inspect() + + +def update_context_data_descriptions( + directory: str | Path, + descriptions: dict[str, str], + *, + workspace: Workspace | None = None, +) -> dict[str, Any]: + """Update variable and axis descriptions in ``manifest.json``. + + The complete store is validated before the edit. An atomic replacement is + used when the directory permits creating entries. If the directory is + read-only but ``manifest.json`` itself is writable, the existing file is + updated in place, matching normal POSIX file-permission semantics. Because + only existing string-valued description fields are changed, structural + validity is preserved. The returned mapping matches :func:`load_context_data`. + """ + directory = Path(directory).resolve() + manifest_path = directory / _ContextDataReader.MANIFEST_NAME + loaded = load_context_data(directory, workspace=workspace) + opener = workspace.safe_open if workspace is not None else open + if not isinstance(descriptions, dict) or any( + not isinstance(name, str) or not isinstance(value, str) + for name, value in descriptions.items() + ): + raise ValueError("descriptions must map variable names to text") + unknown = set(descriptions) - set(loaded["data"]) + if unknown: + raise ValueError(f"unknown context.data variables: {sorted(unknown)}") + with opener(manifest_path, "r", encoding="utf-8") as f: + manifest = json.load(f) + for section in ("variables", "axes"): + for name, spec in manifest[section].items(): + if name in descriptions: + spec["description"] = descriptions[name].strip() + serialized = json.dumps(manifest, ensure_ascii=False, indent=2) + "\n" + if workspace is not None: + relative_manifest = str(manifest_path.relative_to(workspace.path)) + temporary_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + dir=workspace.path, + prefix=".manifest-", + suffix=".json.tmp", + delete=False, + ) as stream: + temporary_path = Path(stream.name) + stream.write(serialized) + stream.flush() + os.fsync(stream.fileno()) + workspace.replace_file(temporary_path, relative_manifest) + temporary_path = None + finally: + if temporary_path is not None: + temporary_path.unlink(missing_ok=True) + updated = dict(loaded) + updated["variable_descriptions"] = loaded["variable_descriptions"] | { + name: value.strip() for name, value in descriptions.items() + } + return updated + temporary_path = None + try: + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + dir=directory, + prefix=".manifest-", + suffix=".json.tmp", + delete=False, + ) as stream: + temporary_path = Path(stream.name) + stream.write(serialized) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary_path, manifest_path) + temporary_path = None + except PermissionError: + if temporary_path is not None: + temporary_path.unlink(missing_ok=True) + with manifest_path.open("w", encoding="utf-8") as stream: + stream.write(serialized) + stream.flush() + os.fsync(stream.fileno()) + finally: + if temporary_path is not None: + temporary_path.unlink(missing_ok=True) + updated = dict(loaded) + updated["variable_descriptions"] = loaded["variable_descriptions"] | { + name: value.strip() for name, value in descriptions.items() + } + return updated diff --git a/src/sr_harness/core/search.py b/src/sr_harness/core/search.py new file mode 100644 index 0000000000000000000000000000000000000000..6f0754bef9b7dc8a4fb6fcc466948bf38954a078 --- /dev/null +++ b/src/sr_harness/core/search.py @@ -0,0 +1,671 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""In-memory state for one symbolic-regression search run.""" +from __future__ import annotations + +import json +import math +import threading +import uuid +from dataclasses import asdict, dataclass, field, is_dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Literal + +import numpy as np + +from .tool import ToolCall, ToolCallResult + +ParentRelation = Literal["continuation", "restart_seed", "context_merge"] + + +def json_value(value: Any) -> Any: + """Convert runtime values to standards-compliant JSON values. + + Args: + value: Input value. + + Returns: + Any: The operation result. + """ + if value is None or type(value) in (str, int, bool): + return value + if is_dataclass(value) and not isinstance(value, type): + return json_value(asdict(value)) + if isinstance(value, np.ndarray): + return json_value(value.tolist()) + if isinstance(value, np.generic): + return json_value(value.item()) + if isinstance(value, float): + return value if math.isfinite(value) else None + if isinstance(value, Path): + return str(value) + if isinstance(value, ToolCall): + return { + "name": value.name, + "params": json_value(value.params), + "id": value.id, + "raw": json_value(value.raw), + "raw_str": value.raw_str, + } + if isinstance(value, ToolCallResult): + return { + "ok": value.ok, + "result": json_value(value.result), + "result_str": value.result_str, + "meta_data": json_value(value.meta_data), + } + if isinstance(value, dict): + return {str(key): json_value(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [json_value(item) for item in value] + try: + json.dumps(value, allow_nan=False) + return value + except (TypeError, ValueError): + return str(value) + + +@dataclass(frozen=True, slots=True) +class SearchCoordinate: + """Coordinates of one R-C-L-K search sample.""" + R: int + C: int + L: int + K: int + + +@dataclass(frozen=True, slots=True) +class ParentLink: + """Typed link to a parent search node.""" + parent_node_id: str + relation: ParentRelation + + def to_dict(self) -> dict[str, str]: + """Return a serializable dictionary representation. + + Returns: + dict[str, str]: The operation result. + """ + return {"node_id": self.parent_node_id, "relation": self.relation} + + +@dataclass(slots=True) +class SearchNode: + """Recorded state for one search-tree node.""" + run_id: str + node_id: str + node_label: str + coordinate: SearchCoordinate + parents: tuple[ParentLink, ...] + created_at: str + core: dict[str, Any] + detail: dict[str, Any] + + def to_dict(self, *, include_detail: bool = True) -> dict[str, Any]: + """Return a serializable dictionary representation. + + Args: + include_detail: Whether to include detailed payloads. + + Returns: + dict[str, Any]: The operation result. + """ + record = { + "run_id": self.run_id, + "node_id": self.node_id, + "node_label": self.node_label, + "created_at": self.created_at, + "coord": asdict(self.coordinate), + "progress": ( + f"(R={self.coordinate.R}) x (C={self.coordinate.C}) x " + f"(L={self.coordinate.L}) x (K={self.coordinate.K})" + ), + "parents": [parent.to_dict() for parent in self.parents], + "core": json_value(self.core), + } + if include_detail: + record["detail"] = json_value(self.detail) + return record + + +@dataclass(slots=True) +class CandidateRecord: + """Candidate formula and its evaluation details.""" + formula: str + node_id: str + details: dict[str, Any] = field(default_factory=dict) + + def split_metrics(self, split: str) -> dict[str, Any]: + """Run the ``split metrics`` operation. + + Args: + split: Data split name. + + Returns: + dict[str, Any]: The operation result. + """ + return ( + self.details.get("data_split_results", {}) + .get(split, {}) + .get("metrics", {}) + ) + + def metric(self, name: str, split: str) -> Any: + """Run the ``metric`` operation. + + Args: + name: Registered name. + split: Data split name. + + Returns: + Any: The operation result. + """ + return self.split_metrics(split).get(name) + + @property + def complexity(self) -> Any: + """Run the ``complexity`` operation. + + Returns: + Any: The operation result. + """ + return self.metric("complexity", "train") + + def to_dict(self) -> dict[str, Any]: + """Return a serializable dictionary representation. + + Returns: + dict[str, Any]: The operation result. + """ + return { + "formula": self.formula, + "node_id": self.node_id, + "details": json_value(self.details), + } + + def display_dict(self) -> dict[str, Any]: + """Return a flattened view for UI rendering without mutating the record. + + Returns: + dict[str, Any]: The operation result. + """ + split = "validation" if self.split_metrics("validation") else "train" + return self.to_dict() | {"split": split} | json_value(self.split_metrics(split)) + + +@dataclass(slots=True) +class SearchResult: + """Final snapshot of one symbolic-regression run.""" + status: Literal["completed", "early_stopped", "interrupted", "failed"] + progress: str + candidates: list[CandidateRecord] + pareto_front: list[int] + best_candidate: int | None + + def to_dict(self) -> dict[str, Any]: + """Return a serializable dictionary representation. + + Returns: + dict[str, Any]: The operation result. + """ + return { + "status": self.status, + "progress": self.progress, + "candidates": [candidate.to_dict() for candidate in self.candidates], + "pareto_front": list(self.pareto_front), + "best_candidate": self.best_candidate, + } + + +class SearchRunState: + """Authoritative in-memory state for one run, with optional persistence.""" + + def __init__( + self, + save_path: str | Path | None, + ranking_metric: str, + larger_is_better: bool, + agent_metadata: dict[str, Any] | None = None, + run_id: str | None = None, + ) -> None: + if run_id is not None and (not isinstance(run_id, str) or not run_id): + raise ValueError("run_id must be None or a non-empty string") + self.run_id = uuid.uuid4().hex if run_id is None else run_id + self.ranking_metric = ranking_metric + self.larger_is_better = larger_is_better + self.nodes: dict[str, SearchNode] = {} + self._candidates: list[CandidateRecord] = [] + self._lock = threading.RLock() + self._save_path = Path(save_path) if save_path is not None else None + self._nodes_path = self._save_path / "nodes.jsonl" if self._save_path else None + self._result_path = self._save_path / "result.json" if self._save_path else None + if self._save_path is not None: + self._save_path.mkdir(parents=True, exist_ok=True) + metadata = { + "run_id": self.run_id, + "created_at": self.now(), + "agent": agent_metadata or {}, + } + self._write_json(self._save_path / "run.json", metadata) + + @staticmethod + def now() -> str: + """Run the ``now`` operation. + + Returns: + str: The operation result. + """ + return datetime.now(timezone.utc).astimezone().isoformat(timespec="milliseconds") + + @staticmethod + def node_label(R: int, C: int, L: int, K: int) -> str: + """Run the ``node label`` operation. + + Args: + R: One-based restart index. + C: One-based conversation-branch index. + L: One-based refinement-step index. + K: One-based local-sample index. + + Returns: + str: The operation result. + """ + return f"R{R}-C{C}-L{L}-K{K}" + + def node_id(self, R: int, C: int, L: int, K: int) -> str: + """Run the ``node id`` operation. + + Args: + R: One-based restart index. + C: One-based conversation-branch index. + L: One-based refinement-step index. + K: One-based local-sample index. + + Returns: + str: The operation result. + """ + return f"{self.run_id}:{self.node_label(R=R, C=C, L=L, K=K)}" + + @staticmethod + def parent_link(parent_node_id: str, relation: ParentRelation) -> ParentLink: + """Run the ``parent link`` operation. + + Args: + parent_node_id: The parent node id value. + relation: Relation expression that binds symbolic indices. + + Returns: + ParentLink: The operation result. + """ + return ParentLink(parent_node_id=parent_node_id, relation=relation) + + def register_iteration( + self, + response_list: list, + results_list: list, + parents: tuple[ParentLink, ...], + prompt: list[dict[str, Any]], + usage: dict[str, Any], + R: int, + L: int, + C: int, + ) -> None: + """Register iteration. + + Args: + response_list: Model responses for the current step. + results_list: Tool results aligned with model responses. + parents: Parent links for the new search nodes. + prompt: Prompt messages sent to the model. + usage: Token and price usage information. + R: One-based restart index. + L: One-based refinement-step index. + C: One-based conversation-branch index. + """ + with self._lock: + for K, (response, results) in enumerate(zip(response_list, results_list), 1): + content = response.content + tool_calls = response.tool_calls + message = response.message + coordinate = SearchCoordinate(R=R, C=C, L=L, K=K) + node = SearchNode( + run_id=self.run_id, + node_id=self.node_id(R=R, C=C, L=L, K=K), + node_label=self.node_label(R=R, C=C, L=L, K=K), + coordinate=coordinate, + parents=parents, + created_at=self.now(), + core=self._build_core(content, tool_calls, results, message), + detail={ + "prompt": json_value(prompt), + "message": json_value(message), + "content": content, + "tool_calls": json_value(tool_calls), + "tool_results": json_value(results), + "usage": json_value(usage), + }, + ) + self.nodes[node.node_id] = node + if self._nodes_path is not None: + with self._nodes_path.open("a", encoding="utf-8") as stream: + stream.write( + json.dumps(node.to_dict(), ensure_ascii=False, allow_nan=False) + "\n" + ) + + def push_candidate(self, candidate: CandidateRecord) -> bool: + """Run the ``push candidate`` operation. + + Args: + candidate: The candidate value. + + Returns: + bool: The operation result. + """ + priority = self._candidate_priority(candidate) + if priority is None: + return False + with self._lock: + self._candidates.append(candidate) + return True + + def update_diagnostics(self, formula: str, diagnostics: dict[str, Any]) -> None: + """Update diagnostics. + + Args: + formula: Symbolic formula string. + diagnostics: Diagnostic values to store. + """ + with self._lock: + for candidate in self._candidates: + if candidate.formula == formula: + candidate.details["eic_diagnostics"] = diagnostics + + def ranked_candidates(self) -> list[CandidateRecord]: + """Run the ``ranked candidates`` operation. + + Returns: + list[CandidateRecord]: The operation result. + """ + with self._lock: + ranked = [ + (priority, candidate) + for candidate in self._candidates + if (priority := self._candidate_priority(candidate)) is not None + ] + return [candidate for _, candidate in sorted(ranked, key=lambda item: item[0])] + + def pareto_indices(self, candidates: list[CandidateRecord] | None = None) -> list[int]: + """Run the ``pareto indices`` operation. + + Args: + candidates: The candidates value. + + Returns: + list[int]: The operation result. + """ + candidates = candidates if candidates is not None else self.ranked_candidates() + indices = [] + current_complexity = float("inf") + for index, candidate in enumerate(candidates): + try: + complexity = float(candidate.complexity) + except (TypeError, ValueError): + complexity = float("inf") + if complexity < current_complexity: + indices.append(index) + current_complexity = complexity + return indices + + def result(self, status: str, progress: str) -> SearchResult: + """Run the ``result`` operation. + + Args: + status: Run completion status. + progress: Human-readable search progress. + + Returns: + SearchResult: The operation result. + """ + candidates = self.ranked_candidates() + result = SearchResult( + status=status, + progress=progress, + candidates=candidates, + pareto_front=self.pareto_indices(candidates), + best_candidate=0 if candidates else None, + ) + if self._result_path is not None: + self._write_json(self._result_path, result.to_dict()) + return result + + def records(self, *, include_detail: bool = False) -> list[dict[str, Any]]: + """Run the ``records`` operation. + + Args: + include_detail: Whether to include detailed payloads. + + Returns: + list[dict[str, Any]]: The operation result. + """ + with self._lock: + nodes = list(self.nodes.values()) + return [node.to_dict(include_detail=include_detail) for node in nodes] + + @property + def node_count(self) -> int: + """Run the ``node count`` operation. + + Returns: + int: The operation result. + """ + with self._lock: + return len(self.nodes) + + @property + def latest_coordinate(self) -> SearchCoordinate | None: + """Return the coordinate of the most recently recorded search node. + + Returns: + SearchCoordinate | None: The operation result. + """ + with self._lock: + if not self.nodes: + return None + node_id = next(reversed(self.nodes)) + return self.nodes[node_id].coordinate + + def export_state(self) -> dict[str, Any]: + """Return enough durable state to rebuild this run after a restart.""" + with self._lock: + return { + "version": 1, + "run_id": self.run_id, + "ranking_metric": self.ranking_metric, + "larger_is_better": self.larger_is_better, + "nodes": [node.to_dict(include_detail=True) for node in self.nodes.values()], + "candidates": [candidate.to_dict() for candidate in self._candidates], + } + + @classmethod + def from_state(cls, snapshot: dict[str, Any], save_path: str | Path | None = None) -> "SearchRunState": + """Rebuild a run from :meth:`export_state` without replaying work.""" + expected_fields = { + "version", "run_id", "ranking_metric", "larger_is_better", + "nodes", "candidates", + } + if set(snapshot) != expected_fields: + raise ValueError("Persisted SearchRunState does not match the current schema") + if snapshot["version"] != 1: + raise ValueError("Unsupported SearchRunState snapshot version") + state = cls.__new__(cls) + state.run_id = str(snapshot["run_id"]) + state.ranking_metric = str(snapshot["ranking_metric"]) + state.larger_is_better = bool(snapshot["larger_is_better"]) + state.nodes = {} + state._candidates = [] + state._lock = threading.RLock() + state._save_path = Path(save_path) if save_path is not None else None + state._nodes_path = state._save_path / "nodes.jsonl" if state._save_path else None + state._result_path = state._save_path / "result.json" if state._save_path else None + nodes = snapshot["nodes"] + if not isinstance(nodes, list) or any(not isinstance(item, dict) for item in nodes): + raise TypeError("Persisted search nodes must be a list of dictionaries") + for item in nodes: + coord = item["coord"] + parents = tuple( + ParentLink( + parent_node_id=str(parent["node_id"]), + relation=parent["relation"], + ) + for parent in item["parents"] + ) + node = SearchNode( + run_id=str(item["run_id"]), + node_id=str(item["node_id"]), + node_label=str(item["node_label"]), + coordinate=SearchCoordinate( + R=int(coord["R"]), + C=int(coord["C"]), + L=int(coord["L"]), + K=int(coord["K"]), + ), + parents=parents, + created_at=str(item["created_at"]), + core=dict(item["core"]), + detail=dict(item["detail"]), + ) + state.nodes[node.node_id] = node + candidates = snapshot["candidates"] + if not isinstance(candidates, list) or any(not isinstance(item, dict) for item in candidates): + raise TypeError("Persisted candidates must be a list of dictionaries") + state._candidates = [ + CandidateRecord( + formula=str(item["formula"]), + node_id=str(item["node_id"]), + details=dict(item["details"]), + ) + for item in candidates + ] + return state + + def node_record(self, node_id: str) -> dict[str, Any] | None: + """Run the ``node record`` operation. + + Args: + node_id: The node id value. + + Returns: + dict[str, Any] | None: The operation result. + """ + with self._lock: + node = self.nodes.get(node_id) + return node.to_dict() if node is not None else None + + def _candidate_priority(self, candidate: CandidateRecord) -> tuple[float, float] | None: + validation = candidate.metric(self.ranking_metric, "validation") + metric = validation if validation is not None else candidate.metric( + self.ranking_metric, "train" + ) + try: + metric = float(metric) + complexity = float(candidate.complexity) + except (TypeError, ValueError): + return None + if not math.isfinite(metric) or not math.isfinite(complexity): + return None + return (-metric if self.larger_is_better else metric, complexity) + + @staticmethod + def _build_core(content, tool_calls, results, message) -> dict[str, Any]: + best_record = None + is_candidate = False + for tool_call, call_result in zip(tool_calls, results): + if not call_result.ok: + continue + split_results = call_result.result.get("data_split_results", {}) + split_name = "validation" if "validation" in split_results else "train" + metrics = split_results.get(split_name, {}).get("metrics") + if metrics is None: + continue + record = { + "formula": call_result.result.get("formula"), + "split": split_name, + "rmse": metrics.get("rmse"), + "mse": metrics.get("mse"), + "mae": metrics.get("mae"), + "r2": metrics.get("r2"), + } + if ( + best_record is None + or SearchRunState._score_key(record) + < SearchRunState._score_key(best_record) + ): + best_record = record + is_candidate = is_candidate or bool(call_result.result.get("is_candidate")) + return { + "formula": best_record.pop("formula") if best_record else None, + "score": best_record, + "is_candidate": is_candidate, + "tool_names": [tool_call.name for tool_call in tool_calls], + "tool_count": len(tool_calls), + "content_preview": SearchRunState._build_preview(content, tool_calls, message), + } + + @staticmethod + def _score_key(record: dict[str, Any]) -> float: + try: + score = float(record.get("mse")) + except (TypeError, ValueError): + return float("inf") + return score if math.isfinite(score) else float("inf") + + @staticmethod + def _build_preview(content, tool_calls, message, max_param_length: int = 240) -> str: + parts = [] + if not isinstance(message, dict): + reason = "" + elif message.get("reasoning"): + reason = str(message["reasoning"]) + elif isinstance(details := message.get("reasoning_details"), list): + reason = "\n".join( + str(item.get("text")) + for item in details + if isinstance(item, dict) and item.get("text") + ) + else: + reason = "" + if reason: + parts.append(f"Reason:\n{reason.strip()}") + if content: + parts.append(f"Content:\n{content.strip()}") + if tool_calls: + lines = [] + for index, tool_call in enumerate(tool_calls, 1): + params = SearchRunState._truncate(tool_call.params or {}, max_param_length) + lines.append( + f"{index:02d}. {tool_call.name}({json.dumps(params, ensure_ascii=False)})" + ) + parts.append("Tool Calls:\n" + "\n".join(lines)) + return "\n\n".join(parts) + + @staticmethod + def _truncate(value: Any, max_length: int) -> Any: + if isinstance(value, str): + return value if len(value) <= max_length else value[:max_length] + "..." + if isinstance(value, list): + return [SearchRunState._truncate(item, max_length) for item in value] + if isinstance(value, dict): + return { + key: SearchRunState._truncate(item, max_length) + for key, item in value.items() + } + return value + + @staticmethod + def _write_json(path: Path, value: Any) -> None: + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text( + json.dumps(json_value(value), ensure_ascii=False, indent=2, allow_nan=False) + "\n", + encoding="utf-8", + ) + temporary.replace(path) diff --git a/src/sr_harness/core/tool.py b/src/sr_harness/core/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..b878033017b9255c19ccb6b7ec432a66c37c60d8 --- /dev/null +++ b/src/sr_harness/core/tool.py @@ -0,0 +1,66 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""Shared data contracts for tool definitions, calls, and results.""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Dict + + +@dataclass +class ToolMetadata: + """Description and parameter schema exposed for a tool. + + ``description`` and ``parameters`` may be omitted so ``BaseTool`` can infer + them from the implementation's signature and docstring. + """ + + name: str + description: str | None = None + parameters: Dict[str, Any] | None = None + + +@dataclass +class ToolCall: + """Normalized tool call emitted by LLM APIs and parsers.""" + + name: str + params: dict + id: str | None = None + raw: Any = None + raw_str: str | None = None + + def __post_init__(self) -> None: + """Normalize the former textual raw field into the common raw field.""" + if self.raw is None and self.raw_str is not None: + self.raw = self.raw_str + elif self.raw_str is None and isinstance(self.raw, str): + self.raw_str = self.raw + + +@dataclass +class ToolCallResult: + """Structured result returned by the tool execution boundary. + + ``result`` retains the complete machine-readable value, while + ``result_str`` is the bounded representation returned to the model. + """ + + ok: bool + result: Dict[str, Any] + result_str: str + meta_data: Dict[str, Any] + + def get(self, key: str, default: Any = None) -> Any: + """Run the ``get`` operation. + + Args: + key: The key value. + default: Fallback value. + + Returns: + Any: The operation result. + """ + return self.result.get(key, default) + + def __getitem__(self, key: str) -> Any: + return self.result[key] diff --git a/src/sr_harness/evaluator/__init__.py b/src/sr_harness/evaluator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..43d7703d28fece486fc4121dcb4756b3a0f65e88 --- /dev/null +++ b/src/sr_harness/evaluator/__init__.py @@ -0,0 +1,17 @@ +"""Evaluator contracts, implementations, loading, and reusable utilities.""" +from . import utils +from .default_evaluator import ContextSplits, DefaultEvaluator, MetricDict, MetricValue +from .delay_rollout_evaluator import DelayRolloutEvaluator +from .graph_evaluator import GraphEvaluator +from .load_custom_evaluator import load_custom_evaluator + +__all__ = [ + "ContextSplits", + "DefaultEvaluator", + "DelayRolloutEvaluator", + "GraphEvaluator", + "load_custom_evaluator", + "MetricDict", + "MetricValue", + "utils", +] diff --git a/src/sr_harness/evaluator/default_evaluator.py b/src/sr_harness/evaluator/default_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..63046ac83453065f8551702d845eb40b72163c21 --- /dev/null +++ b/src/sr_harness/evaluator/default_evaluator.py @@ -0,0 +1,90 @@ +"""Default evaluation protocol for ordinary aligned data.""" +from __future__ import annotations + +from typing import Literal, TypeAlias + +import sr_harness_engine as engine + +from ..core import AgentContext +from . import utils + +MetricValue: TypeAlias = float | int +MetricDict: TypeAlias = dict[str, MetricValue] +ContextSplits: TypeAlias = dict[Literal["train", "validation"], AgentContext] + + +class DefaultEvaluator: + """Default implementation and extension point for formula evaluation.""" + + @classmethod + def split(cls, context: AgentContext) -> ContextSplits: + """Split a context into training and validation views. + + Args: + context: Complete unsplit agent context. + + Returns: + Training and validation contexts keyed by split name. + """ + return utils.split_aligned_context(context) + + @classmethod + def fit(cls, f: engine.Expression, y: engine.Expression, context: AgentContext) -> engine.Expression: + """Fit parameters in a general expression equality. + + Args: + f: Expression whose parameters will be fitted. + y: Expression providing target values. + context: Training context containing all referenced variables. + + Returns: + A copy of ``f`` with fitted parameter values. + """ + target = engine.evaluate(y, context.data) + return engine.fit(f, context.data, target).expression + + @classmethod + def evaluate(cls, f: engine.Expression, y: engine.Expression, context: AgentContext) -> MetricDict: + """Evaluate a general expression equality. + + Args: + f: Fitted expression to evaluate. + y: Expression providing target values. + context: Context containing all referenced variables. + + Returns: + Numeric regression and complexity metrics. + """ + target = engine.evaluate(y, context.data) + prediction = engine.evaluate(f, context.data) + return utils.regression_metrics(f, target, prediction) + + @classmethod + def fit_candidate(cls, f: engine.Expression, context: AgentContext) -> engine.Expression: + """Fit an eligible candidate against the configured target variable. + + Args: + f: Candidate expression whose parameters will be fitted. + context: Training context with a configured target. + + Returns: + A copy of ``f`` with fitted parameter values. + """ + if context.target is None: + raise ValueError("context.target must be configured before fitting a candidate") + return cls.fit(f, engine.Symbol(context.target), context) + + @classmethod + def evaluate_candidate(cls, f: engine.Expression, context: AgentContext) -> MetricDict: + """Evaluate an eligible candidate against the configured target. + + Args: + f: Fitted candidate expression. + context: Context with a configured target. + + Returns: + Numeric regression and complexity metrics. + """ + if context.target is None: + raise ValueError("context.target must be configured before evaluating a candidate") + return cls.evaluate(f, engine.Symbol(context.target), context) diff --git a/src/sr_harness/evaluator/delay_rollout_evaluator.py b/src/sr_harness/evaluator/delay_rollout_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..5231100727e6e676de61b1f4845e1f30f17bcb2b --- /dev/null +++ b/src/sr_harness/evaluator/delay_rollout_evaluator.py @@ -0,0 +1,95 @@ +"""Evaluator for scalar autonomous delay differential equations.""" +from __future__ import annotations + +import re + +import numpy as np + +import sr_harness_engine as engine + +from ..core import AgentContext +from . import utils +from .default_evaluator import ContextSplits, DefaultEvaluator, MetricDict + + +class DelayRolloutEvaluator(DefaultEvaluator): + """Rank derivative expressions by a free DDE trajectory rollout. + + The evaluator infers the observed state from derivative target names such + as ``dfdt`` and fits one constant pre-observation history value. Both split + labels intentionally retain the full ordered trajectory: a DDE rollout is + a trajectory-reconstruction score, not an exchangeable row prediction. + """ + + @classmethod + def split(cls, context: AgentContext) -> ContextSplits: + """Return full chronological trajectories for fitting and scoring.""" + return { + "train": context.with_data(context.data), + "validation": context.with_data(context.data), + } + + @staticmethod + def _time_and_state(context: AgentContext) -> tuple[str, str]: + axes = context.axis_names() + if not axes: + raise ValueError("DelayRolloutEvaluator requires a one-dimensional time axis") + time = next((name for name in axes if name.lower() in {"t", "time"}), axes[0]) + target = context.target or "" + normalized = re.sub(r"[^a-z0-9]", "", target.lower()) + features = context.feature_names() + state = next( + ( + name for name in features + if normalized in {f"d{re.sub(r'[^a-z0-9]', '', name.lower())}dt", f"{re.sub(r'[^a-z0-9]', '', name.lower())}dot"} + ), + None, + ) + if state is None: + candidates = [ + name for name in features + if np.asarray(context.data[name]).ndim == 1 + and np.asarray(context.data[name]).shape == np.asarray(context.data[time]).shape + and name.lower() not in {"time", "time_value", "timestamp"} + ] + if len(candidates) != 1: + raise ValueError( + "Could not infer one state variable; use a derivative target like dfdt with state f" + ) + state = candidates[0] + return time, state + + @classmethod + def fit_candidate(cls, f: engine.Expression, context: AgentContext) -> engine.Expression: + """Fit symbolic coefficients using time-aware pointwise derivative data.""" + if context.target is None: + raise ValueError("context.target must be configured before fitting a candidate") + time, _state = cls._time_and_state(context) + target = np.asarray(context.data[context.target], dtype=float) + return engine.fit( + f, context.data, target, time=context.data[time], + ).expression + + @classmethod + def evaluate_candidate(cls, f: engine.Expression, context: AgentContext) -> MetricDict: + """Return pointwise metrics plus free-rollout linear and log errors.""" + if context.target is None: + raise ValueError("context.target must be configured before evaluating a candidate") + time, state = cls._time_and_state(context) + target = np.asarray(context.data[context.target], dtype=float) + pointwise = np.asarray( + engine.evaluate(f, context.data, time=context.data[time]), dtype=float, + ) + finite = np.isfinite(target) & np.isfinite(pointwise) + if not np.any(finite): + raise ValueError("candidate has no finite pointwise derivative predictions") + metrics = utils.regression_metrics(f, target[finite], pointwise[finite]) + history, rollout, log_rmse = utils.fit_constant_DDE_history( + f, context, time=time, state=state, + ) + metrics.update({ + "rollout_rmse": utils.calc_RMSE(context.data[state], rollout), + "rollout_log_rmse": log_rmse, + "history_value": history, + }) + return metrics diff --git a/src/sr_harness/evaluator/graph_evaluator.py b/src/sr_harness/evaluator/graph_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..80d4e97fad87007f08acb7cc695290be4a08f2ac --- /dev/null +++ b/src/sr_harness/evaluator/graph_evaluator.py @@ -0,0 +1,99 @@ +"""Evaluator for broadcast-compatible graph and hypergraph arrays.""" +from __future__ import annotations + +import numpy as np + +import sr_harness_engine as engine + +from ..core import AgentContext +from . import utils +from .default_evaluator import ContextSplits, DefaultEvaluator, MetricDict + + +class GraphEvaluator(DefaultEvaluator): + """Evaluate variables with ``(..., N/E/H)`` graph-aligned dimensions.""" + + @classmethod + def fit(cls, f: engine.Expression, y: engine.Expression, context: AgentContext) -> engine.Expression: + """Fit an equality using graph-aware broadcast evaluation. + + Args: + f: Expression whose parameters will be fitted. + y: Expression providing graph-aligned target values. + context: Training context containing relation metadata. + + Returns: + A copy of ``f`` with fitted parameter values. + """ + target = engine.evaluate(y, context.data, num_nodes=context.num_nodes) + return engine.fit(f, context.data, target, num_nodes=context.num_nodes).expression + + @classmethod + def evaluate(cls, f: engine.Expression, y: engine.Expression, context: AgentContext) -> MetricDict: + """Evaluate an equality using graph-aware broadcast evaluation. + + Args: + f: Fitted expression to evaluate. + y: Expression providing graph-aligned target values. + context: Context containing relation metadata. + + Returns: + Numeric regression and complexity metrics. + """ + target = engine.evaluate(y, context.data, num_nodes=context.num_nodes) + prediction = engine.evaluate(f, context.data, num_nodes=context.num_nodes) + return utils.regression_metrics(f, target, prediction) + + @classmethod + def split(cls, context: AgentContext) -> ContextSplits: + """Split sample-aligned graph data without slicing relation arrays. + + Args: + context: Complete graph or hypergraph context. + + Returns: + Training and validation context views. + """ + data = context.data + target = np.asarray(data[context.target]) + if target.ndim < 2: + raise ValueError(f"target variable {context.target!r} must have at least 2 dimensions for graph evaluation") + n_samples = target.shape[0] + n_evaluation = int(round(n_samples * context.args.validation_fraction)) + n_train = n_samples - n_evaluation + if n_train <= 0 or n_evaluation <= 0: + return {"train": context.with_data(data), "validation": context.with_data(data)} + if context.args.split_by == "random": + train_indices, validation_indices = utils.select_random_indices( + seed=context.args.split_random_state, n_samples=n_samples, n_train=n_train + ) + elif context.args.split_by == "ood": + split_name = context.args.split_ood_variable + if not split_name or split_name not in data: + raise ValueError(f"split_ood_variable {split_name!r} not found in context.data") + train_indices, validation_indices = utils.select_OOD_indices( + seed=context.args.split_random_state, n_samples=n_samples, n_train=n_train, value=data[split_name] + ) + else: + raise ValueError(f"invalid split_by value: {context.args.split_by}") + + relation_names = context.relation_names + target_axes = context.variable_axes.get(context.target, ()) + sample_axis = target_axes[0] if target_axes else None + + def select(indices: np.ndarray) -> dict[str, np.ndarray]: + selected = {} + for variable, value in data.items(): + axes = context.variable_axes.get(variable, ()) + sample_aligned = variable not in relation_names and ( + variable == sample_axis + or bool(axes and axes[0] == sample_axis) + or (not axes and value.ndim > 1 and value.shape[0] == n_samples) + ) + selected[variable] = value[indices] if sample_aligned else value + return selected + + return { + "train": context.with_data(select(train_indices)), + "validation": context.with_data(select(validation_indices)), + } diff --git a/src/sr_harness/evaluator/load_custom_evaluator.py b/src/sr_harness/evaluator/load_custom_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..6ef2ffb97c46944e59d6c0141494d82352bc738e --- /dev/null +++ b/src/sr_harness/evaluator/load_custom_evaluator.py @@ -0,0 +1,166 @@ +"""Load built-in and user-authored evaluator implementations.""" + +from __future__ import annotations + +import re +from collections import OrderedDict +from pathlib import Path +from typing import TYPE_CHECKING + +from .default_evaluator import DefaultEvaluator +from .delay_rollout_evaluator import DelayRolloutEvaluator +from .graph_evaluator import GraphEvaluator +from .sandboxed_evaluator import create_sandboxed_evaluator + +if TYPE_CHECKING: + from ..runtime.workspace import Workspace + +EVALUATOR_DIRECTORY = Path(__file__).resolve().parent +CUSTOM_TEMPLATE = ( + '"""Custom evaluator."""\n' + "from .default_evaluator import DefaultEvaluator\n\n\n" + "class CustomEvaluator(DefaultEvaluator):\n" + " pass\n" +) +BUILTIN_EVALUATORS = OrderedDict( + ( + ( + "default", + { + "label": "DefaultEvaluator(默认评测)", + "label_en": "DefaultEvaluator (default)", + "class": DefaultEvaluator, + "filename": "default_evaluator.py", + }, + ), + ( + "delay_rollout", + { + "label": "DelayRolloutEvaluator(延迟方程轨迹评测)", + "label_en": "DelayRolloutEvaluator (DDE trajectory rollout)", + "class": DelayRolloutEvaluator, + "filename": "delay_rollout_evaluator.py", + }, + ), + ( + "graph", + { + "label": "GraphEvaluator(图与超图)", + "label_en": "GraphEvaluator (graph/hypergraph)", + "class": GraphEvaluator, + "filename": "graph_evaluator.py", + }, + ), + ) +) +BUILTIN_EVALUATOR_CLASS_NAMES = { + DefaultEvaluator.__name__, DelayRolloutEvaluator.__name__, GraphEvaluator.__name__, +} + + +def evaluator_source(evaluator_id: str) -> str: + """Read the source of a built-in evaluator. + + Args: + evaluator_id: Built-in evaluator identifier. + + Returns: + UTF-8 Python source for the evaluator. + + Raises: + ValueError: If ``evaluator_id`` is unknown. + """ + try: + filename = BUILTIN_EVALUATORS[evaluator_id]["filename"] + except KeyError as exc: + raise ValueError(f"Unknown evaluator: {evaluator_id}") from exc + return (EVALUATOR_DIRECTORY / filename).read_text(encoding="utf-8") + + +def evaluator_catalog() -> list[dict[str, str]]: + """Return serializable metadata and source for built-in evaluators.""" + return [ + { + "id": evaluator_id, + "label": item["label"], + "label_en": item["label_en"], + "source": evaluator_source(evaluator_id), + "abstract": False, + } + for evaluator_id, item in BUILTIN_EVALUATORS.items() + ] + + +def create_builtin_evaluator(evaluator_id: str) -> DefaultEvaluator: + """Instantiate a built-in evaluator. + + Args: + evaluator_id: Built-in evaluator identifier. + + Returns: + A new evaluator instance. + + Raises: + ValueError: If ``evaluator_id`` is unknown. + """ + try: + return BUILTIN_EVALUATORS[evaluator_id]["class"]() + except KeyError as exc: + raise ValueError(f"Unknown evaluator: {evaluator_id}") from exc + + +def evaluator_filename(class_name: str) -> str: + """Convert an evaluator class name to a snake-case Python filename. + + Args: + class_name: Evaluator class name. + + Returns: + Filename ending in ``.py``. + """ + stem = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1_\2", class_name) + stem = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", stem).lower() + return f"{stem}.py" + + +def load_custom_evaluator( + source: str | None = None, + file: Path | None = None, + *, + workspace: Workspace | None = None, +) -> DefaultEvaluator: + """Load exactly one evaluator subclass as a virtual package module. + + Args: + source: Python source defining one ``DefaultEvaluator`` subclass. + file: Optional source file. Its contents are used when ``source`` is + omitted and its path is retained for provenance. + workspace: Workspace enforcing safe reads, when available. + + Returns: + An instantiated custom evaluator with ``CUSTOM_EVALUATOR`` provenance. + + Raises: + ValueError: If the source is unsafe, invalid, or does not define exactly + one loadable evaluator subclass. + """ + origin = Path(file).expanduser() if file is not None else None + if source is None: + if origin is None: + raise ValueError("source or file must be provided") + try: + opener = workspace.safe_open if workspace is not None else open + with opener(origin, "r", encoding="utf-8") as f: + source = f.read() + except OSError as exc: + raise ValueError(f"Could not read custom evaluator: {exc}") from exc + if not isinstance(source, str) or not source.strip(): + raise ValueError("Custom evaluator source must not be empty") + if len(source) > 50_000: + raise ValueError("Custom evaluator source exceeds 50000 characters") + try: + return create_sandboxed_evaluator(source, origin) + except Exception as exc: + if "SyntaxError:" in str(exc): + raise ValueError(f"Invalid evaluator syntax: {exc}") from exc + raise ValueError(f"Could not load custom evaluator: {exc}") from exc diff --git a/src/sr_harness/evaluator/sandboxed_evaluator.py b/src/sr_harness/evaluator/sandboxed_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..ebedd3017e4f575c0ea3ad9bf345d65f16e288bb --- /dev/null +++ b/src/sr_harness/evaluator/sandboxed_evaluator.py @@ -0,0 +1,174 @@ +"""Proxy custom evaluator calls into the data-only OS sandbox.""" + +from __future__ import annotations + +from functools import lru_cache +from pathlib import Path +from typing import Any + +import sr_harness_engine as engine + +from ..core import AgentContext +from ..runtime.sandbox import _context_array_snapshot, _run_sandbox_protocol +from ..runtime.sandbox_context import sandbox_arguments +from .default_evaluator import DefaultEvaluator, MetricDict + + +def _context_payload(context: AgentContext) -> dict[str, Any]: + return { + "args": sandbox_arguments(context.args), + "target": context.target, + "variable_descriptions": context.variable_descriptions, + "variable_axes": {name: list(axes) for name, axes in context.variable_axes.items()}, + "variable_structures": context.variable_structures, + "relation_names": sorted(context.relation_names), + "num_nodes": context.num_nodes, + } + + +class SandboxedCustomEvaluator(DefaultEvaluator): + """DefaultEvaluator-compatible proxy whose implementation runs out of process.""" + + CUSTOM_EVALUATOR: dict[str, Any] + SANDBOX_SOURCE: str + SANDBOX_FILENAME: str + + @classmethod + def _request( + cls, + action: str, + context: AgentContext | None = None, + *, + f: engine.Expression | None = None, + y: engine.Expression | None = None, + candidate: bool = False, + ): + request: dict[str, Any] = { + "action": action, + "source": cls.SANDBOX_SOURCE, + "filename": cls.SANDBOX_FILENAME, + } + array_snapshot = None + if context is not None: + request["context"] = _context_payload(context) + array_snapshot = _context_array_snapshot(context) + if f is not None: + request["f"] = f.to_str(number_format=".17g") + if y is not None: + request["y"] = y.to_str(number_format=".17g") + request["candidate"] = candidate + return _run_sandbox_protocol( + operation="evaluator", + request=request, + array_snapshot=array_snapshot, + timeout_seconds=120, + memory_limit_mb=4096, + output_limit_bytes=64 * 1024, + ) + + @classmethod + def split(cls, context: AgentContext): + """Split context data in the isolated evaluator process.""" + result = cls._request("split", context) + if set(result.arrays) != {"train", "validation"}: + raise ValueError("Custom evaluator split() must return train and validation data") + return {name: context.with_data(data) for name, data in result.arrays.items()} + + @classmethod + def fit( + cls, f: engine.Expression, y: engine.Expression, context: AgentContext + ) -> engine.Expression: + """Fit a general equality in the isolated evaluator process.""" + result = cls._request("fit", context, f=f, y=y) + return engine.parse(str(result.payload["expression"])) + + @classmethod + def evaluate( + cls, f: engine.Expression, y: engine.Expression, context: AgentContext + ) -> MetricDict: + """Evaluate a general equality in the isolated evaluator process.""" + result = cls._request("evaluate", context, f=f, y=y) + return dict(result.payload["metrics"]) + + @classmethod + def fit_candidate(cls, f: engine.Expression, context: AgentContext) -> engine.Expression: + """Fit a candidate in the isolated evaluator process.""" + result = cls._request("fit", context, f=f, candidate=True) + return engine.parse(str(result.payload["expression"])) + + @classmethod + def evaluate_candidate(cls, f: engine.Expression, context: AgentContext) -> MetricDict: + """Evaluate a candidate in the isolated evaluator process.""" + result = cls._request("evaluate", context, f=f, candidate=True) + return dict(result.payload["metrics"]) + + @classmethod + def _evaluate_formula_isolated( + cls, + f: engine.Expression, + y: engine.Expression, + context: AgentContext, + *, + fit: bool, + candidate: bool, + ) -> tuple[engine.Expression, dict[str, MetricDict], dict[str, AgentContext]]: + """Run split, optional fit, and both evaluations in one sandbox call.""" + request = { + "action": "evaluate-formula", + "source": cls.SANDBOX_SOURCE, + "filename": cls.SANDBOX_FILENAME, + "context": _context_payload(context), + "f": f.to_str(number_format=".17g"), + "y": y.to_str(number_format=".17g"), + "fit": fit, + "candidate": candidate, + } + result = _run_sandbox_protocol( + operation="evaluator", + request=request, + arrays={"context": context.data}, + timeout_seconds=120, + memory_limit_mb=4096, + output_limit_bytes=64 * 1024, + ) + split_contexts = {name: context.with_data(data) for name, data in result.arrays.items()} + return ( + engine.parse(str(result.payload["expression"])), + {name: dict(values) for name, values in result.payload["metrics"].items()}, + split_contexts, + ) + + +@lru_cache(maxsize=128) +def _inspect_source(source: str, filename: str) -> tuple[str, tuple[tuple[str, Any], ...]]: + """Inspect immutable evaluator source once per process.""" + result = _run_sandbox_protocol( + operation="evaluator", + request={"action": "inspect", "source": source, "filename": filename}, + timeout_seconds=30, + memory_limit_mb=2048, + output_limit_bytes=64 * 1024, + ) + return ( + str(result.payload["class_name"]), + tuple(sorted(dict(result.payload.get("class_attributes", {})).items())), + ) + + +def create_sandboxed_evaluator(source: str, file: Path | None = None) -> DefaultEvaluator: + """Validate source in the sandbox and return a named proxy instance.""" + filename = file.name if file is not None else "custom_evaluator.py" + class_name, class_attributes = _inspect_source(source, filename) + module_name = f"sr_harness.evaluator.{Path(filename).stem}" + proxy_class = type( + class_name, + (SandboxedCustomEvaluator,), + { + **dict(class_attributes), + "__module__": module_name, + "CUSTOM_EVALUATOR": {"source": source, "file": file}, + "SANDBOX_SOURCE": source, + "SANDBOX_FILENAME": filename, + }, + ) + return proxy_class() diff --git a/src/sr_harness/evaluator/utils/__init__.py b/src/sr_harness/evaluator/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..96c120880cb36c34e531500ea86c809188f0767c --- /dev/null +++ b/src/sr_harness/evaluator/utils/__init__.py @@ -0,0 +1,483 @@ +"""Reusable evaluator infrastructure kept outside evaluator contracts.""" +from __future__ import annotations + +import warnings +from typing import TYPE_CHECKING, Any + +import numpy as np +from scipy import stats +from scipy.integrate import solve_ivp +from scipy.optimize import minimize_scalar + +import sr_harness_engine as engine + +if TYPE_CHECKING: + from ...core import AgentContext + + +def _regression_arrays(y_true: Any, y_pred: Any) -> tuple[np.ndarray, np.ndarray]: + try: + y_pred, y_true = np.broadcast_arrays(np.asarray(y_pred), np.asarray(y_true)) + except ValueError as exc: + raise ValueError( + f"Prediction shape {np.shape(y_pred)} and target shape {np.shape(y_true)} " + "cannot be broadcast to a common shape." + ) from exc + return y_true.astype(float, copy=False).reshape(-1), y_pred.astype(float, copy=False).reshape(-1) + + +def calc_MSE(y_true: Any, y_pred: Any) -> float: + """Calculate mean squared error. + + Args: + y_true: Target values. + y_pred: Predicted values broadcastable to ``y_true``. + + Returns: + Mean squared error over flattened broadcast arrays. + """ + y_true, y_pred = _regression_arrays(y_true, y_pred) + return float(np.mean((y_pred - y_true) ** 2)) + + +def calc_RMSE(y_true: Any, y_pred: Any) -> float: + """Calculate root mean squared error. + + Args: + y_true: Target values. + y_pred: Predicted values broadcastable to ``y_true``. + + Returns: + Root mean squared error. + """ + return float(np.sqrt(calc_MSE(y_true, y_pred))) + + +def calc_MAE(y_true: Any, y_pred: Any) -> float: + """Calculate mean absolute error. + + Args: + y_true: Target values. + y_pred: Predicted values broadcastable to ``y_true``. + + Returns: + Mean absolute error. + """ + y_true, y_pred = _regression_arrays(y_true, y_pred) + return float(np.mean(np.abs(y_pred - y_true))) + + +def calc_MAPE(y_true: Any, y_pred: Any) -> float: + """Calculate mean absolute percentage error over nonzero targets. + + Args: + y_true: Target values. + y_pred: Predicted values broadcastable to ``y_true``. + + Returns: + Mean absolute percentage error, or NaN when every target is zero. + """ + y_true, y_pred = _regression_arrays(y_true, y_pred) + nonzero = y_true != 0 + if not np.any(nonzero): + return float("nan") + return float(np.mean(np.abs((y_pred[nonzero] - y_true[nonzero]) / y_true[nonzero]))) + + +def calc_R2(y_true: Any, y_pred: Any) -> float: + """Calculate the coefficient of determination. + + Args: + y_true: Target values. + y_pred: Predicted values broadcastable to ``y_true``. + + Returns: + The R-squared score. + """ + y_true, y_pred = _regression_arrays(y_true, y_pred) + residual = float(np.sum((y_pred - y_true) ** 2)) + total = float(np.sum((y_true - np.mean(y_true)) ** 2)) + return float(1 - residual / total) if total else (1.0 if residual == 0 else float("-inf")) + + +def calc_AIC(y_true: Any, y_pred: Any, num_parameters: int) -> float: + """Calculate the Gaussian Akaike information criterion. + + Args: + y_true: Target values. + y_pred: Predicted values broadcastable to ``y_true``. + num_parameters: Number of fitted parameters. + + Returns: + AIC value, negative infinity for an exact fit, or NaN for invalid loss. + """ + y_true, y_pred = _regression_arrays(y_true, y_pred) + ss_res = float(np.sum((y_pred - y_true) ** 2)) + if np.isfinite(ss_res) and ss_res > 0: + n = int(y_true.size) + likelihood = -n / 2 * (np.log(2 * np.pi) + np.log(ss_res / n) + 1) + return float(2 * num_parameters - 2 * likelihood) + return float("-inf") if ss_res == 0 else float("nan") + + +def calc_BIC(y_true: Any, y_pred: Any, num_parameters: int) -> float: + """Calculate the Gaussian Bayesian information criterion. + + Args: + y_true: Target values. + y_pred: Predicted values broadcastable to ``y_true``. + num_parameters: Number of fitted parameters. + + Returns: + BIC value, negative infinity for an exact fit, or NaN for invalid loss. + """ + y_true, y_pred = _regression_arrays(y_true, y_pred) + ss_res = float(np.sum((y_pred - y_true) ** 2)) + if np.isfinite(ss_res) and ss_res > 0: + n = int(y_true.size) + likelihood = -n / 2 * (np.log(2 * np.pi) + np.log(ss_res / n) + 1) + return float(num_parameters * np.log(n) - 2 * likelihood) + return float("-inf") if ss_res == 0 else float("nan") + + +def calc_PearsonR(y_true: Any, y_pred: Any) -> float: + """Calculate Pearson's correlation coefficient over finite pairs. + + Args: + y_true: Target values. + y_pred: Predicted values broadcastable to ``y_true``. + + Returns: + Pearson correlation, or NaN when fewer than two finite pairs exist. + """ + y_true, y_pred = _regression_arrays(y_true, y_pred) + finite = np.isfinite(y_true) & np.isfinite(y_pred) + if np.count_nonzero(finite) < 2: + return float("nan") + with np.errstate(invalid="ignore", divide="ignore"), warnings.catch_warnings(): + warnings.simplefilter("ignore") + return float(np.corrcoef(y_true[finite], y_pred[finite])[0, 1]) + + +def calc_SpearmanR(y_true: Any, y_pred: Any) -> float: + """Calculate Spearman's rank correlation over finite pairs. + + Args: + y_true: Target values. + y_pred: Predicted values broadcastable to ``y_true``. + + Returns: + Spearman correlation, or NaN when fewer than two finite pairs exist. + """ + y_true, y_pred = _regression_arrays(y_true, y_pred) + finite = np.isfinite(y_true) & np.isfinite(y_pred) + if np.count_nonzero(finite) < 2: + return float("nan") + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return float(stats.spearmanr(y_true[finite], y_pred[finite]).statistic) + + +def calc_complexity(expression: engine.Expression) -> int: + """Count nodes in a symbolic expression. + + Args: + expression: Symbolic expression to inspect. + + Returns: + Expression node count. + """ + return len(expression) + + +def regression_metrics(expression: engine.Expression, y_true: Any, y_pred: Any) -> dict[str, float | int]: + """Calculate the standard regression metric bundle. + + Args: + expression: Fitted expression used for complexity and parameter counts. + y_true: Target values. + y_pred: Predicted values. + + Returns: + Numeric prediction, information-criterion, correlation, and complexity metrics. + """ + parameters = engine.count_parameters(expression) + return { + "mse": calc_MSE(y_true, y_pred), "rmse": calc_RMSE(y_true, y_pred), + "mae": calc_MAE(y_true, y_pred), "mape": calc_MAPE(y_true, y_pred), + "r2": calc_R2(y_true, y_pred), "aic": calc_AIC(y_true, y_pred, parameters), + "bic": calc_BIC(y_true, y_pred, parameters), + "pearson_r": calc_PearsonR(y_true, y_pred), + "spearman_r": calc_SpearmanR(y_true, y_pred), + "complexity": calc_complexity(expression), + } + + +def select_random_indices(*, seed: int, n_samples: int, n_train: int) -> tuple[np.ndarray, np.ndarray]: + """Select reproducible random training and validation indices. + + Args: + seed: Random seed. + n_samples: Total sample count. + n_train: Number of training samples. + + Returns: + Training and validation index arrays. + """ + indices = np.random.RandomState(seed).permutation(n_samples) + return indices[:n_train], indices[n_train:] + + +def select_OOD_indices(*, seed: int, n_samples: int, n_train: int, value: Any) -> tuple[np.ndarray, np.ndarray]: + """Select an ordered out-of-distribution split. + + Args: + seed: Seed used to break ties reproducibly. + n_samples: Total sample count. + n_train: Number of low-ranked training samples. + value: One-dimensional ordering variable. + + Returns: + Training and validation index arrays. + """ + value = np.asarray(value) + if value.ndim != 1 or len(value) != n_samples: + raise ValueError("split_ood_variable must have shape (N,)") + shuffled = np.random.RandomState(seed).permutation(n_samples) + ordered = shuffled[np.argsort(value[shuffled], kind="stable")] + return ordered[:n_train], ordered[n_train:] + + +def split_indices(context: AgentContext, *, chronological: bool = False) -> tuple[np.ndarray, np.ndarray] | None: + """Select split indices according to evaluator arguments. + + Args: + context: Unsplit agent context. + chronological: Whether to preserve input order rather than use configured + random or OOD splitting. + + Returns: + Training and validation indices, or ``None`` when splitting is disabled. + """ + n_samples = len(context.data[context.target]) + n_validation = int(round(n_samples * context.args.validation_fraction)) + n_train = n_samples - n_validation + if n_train <= 0 or n_validation <= 0: + return None + if chronological: + indices = np.arange(n_samples) + return indices[:n_train], indices[n_train:] + if context.args.split_by == "random": + return select_random_indices(seed=context.args.split_random_state, n_samples=n_samples, n_train=n_train) + if context.args.split_by == "ood": + name = context.args.split_ood_variable + if not name: + raise ValueError("split_ood_variable is required when split_by='ood'") + if name not in context.data: + raise ValueError(f"split_ood_variable {name!r} not found in context.data") + return select_OOD_indices(seed=context.args.split_random_state, n_samples=n_samples, n_train=n_train, value=context.data[name]) + raise ValueError(f"invalid split_by value: {context.args.split_by}") + + +def split_aligned_context(context: AgentContext, *, chronological: bool = False) -> dict[str, AgentContext]: + """Split every aligned context array along its leading dimension. + + Args: + context: Unsplit agent context. + chronological: Whether to preserve input order. + + Returns: + Training and validation context views. + """ + indices = split_indices(context, chronological=chronological) + if indices is None: + return {"train": context.with_data(context.data), "validation": context.with_data(context.data)} + train_indices, validation_indices = indices + return { + "train": context.with_data({name: value[train_indices] for name, value in context.data.items()}), + "validation": context.with_data({name: value[validation_indices] for name, value in context.data.items()}), + } + + +def integrate_ODE(f: engine.Expression, context: AgentContext, *, time: str = "t", state: str = "x") -> np.ndarray: + """Integrate a one-dimensional ODE over observed sample times. + + Args: + f: Fitted derivative expression. + context: Context containing time and observed state arrays. + time: Time-variable name. + state: State-variable name. + + Returns: + Integrated state values at the observed times. + """ + t = np.asarray(context.data[time], dtype=float) + observed = np.asarray(context.data[state], dtype=float) + if t.ndim != 1 or observed.ndim != 1 or t.shape != observed.shape: + raise ValueError("time and state must be equally shaped one-dimensional arrays") + if len(t) < 2 or np.any(np.diff(t) <= 0): + raise ValueError("time must contain at least two strictly increasing values") + + def rhs(current_time: float, current_state: np.ndarray) -> np.ndarray: + value = engine.evaluate(f, {time: np.asarray([current_time]), state: np.asarray([current_state[0]])}) + return np.asarray([np.asarray(value, dtype=float).reshape(-1)[0]]) + + solution = solve_ivp(rhs, (float(t[0]), float(t[-1])), [float(observed[0])], t_eval=t, rtol=1e-8, atol=1e-10) + if not solution.success or solution.y.shape != (1, len(t)): + raise RuntimeError(f"ODE integration failed: {solution.message}") + return solution.y[0] + + +def calc_trajectory_rollout_RMSE(f: engine.Expression, context: AgentContext, *, time: str = "t", state: str = "x") -> float: + """Calculate trajectory RMSE after integrating a derivative expression. + + Args: + f: Fitted derivative expression. + context: Context containing time and observed state arrays. + time: Time-variable name. + state: State-variable name. + + Returns: + RMSE between observed and integrated state trajectories. + """ + return calc_RMSE(context.data[state], integrate_ODE(f, context, time=time, state=state)) + + +def integrate_DDE( + f: engine.Expression, + context: AgentContext, + *, + time: str = "t", + state: str = "x", + history_value: float = 0.0, + max_step: float | None = None, +) -> np.ndarray: + """Integrate a scalar autonomous delay differential equation. + + ``delay(state, lag)`` is resolved from the computed trajectory, using a + constant history before the first observed time. A fixed-step RK4 method + keeps the delayed lookup causal. + """ + t_eval = np.asarray(context.data[time], dtype=float) + observed = np.asarray(context.data[state], dtype=float) + if t_eval.ndim != 1 or observed.ndim != 1 or t_eval.shape != observed.shape: + raise ValueError("time and state must be equally shaped one-dimensional arrays") + if len(t_eval) < 2 or np.any(np.diff(t_eval) <= 0): + raise ValueError("time must contain at least two strictly increasing values") + default_step = float(np.min(np.diff(t_eval))) + step_limit = default_step if max_step is None else min(default_step, float(max_step)) + if not np.isfinite(step_limit) or step_limit <= 0: + raise ValueError("max_step must be positive and finite") + + times = [float(t_eval[0])] + states = [float(observed[0])] + + def rhs(current_time: float, current_state: float) -> float: + def resolve_delay(_value: np.ndarray, lag: np.ndarray, _time: np.ndarray | None) -> np.ndarray: + lag_value = float(np.asarray(lag, dtype=float).reshape(-1)[0]) + if not np.isfinite(lag_value) or lag_value <= 0: + raise ValueError("DDE rollout requires every delay lag to be positive and finite") + query = current_time - lag_value + if query < times[0]: + delayed = float(history_value) + elif query > times[-1] + 1e-12: + raise ValueError("delay lag is shorter than the DDE integration step") + else: + delayed = float(np.interp(query, times, states)) + return np.asarray([delayed]) + + values = { + name: np.asarray([ + current_state if name == state else np.interp(current_time, t_eval, value) + ]) + for name, value in context.data.items() + if name != context.target and np.asarray(value).ndim == 1 and len(value) == len(t_eval) + } + values[state] = np.asarray([current_state]) + value = engine.evaluate( + f, values, time=np.asarray([current_time]), delay_resolver=resolve_delay, + ) + result = float(np.asarray(value, dtype=float).reshape(-1)[0]) + if not np.isfinite(result): + raise FloatingPointError("DDE right-hand side returned a non-finite value") + return result + + for target_time in t_eval[1:]: + while times[-1] < float(target_time) - 1e-14: + current_time = times[-1] + current_state = states[-1] + step = min(step_limit, float(target_time) - current_time) + k1 = rhs(current_time, current_state) + k2 = rhs(current_time + step / 2, current_state + step * k1 / 2) + k3 = rhs(current_time + step / 2, current_state + step * k2 / 2) + k4 = rhs(current_time + step, current_state + step * k3) + next_state = current_state + step * (k1 + 2 * k2 + 2 * k3 + k4) / 6 + if not np.isfinite(next_state) or abs(next_state) > 1e300: + raise FloatingPointError("DDE rollout diverged") + times.append(current_time + step) + states.append(float(next_state)) + return np.interp(t_eval, np.asarray(times), np.asarray(states)) + + +def fit_constant_DDE_history( + f: engine.Expression, + context: AgentContext, + *, + time: str = "t", + state: str = "x", + bounds: tuple[float, float] = (-1000.0, 1000.0), +) -> tuple[float, np.ndarray, float]: + """Fit one constant pre-observation history, then score a log rollout.""" + observed = np.asarray(context.data[state], dtype=float) + sample_time = np.asarray(context.data[time], dtype=float) + target = np.asarray(context.data[context.target], dtype=float) + if np.any(observed <= 0) or not np.all(np.isfinite(observed)): + raise ValueError("logarithmic DDE rollout scoring requires a positive finite state") + penalty = 1e100 + + def history_objective(history: float) -> float: + def resolve_delay(value: np.ndarray, lag: np.ndarray, evaluation_time: np.ndarray | None) -> np.ndarray: + value = np.asarray(value, dtype=float) + lag = np.asarray(lag, dtype=float) + current_time = sample_time if evaluation_time is None else np.asarray(evaluation_time, dtype=float) + query = current_time - lag + flat = value.reshape(value.shape[0], -1) + delayed = np.column_stack([ + np.interp(query, sample_time, column, left=float(history), right=np.nan) + for column in flat.T + ]) + return delayed.reshape(value.shape) + + try: + prediction = np.asarray( + engine.evaluate( + f, + context.data, + time=sample_time, + delay_resolver=resolve_delay, + ), + dtype=float, + ) + except (FloatingPointError, KeyError, TypeError, ValueError): + return penalty + finite = np.isfinite(prediction) & np.isfinite(target) + if not np.any(finite): + return penalty + nonzero = np.abs(target[finite]) + floor = max(float(np.median(nonzero[nonzero > 0])) * 1e-6, 1e-15) + scaled = (prediction[finite] - target[finite]) / np.maximum(nonzero, floor) + return float(np.mean(np.square(np.clip(scaled, -1e50, 1e50)))) + + lower, upper = map(float, bounds) + refined = minimize_scalar( + history_objective, + bounds=(lower, upper), + method="bounded", + options={"xatol": 1e-12, "maxiter": 200}, + ) + history = float(refined.x) + rollout = integrate_DDE(f, context, time=time, state=state, history_value=history) + if np.any(rollout <= 0) or not np.all(np.isfinite(rollout)): + return history, rollout, penalty + log_rmse = calc_RMSE(np.log10(observed), np.log10(rollout)) + return history, rollout, log_rmse diff --git a/src/sr_harness/parser/__init__.py b/src/sr_harness/parser/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..35167d8e3d47d4a173ac8fcf041a73031692db52 --- /dev/null +++ b/src/sr_harness/parser/__init__.py @@ -0,0 +1,15 @@ +""" +Parser 用一种自定义的方式处理工具调用: +1. 在初始化时,Parser 接受一个工具列表,获得每个工具的名称、描述和参数信息。 +2. Parser 提供一个方法,将所有工具的信息格式化成一个字符串,供 LLM 参考。其中包含样例的调用格式。 +3. Parser 提供一个方法,接受 LLM 的输出字符串,解析出 (零或一或若干个) 工具调用的名称和参数,并返回一个结构化的结果。 + +Parser 的设计初衷在于允许不支持 tool 参数的 API 也能使用工具调用的功能。 +""" +from .base_parser import BaseParser +from .text_parser import TextParser +from .json_parser import JSONParser +from .openai_parser import OpenAIParser +from .xml_parser import XMLParser + +__all__ = ["BaseParser", "TextParser", "JSONParser", "OpenAIParser", "XMLParser"] diff --git a/src/sr_harness/parser/base_parser.py b/src/sr_harness/parser/base_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..1f82c5862b6af7daf1c7e9b91ee0856fee52c46e --- /dev/null +++ b/src/sr_harness/parser/base_parser.py @@ -0,0 +1,80 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""工具调用解析器模块。 + +负责将工具列表格式化为 LLM 可读的描述,以及从 LLM 响应中解析工具调用。 +""" +from __future__ import annotations +from collections import Counter +from logging import getLogger +from abc import ABC, abstractmethod +from typing import List, Dict, Any +from ..core import ToolCall, ToolCallResult +from ..tools import BaseTool +from ..utils import FactoryMixin + +_logger = getLogger(f'sr_harness.{__name__}') + + +class BaseParser(ABC, FactoryMixin): + """Base class for model tool-call parsers.""" + + native_tool_calls = False + + def __init__(self, tool_list: list[BaseTool] | None = None) -> None: + """初始化工具解析器。 + + Args: + tool_list: Bound tool instances. ``None`` and an empty list both + expose no tools. + """ + self.tools = list(tool_list or []) + if invalid := [tool for tool in self.tools if not isinstance(tool, BaseTool)]: + invalid_names = [type(tool).__name__ for tool in invalid] + raise TypeError( + f"tool_list must contain only BaseTool instances; got {', '.join(invalid_names)}" + ) + name_counts = Counter(tool.metadata.name for tool in self.tools) + if duplicated := sorted(name for name, count in name_counts.items() if count > 1): + raise ValueError(f"tool_list contains duplicate tool names: {', '.join(duplicated)}") + self._tools_by_name = {tool.metadata.name: tool for tool in self.tools} + + def __getitem__(self, name: str) -> BaseTool: + """Return a bound tool by name, raising ``KeyError`` when absent.""" + return self._tools_by_name[name] + + @abstractmethod + def format_tools(self) -> str | List[Dict[str, Any]]: + """Format tools. + + Returns: + str: The operation result. + """ + pass + + @abstractmethod + def parse_response(self, response: Any) -> List[ToolCall]: + """Parse response. + + Args: + response: Provider response object. + + Returns: + List[ToolCall]: The operation result. + """ + pass + + def format_tool_result_messages(self, tool_calls: List[ToolCall], results: List[ToolCallResult]) -> List[Dict[str, Any]]: + """Format tool result messages. + + Args: + tool_calls: Tool calls returned by the model. + results: Result records to process. + + Returns: + List[Dict[str, Any]]: The operation result. + """ + lines = [] + for tool_call, result in zip(tool_calls, results): + lines.append(f"=== Results for `{tool_call.name}` with params `{tool_call.params}` ===") + lines.append(result.result_str) + return [{"role": "user", "content": "\n".join(lines)}] if lines else [] diff --git a/src/sr_harness/parser/json_parser.py b/src/sr_harness/parser/json_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..ab1da5d3f076bfb0fe0fca3968faa83bdf92f007 --- /dev/null +++ b/src/sr_harness/parser/json_parser.py @@ -0,0 +1,93 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +from __future__ import annotations +import re +import json +import inspect +from typing import List +from logging import getLogger +from ..core import ToolCall +from .base_parser import BaseParser + +_logger = getLogger(f'sr_harness.{__name__}') + + +@BaseParser.register('json') +class JSONParser(BaseParser): + """Parser for JSON-formatted tool calls.""" + + def format_tools(self) -> str: + """Format tools. + + Returns: + str: The operation result. + """ + lines = ["## Available Tools:", ""] + + for tool in self.tools: + name = tool.metadata.name + desc = tool.metadata.description + + # 获取工具类的签名 + try: + if (tool_cls := type(tool)): + sig = inspect.signature(tool_cls.execute) + params = [] + for param_name, param in sig.parameters.items(): + if param_name in ('self', 'args', 'kwargs'): + continue + param_type = param.annotation.__name__ if param.annotation != inspect.Parameter.empty else 'Any' + if param.default is inspect.Parameter.empty: + params.append(f'"{param_name}": {param_type}') + else: + params.append(f'"{param_name}": {param_type} = {param.default}') + signature = "{" + ", ".join(params) + "}" + else: + signature = "{}" + except Exception: + signature = "{}" + + lines.append(f"### {name}") + lines.append(f"- **Description**: {desc}") + lines.append(f"- **Params**: `{signature}`") + lines.append("") + + lines.append("## Output Format:") + lines.append("") + lines.append("Respond with a JSON object in the following format:") + lines.append("") + lines.append("```json") + lines.append('{"tool": "tool_name", "params": {"param1": "value1", "param2": "value2"}}') + lines.append("```") + lines.append("") + lines.append("You can include multiple tool call blocks in one response if needed.") + + return "\n".join(lines) + + def parse_response(self, response: str) -> List[ToolCall]: + """Parse response. + + Args: + response: Provider response object. + + Returns: + List[ToolCall]: The operation result. + """ + tool_calls = [] + + # 尝试从响应中提取 JSON + if (json_match := re.search(r'```(?:json)?\s*({.*?})\s*```', response, re.DOTALL)): + json_str = json_match.group(1) + else: + # 如果没有代码块标记,尝试直接解析整个响应 + json_str = response.strip() + + try: + data = json.loads(json_str) + except json.JSONDecodeError as e: + _logger.warning(f"Failed to parse JSON: {e}") + return tool_calls + + for action in data["actions"]: + tool_calls.append(ToolCall(name=action["tool"], params=action["params"], raw=json_str)) + + return tool_calls diff --git a/src/sr_harness/parser/openai_parser.py b/src/sr_harness/parser/openai_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..b05ee374577e7378bc0f7124e8ca91ffed56d73f --- /dev/null +++ b/src/sr_harness/parser/openai_parser.py @@ -0,0 +1,89 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +from __future__ import annotations +import json +from logging import getLogger +from typing import List, Dict, Any +from .base_parser import BaseParser +from ..core import ToolCall, ToolCallResult + +_logger = getLogger(f'sr_harness.{__name__}') + + +@BaseParser.register('openai') +class OpenAIParser(BaseParser): + """Parser for native OpenAI-compatible tool calls.""" + + native_tool_calls = True + + def format_tools(self) -> List[Dict[str, Any]]: + """Return OpenAI-compatible native function descriptions.""" + return [ + { + "type": "function", + "function": { + "name": tool.metadata.name, + "description": tool.metadata.description, + "parameters": tool.metadata.parameters, + }, + } + for tool in self.tools + ] + + def parse_response(self, response: Any) -> List[ToolCall]: + """Normalize provider-native function calls already extracted by BaseAPI.""" + normalized = [] + for tool_call in response or []: + if isinstance(tool_call, dict): + raw = tool_call + elif hasattr(tool_call, "to_dict"): + raw = tool_call.to_dict() + elif hasattr(tool_call, "model_dump"): + raw = tool_call.model_dump() + else: + raise ValueError(f"Unrecognized tool call format: {tool_call}") + function = raw.get("function") or {} + name = function.get("name") or raw.get("name") or None + params = ( + function.get("arguments") + or raw.get("arguments") + or raw.get("arguments_json") + or raw.get("args") + or {} + ) + try: + if isinstance(params, str): + params = json.loads(params) if params.strip() else {} + except json.JSONDecodeError as error: + _logger.warning(f"Skip malformed native tool call {raw!r}: {error}") + continue + normalized.append(ToolCall( + name=name, + params=params, + id=raw.get("id") or raw.get("call_id"), + raw=raw, + )) + return normalized + + def format_tool_result_messages( + self, + tool_calls: List[ToolCall], + results: List[ToolCallResult], + ) -> List[Dict[str, Any]]: + """Format tool result messages. + + Args: + tool_calls: Tool calls returned by the model. + results: Result records to process. + + Returns: + List[Dict[str, Any]]: The operation result. + """ + messages = [] + for tool_call, result in zip(tool_calls, results): + messages.append({ + "role": "tool", + "tool_call_id": tool_call.id, + "name": tool_call.name, + "content": result.result_str, + }) + return messages diff --git a/src/sr_harness/parser/text_parser.py b/src/sr_harness/parser/text_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..9221b521d69e5cd02240513ff92eeb53054d0d3e --- /dev/null +++ b/src/sr_harness/parser/text_parser.py @@ -0,0 +1,215 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +from __future__ import annotations +import re +import json +import inspect +from ast import literal_eval +from logging import getLogger +from typing import List, Dict, Any +from .base_parser import BaseParser +from ..core import ToolCall + +_logger = getLogger(f'sr_harness.{__name__}') + + +@BaseParser.register('text') +class TextParser(BaseParser): + """Parser for tagged text tool calls.""" + + def format_tools(self) -> str: + """Format tool list into a description string for LLM. + + Returns: + Formatted tool description string. + """ + lines = ["## Available Tools:", ""] + + for tool in self.tools: + name = tool.metadata.name + desc = tool.metadata.description + + # 获取工具类的签名和 docstring + try: + if (tool_cls := type(tool)): + # 获取 execute 方法的签名 + sig = inspect.signature(tool_cls.execute) + params = [] + for param_name, param in sig.parameters.items(): + if param_name in ('self', 'args', 'kwargs'): + continue + # 构建带类型注解的参数描述 + param_parts = [] + param_parts.append(param_name) + # 添加类型注解 + if param.annotation is not inspect.Parameter.empty: + type_hint = self._format_type(param.annotation) + param_parts.append(f": {type_hint}") + # 添加默认值 + if param.default is not inspect.Parameter.empty: + default_val = param.default + param_parts.append(f" = {default_val!r}") + params.append("".join(param_parts)) + signature = f"{name}({', '.join(params)})" + + # 获取 docstring + docstring = inspect.getdoc(tool_cls.execute) or "No detailed documentation available." + else: + signature = f"{name}(...)" + docstring = "No detailed documentation available." + except Exception: + signature = f"{name}(...)" + docstring = "No detailed documentation available." + + lines.append(f"### {name}") + lines.append(f"- **Description**: {desc}") + lines.append(f"- **Signature**: `{signature}`") + lines.append(f"- **DocString**: {docstring}") + lines.append("") + + lines.append("## Output Format:") + lines.append("") + lines.append("Use the following format for tool calls:") + lines.append("") + lines.append("Action: tool_name(param1=value1, param2=value2)") + lines.append("") + lines.append("You can make multiple tool calls in sequence, one Action per line.") + + return "\n".join(lines) + + def parse_response(self, response: str) -> List[ToolCall]: + """Parse response. + + Args: + response: Provider response object. + + Returns: + List[ToolCall]: The operation result. + """ + tool_calls = [] + for line in response.strip().splitlines(): + line = line.strip() + if line.startswith('Action:'): + action_line = line.removeprefix('Action:').strip() + if (match := re.match(r'(\w+)\s*\((.*)\)', action_line)): + tool_name = match.group(1) + if (params_str := match.group(2).strip()): + params = self._parse_params(params_str) + else: + params = {} + tool_calls.append(ToolCall(name=tool_name, params=params, raw=line)) + else: + _logger.warning(f"Failed to parse action line: '{line}'") + return tool_calls + + def _parse_params(self, params_str: str) -> Dict[str, Any]: + """解析参数字符串为字典。 + + Args: + params_str: 参数字符串,如 'x_vars=["phi0", "phi1"], y_var="y"' + + Returns: + 参数字典 + """ + try: + # 先尝试 JSON 解析(如果整个字符串是 JSON 对象) + if params_str.startswith('{') and params_str.endswith('}'): + return json.loads(params_str) + else: + # 将 key=value, key2=value2 格式转换为字典 + params_dict = {} + parts = self._split_params(params_str) + for part in parts: + if '=' in part: + key, value = part.split('=', 1) + key = key.strip().lower() # 转换为小写 + value = value.strip() + try: + params_dict[key] = literal_eval(value) + except (ValueError, SyntaxError): + params_dict[key] = value + return params_dict + except Exception as e: + _logger.warning(f"Failed to parse params '{params_str}': {e}") + return {'raw_params': params_str} + + def _format_type(self, annotation) -> str: + """Format type annotation into a readable string. + + Args: + annotation: The type annotation to format. + + Returns: + Formatted type string. + """ + import typing + if annotation is inspect.Parameter.empty: + return "" + + # 处理常见类型 + if annotation is type(None): + return "None" + if annotation is ...: + return "..." + + # 处理 typing 模块的类型 + origin = getattr(annotation, '__origin__', None) + if origin is not None: + # 处理 Optional[T] = Union[T, None] + if origin is typing.Union: + args = getattr(annotation, '__args__', ()) + if type(None) in args: + non_none = [t for t in args if t is not type(None)] + if len(non_none) == 1: + return f"Optional[{self._format_type(non_none[0])}]" + # 处理 List[T], Dict[K, V], Tuple[...] + args = getattr(annotation, '__args__', ()) + args_str = ', '.join(self._format_type(arg) for arg in args) + name = getattr(origin, '__name__', str(origin)) + return f"{name}[{args_str}]" + + # 处理普通类型 + if hasattr(annotation, '__name__'): + return annotation.__name__ + + return str(annotation) + + def _split_params(self, params_str: str) -> List[str]: + """分割参数字符串,处理引号内的逗号。 + + Args: + params_str: 参数字符串,如 'x_vars=["phi0", "phi1"], y_var="y"' + + Returns: + 分割后的参数列表 + """ + parts = [] + current = [] + depth = 0 + in_string = False + string_char = None + + for char in params_str: + if char in '"\'': + if not in_string: + in_string = True + string_char = char + elif char == string_char: + in_string = False + string_char = None + current.append(char) + elif char in '[{(': + depth += 1 + current.append(char) + elif char in ']})': + depth -= 1 + current.append(char) + elif char == ',' and depth == 0 and not in_string: + parts.append(''.join(current).strip()) + current = [] + else: + current.append(char) + + if current: + parts.append(''.join(current).strip()) + + return parts diff --git a/src/sr_harness/parser/xml_parser.py b/src/sr_harness/parser/xml_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..2230617e7b50a122e4d8d37b85122588f2977287 --- /dev/null +++ b/src/sr_harness/parser/xml_parser.py @@ -0,0 +1,78 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +from __future__ import annotations +import json +import re +import xml.etree.ElementTree as ET +from logging import getLogger +from xml.sax.saxutils import escape, quoteattr + +from .base_parser import BaseParser +from ..core import ToolCall + +_logger = getLogger(f'sr_harness.{__name__}') +_TOOL_CALL_PATTERN = re.compile( + r"]*>.*?", + flags=re.DOTALL, +) + + +@BaseParser.register('xml') +class XMLParser(BaseParser): + """Parser for XML-formatted tool calls.""" + + def format_tools(self) -> str: + """Return tool metadata and the required XML call syntax.""" + lines = ["## Available Tools:", "", ""] + for tool in self.tools: + metadata = tool.metadata + parameters = json.dumps( + metadata.parameters or {"type": "object", "properties": {}}, + ensure_ascii=False, + separators=(",", ":"), + ) + lines.extend([ + f" ", + f" {escape(metadata.description or '')}", + f" {escape(parameters)}", + " ", + ]) + lines.extend([ + "", + "", + "## Output Format:", + "", + "Emit each tool call as a separate XML element. The arguments must be one JSON object:", + "", + '', + ' {"param1":"value1","param2":2}', + "", + "", + "You may emit multiple elements in one response.", + ]) + return "\n".join(lines) + + def parse_response(self, response: str) -> list[ToolCall]: + """Parse independent ``tool_call`` elements embedded in model text.""" + tool_calls = [] + for raw in _TOOL_CALL_PATTERN.findall(response): + try: + element = ET.fromstring(raw) + name = (element.get("name") or element.findtext("name") or "").strip() + if not name: + raise ValueError("tool_call has no tool name") + arguments_element = element.find("arguments") + if arguments_element is None: + arguments_element = element.find("params") + arguments_text = ( + "".join(arguments_element.itertext()).strip() + if arguments_element is not None + else "" + ) + params = json.loads(arguments_text) if arguments_text else {} + if not isinstance(params, dict): + raise ValueError("tool_call arguments must be a JSON object") + except (ET.ParseError, json.JSONDecodeError, ValueError) as error: + _logger.warning(f"Skip malformed XML tool call {raw!r}: {error}") + continue + tool_calls.append(ToolCall(name=name, params=params, raw=raw)) + return tool_calls diff --git a/src/sr_harness/runtime/__init__.py b/src/sr_harness/runtime/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..50134e91229f6ae95abe4e984d6a23b602080eef --- /dev/null +++ b/src/sr_harness/runtime/__init__.py @@ -0,0 +1,30 @@ +"""Components that coordinate a live SRHarness run.""" + +from .interaction_manager import ( + InteractionAction, + InteractionEventKind, + InteractionManager, + InteractionState, + PendingMessage, + SRInteractionAction, + SRInteractionManager, +) +from .model_router import ModelRoute, ModelRouter +from .sandbox import SandboxResult, SandboxRunner, get_sandbox_runner +from .workspace import Workspace + +__all__ = [ + "InteractionAction", + "InteractionEventKind", + "InteractionManager", + "InteractionState", + "ModelRoute", + "ModelRouter", + "PendingMessage", + "SRInteractionAction", + "SRInteractionManager", + "SandboxResult", + "SandboxRunner", + "get_sandbox_runner", + "Workspace", +] diff --git a/src/sr_harness/runtime/interaction_manager.py b/src/sr_harness/runtime/interaction_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..918ea567bd98ee28f17eacdf429e692f639eea67 --- /dev/null +++ b/src/sr_harness/runtime/interaction_manager.py @@ -0,0 +1,615 @@ +"""Thread-safe interaction state and event streams for one interactive agent.""" + +from __future__ import annotations + +from itertools import islice +import threading +import time +import uuid +from collections import deque +from contextlib import contextmanager +from dataclasses import dataclass +from typing import Any, Callable, Iterator, Literal, Mapping, TypeAlias, cast + +from ..core import json_value + + +InteractionState: TypeAlias = Literal[ + "idle", + "running", + "pausing", + "interrupting", + "paused", +] +InteractionAction: TypeAlias = Literal["message", "pause", "force_pause"] +SRInteractionAction: TypeAlias = Literal[ + "message", + "pause", + "force_pause", + "next_c", + "next_r", +] +InteractionEventKind: TypeAlias = Literal[ + "prompt_added", + "context", + "assistant_started", + "assistant_delta", + "assistant_completed", + "assistant_failed", + "tool_started", + "tool_completed", + "settings_applied", + "settings_failed", + "workspace_changed", + "execution_completed", + "execution_failed", + "command_received", + "state_changed", + "search_position_changed", + "topk_updated", +] + + +@dataclass(frozen=True) +class PendingMessage: + """A user message waiting to be inserted at an agent boundary.""" + + content: str + created_at: float + + +class _CancellationSignal: + """Read-only Event-like view of the manager's interruption state.""" + + def __init__(self, manager: "InteractionManager") -> None: + self._manager = manager + + def is_set(self) -> bool: + return self._manager.is_interrupting + + +class InteractionManager: + """Own the controls and observable event stream of exactly one agent. + + Args: + event_capacity: Maximum number of retained timeline events. + """ + + _DELTA_KIND = "assistant_delta" + _TERMINAL_KINDS = {"assistant_completed", "assistant_failed"} + _EVENT_KINDS = { + "prompt_added", + "context", + "assistant_started", + "assistant_delta", + "assistant_completed", + "assistant_failed", + "tool_started", + "tool_completed", + "settings_applied", + "settings_failed", + "workspace_changed", + "execution_completed", + "execution_failed", + "command_received", + "state_changed", + "search_position_changed", + "topk_updated", + } + _STATE_FIELDS = { + "version", + "state", + "messages", + "events", + "next_sequence", + "discarded_through", + "event_capacity", + } + + def __init__(self, *, event_capacity: int = 1000) -> None: + if event_capacity < 1: + raise ValueError("event_capacity must be positive") + self._condition = threading.Condition(threading.RLock()) + self._state: InteractionState = "idle" + self._messages: deque[PendingMessage] = deque() + self._events: deque[dict[str, Any]] = deque(maxlen=event_capacity) + self._next_sequence = 1 + self._discarded_through = 0 + self._cancel_current: Callable[[], str | None] | None = None + self._cancellation_signal = _CancellationSignal(self) + + @property + def state(self) -> InteractionState: + """Return the authoritative execution state. + + Returns: + Current interaction state. + """ + with self._condition: + return self._state + + @property + def is_interrupting(self) -> bool: + """Return whether the active operation should abort promptly. + + Returns: + Whether a force-pause request is interrupting active work. + """ + return self.state == "interrupting" + + @property + def cancellation_signal(self) -> _CancellationSignal: + """Expose a read-only Event-like cancellation adapter to tools. + + Returns: + Object exposing ``is_set()`` for cancellation-aware tools. + """ + return self._cancellation_signal + + def status(self) -> dict[str, Any]: + """Return a serializable control snapshot. + + Returns: + Current state, pending-input counts, event cursor, and server time. + """ + with self._condition: + return { + "interaction_state": self._state, + "paused": self._state in {"pausing", "interrupting", "paused"}, + "waiting_at_boundary": self._state == "paused", + "force_pause_requested": self._state == "interrupting", + "pending_messages": len(self._messages), + "last_event_seq": self._next_sequence - 1, + "server_time": time.time(), + } + + def command(self, action: InteractionAction, message: str | None = None) -> dict[str, Any]: + """Apply a user control command to this agent. + + Args: + action: Message, pause, or force-pause command. + message: User guidance required by the ``message`` action. + + Returns: + Control snapshot after applying the command. + + Raises: + ValueError: If the action is invalid or a message is empty. + """ + if action not in {"message", "pause", "force_pause"}: + raise ValueError("action must be message, pause, or force_pause") + cancel: Callable[[], str | None] | None = None + with self._condition: + if action == "message": + content = (message or "").strip() + if not content: + raise ValueError("message command requires non-empty message") + self._messages.append(PendingMessage(content, time.time())) + elif action == "pause": + if self._state == "running": + self._set_state_locked("pausing") + elif self._state in {"running", "pausing"}: + self._set_state_locked("interrupting") + cancel = self._cancel_current + self._condition.notify_all() + cancellation_error = cancel() if cancel is not None else None + with self._condition: + if cancellation_error and self._state == "interrupting": + self._set_state_locked("pausing") + if action != "message": + payload = {"action": action} + if cancellation_error: + payload["error"] = cancellation_error + self._publish_event_locked("command_received", payload) + result = self.status() + if cancellation_error: + result["cancellation_error"] = cancellation_error + return result + + def request_pause(self) -> None: + """Request a quiet pause, such as after a tool-free response.""" + with self._condition: + if self._state == "running": + self._set_state_locked("pausing") + self._condition.notify_all() + + def start_agent_execution(self) -> list[PendingMessage]: + """Enter running state and consume messages that start this execution. + + Returns: + Messages queued before execution started. + + Raises: + RuntimeError: If the manager is not idle. + """ + with self._condition: + if self._state != "idle": + raise RuntimeError(f"cannot start agent execution while {self._state}") + messages = self._consume_messages_locked() + self._set_state_locked("running") + return messages + + def finish_agent_execution(self) -> None: + """Mark a naturally completed agent execution as idle. + + Raises: + RuntimeError: If execution is paused at a boundary. + """ + with self._condition: + if self._state == "paused": + raise RuntimeError("cannot finish an execution while paused") + self._cancel_current = None + self._set_state_locked("idle") + + @contextmanager + def wait(self) -> Iterator[list[PendingMessage]]: + """Wait at a safe boundary and yield queued messages. + + Yields: + Messages to insert before the next model request. + + Raises: + RuntimeError: If no agent execution is active. + """ + with self._condition: + if self._state == "running": + messages = self._consume_messages_locked() + paused = False + elif self._state in {"pausing", "interrupting", "paused"}: + if self._state != "paused": + self._set_state_locked("paused") + self._cancel_current = None + while not self._has_boundary_input_locked(): + self._condition.wait() + messages = self._consume_messages_locked() + paused = True + else: + raise RuntimeError(f"cannot wait at an agent boundary while {self._state}") + try: + yield messages + finally: + if paused: + with self._condition: + if self._state == "paused": + self._set_state_locked("running") + + @contextmanager + def cancellable(self, cancel: Callable[[], str | None]) -> Iterator[None]: + """Register cancellation for the current blocking operation. + + Args: + cancel: Callback that promptly interrupts the active operation. + + Yields: + Control while the callback is registered. + + Raises: + RuntimeError: If another cancellable operation is already active. + """ + with self._condition: + if self._cancel_current is not None: + raise RuntimeError("another cancellable operation is already active") + self._cancel_current = cancel + cancel_immediately = self._state == "interrupting" + if cancel_immediately: + cancellation_error = cancel() + if cancellation_error: + with self._condition: + if self._state == "interrupting": + self._set_state_locked("pausing") + self._publish_event_locked( + "command_received", + {"action": "force_pause", "error": cancellation_error}, + ) + self._condition.notify_all() + try: + yield + finally: + with self._condition: + if self._cancel_current is cancel: + self._cancel_current = None + + def publish_event( + self, kind: InteractionEventKind, payload: Mapping[str, Any] + ) -> dict[str, Any]: + """Append one observable event to this agent's timeline. + + Args: + kind: Supported event kind. + payload: JSON-serializable event data. + + Returns: + Stored event with sequence, identifier, and timestamp. + + Raises: + ValueError: If ``kind`` is unsupported. + """ + if kind not in self._EVENT_KINDS: + raise ValueError(f"unsupported interaction event kind: {kind}") + with self._condition: + return self._publish_event_locked(kind, payload) + + def get_recent_events(self, after_sequence: int = 0, *, limit: int | None = None) -> dict[str, Any]: + """Return retained events newer than a consumer-owned sequence cursor. + + Args: + after_sequence: Last sequence already consumed by the caller. + limit: Maximum events per batch; omitted for an unlimited internal snapshot. + + Returns: + Event batch and cursor-reset or truncation metadata. + """ + with self._condition: + latest_sequence = self._next_sequence - 1 + cursor_reset = after_sequence > latest_sequence + effective_sequence = 0 if cursor_reset else after_sequence + return { + "events": [ + dict(event) for event in islice( + (item for item in self._events if item["seq"] > effective_sequence), + limit, + ) + ], + "truncated": effective_sequence < self._discarded_through, + "discarded_through": self._discarded_through, + "cursor_reset": cursor_reset, + "server_time": time.time(), + } + + def export_state(self) -> dict[str, Any]: + """Return the durable portion of this manager's state. + + Returns: + Versioned interaction snapshot without runtime locks or callbacks. + """ + with self._condition: + return { + "version": 1, + "state": self._state, + "messages": [ + {"content": message.content, "created_at": message.created_at} + for message in self._messages + ], + "events": [dict(event) for event in self._events], + "next_sequence": self._next_sequence, + "discarded_through": self._discarded_through, + "event_capacity": self._events.maxlen, + } + + def restore_state(self, snapshot: Mapping[str, Any]) -> bool: + """Restore durable state and interrupt work that died with the process. + + Runtime callbacks and locks are deliberately never restored. + + Args: + snapshot: State returned by :meth:`export_state`. + + Returns: + Whether in-flight work was converted into an interruption event. + """ + with self._condition: + if set(snapshot) != self._STATE_FIELDS: + raise ValueError("Persisted interaction state does not match the current schema") + if snapshot["version"] != 1: + raise ValueError("Unsupported InteractionManager snapshot version") + previous = snapshot["state"] + if previous not in {"idle", "running", "pausing", "interrupting", "paused"}: + raise ValueError(f"Unknown persisted interaction state: {previous!r}") + capacity = snapshot["event_capacity"] + if not isinstance(capacity, int) or isinstance(capacity, bool) or capacity < 1: + raise ValueError("Persisted event_capacity must be positive") + events = snapshot["events"] + if not isinstance(events, list) or any( + not isinstance(event, Mapping) for event in events + ): + raise TypeError("Persisted events must be a list of mappings") + required_event_fields = {"seq", "id", "kind", "timestamp", "payload"} + if any(set(event) != required_event_fields for event in events): + raise ValueError("Persisted events must use the current event schema") + if any(event["kind"] not in self._EVENT_KINDS for event in events): + raise ValueError("Persisted events contain an unsupported event kind") + if any( + not isinstance(event["seq"], int) + or isinstance(event["seq"], bool) + or event["seq"] < 1 + or not isinstance(event["id"], str) + or not event["id"] + or not isinstance(event["timestamp"], (int, float)) + or isinstance(event["timestamp"], bool) + or not isinstance(event["payload"], Mapping) + for event in events + ): + raise TypeError("Persisted events contain invalid field values") + if [event["seq"] for event in events] != sorted({event["seq"] for event in events}): + raise ValueError("Persisted event sequences must be unique and increasing") + self._events = deque( + (dict(event) for event in events), + maxlen=capacity, + ) + messages = snapshot["messages"] + if not isinstance(messages, list) or any( + not isinstance(item, Mapping) for item in messages + ): + raise TypeError("Persisted messages must be a list of mappings") + if any(set(item) != {"content", "created_at"} for item in messages): + raise ValueError("Persisted messages must use the current message schema") + if any( + not isinstance(item["content"], str) + or not item["content"] + or not isinstance(item["created_at"], (int, float)) + or isinstance(item["created_at"], bool) + for item in messages + ): + raise TypeError("Persisted messages contain invalid field values") + self._messages = deque( + PendingMessage(item["content"], item["created_at"]) for item in messages + ) + discarded_through = snapshot["discarded_through"] + if ( + not isinstance(discarded_through, int) + or isinstance(discarded_through, bool) + or discarded_through < 0 + ): + raise ValueError("Persisted discarded_through must be a non-negative integer") + self._discarded_through = discarded_through + highest_sequence = max( + (event["seq"] for event in self._events), + default=0, + ) + next_sequence = snapshot["next_sequence"] + if ( + not isinstance(next_sequence, int) + or isinstance(next_sequence, bool) + or next_sequence <= highest_sequence + or next_sequence <= discarded_through + ): + raise ValueError("Persisted next_sequence is inconsistent with retained events") + self._next_sequence = next_sequence + interrupted = previous in {"running", "pausing", "interrupting", "paused"} + self._state = "idle" + self._cancel_current = None + if interrupted: + self._publish_event_locked( + "command_received", + {"action": "force_pause", "restored_after_restart": True}, + ) + self._publish_event_locked( + "state_changed", + {"previous": previous, "current": "idle", "interrupted": True}, + ) + return interrupted + + def _consume_messages_locked(self) -> list[PendingMessage]: + messages = list(self._messages) + self._messages.clear() + return messages + + def _has_boundary_input_locked(self) -> bool: + return bool(self._messages) + + def _set_state_locked(self, state: InteractionState) -> None: + previous = self._state + if previous == state: + return + self._state = state + self._publish_event_locked("state_changed", {"previous": previous, "current": state}) + + def _publish_event_locked( + self, kind: InteractionEventKind, payload: Mapping[str, Any] + ) -> dict[str, Any]: + payload_dict = cast(dict[str, Any], json_value(dict(payload))) + sequence = self._next_sequence + self._next_sequence += 1 + event = { + "seq": sequence, + "id": uuid.uuid4().hex, + "kind": kind, + "timestamp": time.time(), + "payload": payload_dict, + } + response_id = payload_dict.get("response_id") + if response_id and kind == self._DELTA_KIND: + self._remove_stream_events_locked(response_id, {kind}) + elif response_id and kind in self._TERMINAL_KINDS: + self._remove_stream_events_locked(response_id, {self._DELTA_KIND}) + if len(self._events) == self._events.maxlen and self._events: + self._discarded_through = max(self._discarded_through, self._events[0]["seq"]) + self._events.append(event) + return dict(event) + + def _remove_stream_events_locked(self, response_id: str, kinds: set[str]) -> None: + self._events = deque( + ( + event + for event in self._events + if not ( + event["kind"] in kinds + and event.get("payload", {}).get("response_id") == response_id + ) + ), + maxlen=self._events.maxlen, + ) + + +class SRInteractionManager(InteractionManager): + """Interaction manager with symbolic-regression branch commands.""" + + _STATE_FIELDS = InteractionManager._STATE_FIELDS | {"search_transitions"} + + def __init__(self, *, event_capacity: int = 1000) -> None: + super().__init__(event_capacity=event_capacity) + self._search_transitions: deque[Literal["next_c", "next_r"]] = deque() + + def command(self, action: SRInteractionAction, message: str | None = None) -> dict[str, Any]: + """Apply a common command or queue an SR branch transition. + + Args: + action: Common interaction action or ``next_c``/``next_r``. + message: User guidance for a ``message`` action. + + Returns: + Control snapshot after applying the command. + """ + if action not in {"next_c", "next_r"}: + return super().command(cast(InteractionAction, action), message) + with self._condition: + self._search_transitions.clear() + self._search_transitions.append(action) + self._publish_event_locked("command_received", {"action": action}) + self._condition.notify_all() + return self.status() + + def consume_search_transition(self) -> Literal["next_c", "next_r"] | None: + """Consume the newest queued branch transition. + + Returns: + Queued transition, or ``None`` when no transition is pending. + """ + with self._condition: + return self._search_transitions.popleft() if self._search_transitions else None + + def _has_boundary_input_locked(self) -> bool: + return bool(self._messages or self._search_transitions) + + def status(self) -> dict[str, Any]: + """Include the pending SR branch transition in the control snapshot. + + Returns: + Common control snapshot with ``pending_transition``. + """ + with self._condition: + status = super().status() + status["pending_transition"] = ( + self._search_transitions[-1] if self._search_transitions else None + ) + return status + + def export_state(self) -> dict[str, Any]: + """Include pending search transitions in the durable snapshot. + + Returns: + Versioned interaction snapshot with symbolic-search transitions. + """ + with self._condition: + state = super().export_state() + state["search_transitions"] = list(self._search_transitions) + return state + + def restore_state(self, snapshot: Mapping[str, Any]) -> bool: + """Restore common state plus queued symbolic-search transitions. + + Args: + snapshot: State returned by :meth:`export_state`. + + Returns: + Whether in-flight work was converted into an interruption event. + """ + interrupted = super().restore_state(snapshot) + with self._condition: + transitions = snapshot["search_transitions"] + if not isinstance(transitions, list) or any( + action not in {"next_c", "next_r"} for action in transitions + ): + raise ValueError("Persisted search_transitions contains an invalid action") + self._search_transitions = deque(transitions) + return interrupted diff --git a/src/sr_harness/runtime/landlock.py b/src/sr_harness/runtime/landlock.py new file mode 100644 index 0000000000000000000000000000000000000000..341a273003fb804917fce9071136db6081f3f3ce --- /dev/null +++ b/src/sr_harness/runtime/landlock.py @@ -0,0 +1,293 @@ +"""Small Linux Landlock and seccomp bindings for sandbox workers.""" + +from __future__ import annotations + +import ctypes +import errno +import os +import platform +from pathlib import Path + + +class LandlockUnavailableError(RuntimeError): + """Raised when the kernel cannot enforce the requested Landlock policy.""" + + +_LIBC = ctypes.CDLL(None, use_errno=True) +_SYS_LANDLOCK_CREATE_RULESET = 444 +_SYS_LANDLOCK_ADD_RULE = 445 +_SYS_LANDLOCK_RESTRICT_SELF = 446 +_LANDLOCK_CREATE_RULESET_VERSION = 1 +_LANDLOCK_RULE_PATH_BENEATH = 1 +_PR_SET_NO_NEW_PRIVS = 38 +_PR_SET_SECCOMP = 22 +_SECCOMP_MODE_FILTER = 2 +_SECCOMP_RET_KILL_PROCESS = 0x80000000 +_AUDIT_ARCHITECTURES = { + "x86_64": 0xC000003E, + "aarch64": 0xC00000B7, +} + +_FS_EXECUTE = 1 << 0 +_FS_WRITE_FILE = 1 << 1 +_FS_READ_FILE = 1 << 2 +_FS_READ_DIR = 1 << 3 +_FS_REMOVE_DIR = 1 << 4 +_FS_REMOVE_FILE = 1 << 5 +_FS_MAKE_CHAR = 1 << 6 +_FS_MAKE_DIR = 1 << 7 +_FS_MAKE_REG = 1 << 8 +_FS_MAKE_SOCK = 1 << 9 +_FS_MAKE_FIFO = 1 << 10 +_FS_MAKE_BLOCK = 1 << 11 +_FS_MAKE_SYM = 1 << 12 +_FS_REFER = 1 << 13 +_FS_TRUNCATE = 1 << 14 +_FS_IOCTL_DEV = 1 << 15 + + +class _RulesetAttr(ctypes.Structure): + _fields_ = [("handled_access_fs", ctypes.c_uint64)] + + +class _PathBeneathAttr(ctypes.Structure): + _fields_ = [ + ("allowed_access", ctypes.c_uint64), + ("parent_fd", ctypes.c_int32), + ("reserved", ctypes.c_uint32), + ] + + +class _SockFilter(ctypes.Structure): + _fields_ = [ + ("code", ctypes.c_ushort), + ("jt", ctypes.c_ubyte), + ("jf", ctypes.c_ubyte), + ("k", ctypes.c_uint32), + ] + + +class _SockFprog(ctypes.Structure): + _fields_ = [ + ("length", ctypes.c_ushort), + ("filters", ctypes.POINTER(_SockFilter)), + ] + + +def _syscall(number: int, *args) -> int: + result = int(_LIBC.syscall(number, *args)) + if result < 0: + code = ctypes.get_errno() + raise OSError(code, os.strerror(code)) + return result + + +def landlock_abi() -> int: + """Return the supported Landlock ABI version. + + Returns: + Positive ABI version. + """ + if platform.system() != "Linux": + raise LandlockUnavailableError("Landlock is available only on Linux") + try: + return _syscall( + _SYS_LANDLOCK_CREATE_RULESET, + ctypes.c_void_p(), + ctypes.c_size_t(0), + ctypes.c_uint(_LANDLOCK_CREATE_RULESET_VERSION), + ) + except OSError as exc: + raise LandlockUnavailableError(f"Landlock is unavailable: {exc}") from exc + + +def _handled_rights(abi: int) -> int: + rights = ( + _FS_EXECUTE + | _FS_WRITE_FILE + | _FS_READ_FILE + | _FS_READ_DIR + | _FS_REMOVE_DIR + | _FS_REMOVE_FILE + | _FS_MAKE_CHAR + | _FS_MAKE_DIR + | _FS_MAKE_REG + | _FS_MAKE_SOCK + | _FS_MAKE_FIFO + | _FS_MAKE_BLOCK + | _FS_MAKE_SYM + ) + if abi >= 2: + rights |= _FS_REFER + if abi >= 3: + rights |= _FS_TRUNCATE + if abi >= 5: + rights |= _FS_IOCTL_DEV + return rights + + +def _path_rights( + path: Path, + handled: int, + *, + write: bool, + execute: bool, + remove: bool, +) -> int: + rights = _FS_READ_FILE + if path.is_dir(): + rights |= _FS_READ_DIR + if execute: + rights |= _FS_EXECUTE + if write: + rights |= ( + _FS_WRITE_FILE + | _FS_MAKE_DIR + | _FS_MAKE_REG + | _FS_MAKE_SOCK + | _FS_MAKE_FIFO + | _FS_MAKE_SYM + | _FS_TRUNCATE + ) + if remove: + rights |= _FS_REMOVE_DIR | _FS_REMOVE_FILE | _FS_REFER + return rights & handled + + +def restrict_filesystem( + *, + readable: list[str | Path], + writable: list[str | Path], + nonremovable_writable: list[str | Path], + executable: list[str | Path], +) -> int: + """Restrict the current process and descendants to explicit path trees. + + Args: + readable: Read-only files and directory trees. + writable: Read-write files and directory trees. + nonremovable_writable: Read-write trees in which removal, rename, and + cross-directory linking are denied. + executable: Trees from which binaries or libraries may be executed. + + Returns: + Enforced Landlock ABI version. + """ + abi = landlock_abi() + handled = _handled_rights(abi) + ruleset_attr = _RulesetAttr(handled_access_fs=handled) + ruleset_fd = _syscall( + _SYS_LANDLOCK_CREATE_RULESET, + ctypes.byref(ruleset_attr), + ctypes.sizeof(ruleset_attr), + ctypes.c_uint(0), + ) + try: + policies: dict[Path, tuple[bool, bool, bool]] = {} + for raw_path, write, execute_path, remove in [ + *((path, False, False, False) for path in readable), + *((path, True, False, True) for path in writable), + *((path, True, False, False) for path in nonremovable_writable), + *((path, False, True, False) for path in executable), + ]: + path = Path(raw_path).resolve() + if not path.exists(): + continue + previous = policies.get(path, (False, False, False)) + policies[path] = ( + previous[0] or write, + previous[1] or execute_path, + previous[2] or remove, + ) + for path, (write, execute_path, remove) in policies.items(): + descriptor = os.open(path, os.O_PATH | os.O_CLOEXEC) + try: + attr = _PathBeneathAttr( + allowed_access=_path_rights( + path, + handled, + write=write, + execute=execute_path, + remove=remove, + ), + parent_fd=descriptor, + reserved=0, + ) + _syscall( + _SYS_LANDLOCK_ADD_RULE, + ruleset_fd, + _LANDLOCK_RULE_PATH_BENEATH, + ctypes.byref(attr), + ctypes.c_uint(0), + ) + finally: + os.close(descriptor) + if _LIBC.prctl(_PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0: + code = ctypes.get_errno() + raise OSError(code, os.strerror(code)) + _syscall(_SYS_LANDLOCK_RESTRICT_SELF, ruleset_fd, ctypes.c_uint(0)) + except OSError as exc: + raise LandlockUnavailableError(f"Could not enforce Landlock policy: {exc}") from exc + finally: + os.close(ruleset_fd) + return abi + + +def _number_set(values: str) -> frozenset[int]: + return frozenset(map(int, values.split())) + + +_BLOCKED_SYSCALLS = { + "x86_64": _number_set( + "29 30 31 34 41 53 56 57 58 59 62 64 65 66 67 68 69 70 " + "71 76 77 90 91 92 93 94 101 103 132 133 141 142 144 155 159 161 " + "163 164 165 166 167 168 169 170 171 172 173 175 176 179 188 189 190 197 " + "198 199 200 203 220 227 234 246 248 249 250 256 259 260 261 268 272 279 " + "280 298 300 301 302 303 304 305 308 310 311 313 321 322 323 424 425 426 " + "427 434 435 438 440" + ), + "aarch64": _number_set( + "5 6 7 14 15 16 33 39 40 41 45 46 51 52 53 54 55 88 " + "89 97 104 105 106 117 118 119 122 129 130 131 142 161 162 170 171 186 " + "187 188 189 190 191 192 193 194 195 196 197 198 199 217 218 219 220 221 " + "224 225 238 239 241 261 262 263 265 266 268 270 271 273 280 281 282 294 " + "424 425 426 427 434 435 438 440" + ), +} + + +def restrict_system_calls() -> None: + """Deny networking, child processes, and host-management syscalls.""" + architecture = platform.machine().lower() + if architecture in {"amd64"}: + architecture = "x86_64" + if architecture in {"arm64"}: + architecture = "aarch64" + try: + blocked = sorted(_BLOCKED_SYSCALLS[architecture]) + except KeyError as exc: + raise LandlockUnavailableError( + f"No seccomp syscall table for architecture {architecture!r}" + ) from exc + # classic BPF: validate seccomp_data.arch, load seccomp_data.nr, return + # EACCES for blocked calls, and allow everything else. + instructions = [ + _SockFilter(0x20, 0, 0, 4), + _SockFilter(0x15, 1, 0, _AUDIT_ARCHITECTURES[architecture]), + _SockFilter(0x06, 0, 0, _SECCOMP_RET_KILL_PROCESS), + _SockFilter(0x20, 0, 0, 0), + ] + denied = 0x00050000 | errno.EACCES + for syscall_number in blocked: + instructions.append(_SockFilter(0x15, 0, 1, syscall_number)) + instructions.append(_SockFilter(0x06, 0, 0, denied)) + instructions.append(_SockFilter(0x06, 0, 0, 0x7FFF0000)) + array_type = _SockFilter * len(instructions) + filters = array_type(*instructions) + program = _SockFprog(len(instructions), filters) + if _LIBC.prctl(_PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0: + code = ctypes.get_errno() + raise LandlockUnavailableError(f"Could not set no_new_privs: {os.strerror(code)}") + if _LIBC.prctl(_PR_SET_SECCOMP, _SECCOMP_MODE_FILTER, ctypes.byref(program)) != 0: + code = ctypes.get_errno() + raise LandlockUnavailableError(f"Could not install seccomp filter: {os.strerror(code)}") diff --git a/src/sr_harness/runtime/model_router.py b/src/sr_harness/runtime/model_router.py new file mode 100644 index 0000000000000000000000000000000000000000..75c64f50364b82b9742daba7d2aaa2d5b3b98146 --- /dev/null +++ b/src/sr_harness/runtime/model_router.py @@ -0,0 +1,120 @@ +"""Deterministic cost-aware routing between base and strong LLM backends.""" +from __future__ import annotations + +import re +from dataclasses import dataclass + + +@dataclass(frozen=True) +class ModelRoute: + """Selected provider/model route and its rationale.""" + tier: str + provider: str + model: str + score: int + reason: str + + +class ModelRouter: + """Choose a cheap base model or an optional stronger model per request.""" + + COMPLEX_PATTERNS = { + r"\b(?:pde|ode|differential equation|network dynamics|graph dynamics)\b": 3, + r"\b(?:implicit|piecewise|singular|stiff|chaotic|high[- ]dimensional)\b": 2, + r"\b(?:noise|noisy|numerical stability|floating[- ]point|cancellation)\b": 1, + r"(?:微分方程|网络动力学|图动力学|隐式|分段|奇异|混沌|高维)": 3, + r"(?:噪声|数值稳定|浮点|消减误差)": 1, + } + + def __init__( + self, + *, + enabled: bool, + base_provider: str, + base_model: str, + strong_provider: str | None = None, + strong_model: str | None = None, + ) -> None: + for name, value in (("base_provider", base_provider), ("base_model", base_model)): + if not isinstance(value, str) or not value.strip(): + raise ValueError(f"{name} must be a non-empty string") + for name, value in (("strong_provider", strong_provider), ("strong_model", strong_model)): + if value is not None and (not isinstance(value, str) or not value.strip()): + raise ValueError(f"{name} must be None or a non-empty string") + self.enabled = enabled + self.base_provider = base_provider + self.base_model = base_model + self.strong_provider = base_provider if strong_provider is None else strong_provider + self.strong_model = strong_model + + @property + def has_strong_backend(self) -> bool: + """Run the ``has strong backend`` operation. + + Returns: + bool: The operation result. + """ + return bool( + self.strong_model + and (self.strong_provider, self.strong_model) + != (self.base_provider, self.base_model) + ) + + def assess(self, task: str, feature_count: int) -> tuple[int, list[str]]: + """Run the ``assess`` operation. + + Args: + task: The task value. + feature_count: The feature count value. + + Returns: + tuple[int, list[str]]: The operation result. + """ + text = task.lower() + score = max(0, feature_count - 3) + reasons = [f"{feature_count} features"] if feature_count > 3 else [] + for pattern, weight in self.COMPLEX_PATTERNS.items(): + if re.search(pattern, text): + score += weight + reasons.append(pattern) + return score, reasons + + def route( + self, + *, + task_score: int, + task_reasons: list[str], + refinement_step: int, + ) -> ModelRoute: + """Run the ``route`` operation. + + Args: + task_score: The task score value. + task_reasons: The task reasons value. + refinement_step: The refinement step value. + + Returns: + ModelRoute: The operation result. + """ + if not self.enabled: + return self._base(task_score, "automatic routing disabled") + if not self.has_strong_backend: + return self._base(task_score, "no distinct strong backend configured") + if task_score >= 3: + reason = "complex task signals: " + ", ".join(task_reasons or [str(task_score)]) + return self._strong(task_score, reason) + if refinement_step >= 3: + return self._strong(task_score, "base backend did not converge within two rounds") + return self._base(task_score, "simple task or early exploration") + + def _base(self, score: int, reason: str) -> ModelRoute: + return ModelRoute("base", self.base_provider, self.base_model, score, reason) + + def _strong(self, score: int, reason: str) -> ModelRoute: + return ModelRoute( + "strong", + self.strong_provider, + self.strong_model or self.base_model, + score, + reason, + ) diff --git a/src/sr_harness/runtime/network.py b/src/sr_harness/runtime/network.py new file mode 100644 index 0000000000000000000000000000000000000000..da278e56ee7e0eb342e5185ffd67bf6669586d1d --- /dev/null +++ b/src/sr_harness/runtime/network.py @@ -0,0 +1,53 @@ +"""Session-scoped outbound proxy routing.""" +from __future__ import annotations + +import base64 +from collections.abc import Mapping +from urllib.parse import quote, urlsplit, urlunsplit + + +def routed_proxy(user_proxy: str, egress_proxy: str) -> str: + """Route an optional user proxy through the deployment egress gateway. + + Args: + user_proxy: User-selected upstream HTTP, HTTPS, or SOCKS proxy. + egress_proxy: Deployment-managed HTTP egress gateway. + + Returns: + A proxy URL suitable for ordinary HTTP clients. When both values are + present, the upstream URL is encoded as gateway credentials so the + gateway can establish the second proxy hop. + """ + user_proxy = user_proxy.strip() + egress_proxy = egress_proxy.strip() + if not egress_proxy: + return user_proxy + if not user_proxy: + return egress_proxy + if urlsplit(user_proxy).scheme not in {"http", "https"}: + raise ValueError("the deployment egress gateway supports HTTP(S) upstream proxies only") + parsed = urlsplit(egress_proxy) + if parsed.scheme not in {"http", "https"} or not parsed.hostname: + raise ValueError("SRH_EGRESS_PROXY must be an HTTP or HTTPS URL") + token = base64.urlsafe_b64encode(user_proxy.encode()).decode().rstrip("=") + host = parsed.hostname + if ":" in host: + host = f"[{host}]" + if parsed.port: + host += f":{parsed.port}" + netloc = f"{quote('srh.' + token, safe='')}:x@{host}" + return urlunsplit((parsed.scheme, netloc, parsed.path, parsed.query, parsed.fragment)) + + +def proxy_environment( + environment: Mapping[str, str], *, user_proxy: str, egress_proxy: str, +) -> dict[str, str]: + """Return a session environment containing the effective outbound proxy.""" + result = dict(environment) + for name in ("http_proxy", "HTTP_PROXY", "https_proxy", "HTTPS_PROXY"): + result.pop(name, None) + effective = routed_proxy(user_proxy, egress_proxy) + if effective: + result.update({"HTTP_PROXY": effective, "HTTPS_PROXY": effective}) + return result + diff --git a/src/sr_harness/runtime/sandbox.py b/src/sr_harness/runtime/sandbox.py new file mode 100644 index 0000000000000000000000000000000000000000..bf7fcae0fe7de9c085928b22a472612886f5d66d --- /dev/null +++ b/src/sr_harness/runtime/sandbox.py @@ -0,0 +1,609 @@ +"""Operating-system sandbox used for untrusted Python execution.""" + +from __future__ import annotations + +import io +import json +import os +import signal +import stat +import subprocess +import sys +import tempfile +import threading +import time +import weakref +from dataclasses import dataclass +from pathlib import Path +from threading import Event +from typing import Any + +import numpy as np + +from .landlock import LandlockUnavailableError, landlock_abi +from .workspace import Workspace + + +def _fully_unlocked_workspace_subtrees(workspace: Workspace) -> list[Path]: + """Return maximal directory trees containing no effectively locked entries. + + Landlock removal rights belong to directories and therefore cannot distinguish + locked and unlocked siblings. A directory is safe to grant recursively only + when the directory itself and every ordinary descendant are unlocked. Mounted + inputs are governed by their own rules and are excluded from this calculation. + """ + root = workspace.path + mount_roots = set(workspace.mount_map) + directories: list[Path] = [] + child_directories: dict[Path, list[Path]] = {} + child_files: dict[Path, list[Path]] = {} + for current_name, directory_names, file_names in os.walk(root, followlinks=False): + current = Path(current_name) + directory_names[:] = [ + name + for name in directory_names + if (current / name) not in mount_roots and not (current / name).is_symlink() + ] + directories.append(current) + child_directories[current] = [current / name for name in directory_names] + child_files[current] = [ + current / name + for name in file_names + if (current / name) not in mount_roots and not (current / name).is_symlink() + ] + + fully_unlocked: dict[Path, bool] = {} + for directory in reversed(directories): + fully_unlocked[directory] = ( + not workspace.is_locked(directory) + and all(not workspace.is_locked(path) for path in child_files[directory]) + and all(fully_unlocked[path] for path in child_directories[directory]) + ) + return [ + directory + for directory in directories + if fully_unlocked[directory] + and (directory == root or not fully_unlocked.get(directory.parent, False)) + ] + + +class SandboxUnavailableError(RuntimeError): + """Raised when the required operating-system sandbox is unavailable.""" + + +class SandboxExecutionError(RuntimeError): + """Raised when an isolated worker cannot complete its request.""" + + +@dataclass(frozen=True) +class SandboxResult: + """Observable result of executing a Python program in the sandbox. + + Args: + exit_code: Program exit status; zero denotes successful execution. + stdout: Captured standard output. + stderr: Captured standard error. + duration_seconds: Wall-clock execution duration in seconds. + cpu_seconds: User and system CPU time consumed by the worker. + peak_memory_bytes: Peak resident set size reported by the worker. + """ + + exit_code: int + stdout: str + stderr: str + duration_seconds: float + cpu_seconds: float + peak_memory_bytes: int + + +@dataclass(frozen=True) +class _ProtocolResult: + """Private result used by structured sandbox adapters.""" + + payload: dict[str, Any] + arrays: dict[str, dict[str, np.ndarray]] + duration_seconds: float + cpu_seconds: float + peak_memory_bytes: int + + +@dataclass +class _ArraySnapshot: + """Reusable read-only-on-disk arrays for one AgentContext data revision.""" + + temporary_directory: tempfile.TemporaryDirectory[str] + root: Path + revision: int + signature: tuple[tuple[str, int, tuple[int, ...], str], ...] + + +_ARRAY_SNAPSHOT_LOCK = threading.RLock() +_ARRAY_SNAPSHOTS: weakref.WeakKeyDictionary[Any, _ArraySnapshot] = weakref.WeakKeyDictionary() + + +def _write_array_groups(root: Path, groups: dict[str, dict[str, Any]]) -> None: + """Serialize named array groups without pickle support.""" + manifest: dict[str, dict[str, str]] = {} + array_root = root / "arrays" + array_root.mkdir() + index = 0 + for group_name, values in groups.items(): + manifest[group_name] = {} + for name, value in values.items(): + filename = f"array-{index}.npy" + array = np.asarray(value) + if array.dtype.hasobject: + raise TypeError(f"Sandbox array {name!r} must not use object dtype") + np.save(array_root / filename, array, allow_pickle=False) + manifest[group_name][str(name)] = filename + index += 1 + (root / "arrays.json").write_text(json.dumps(manifest), encoding="utf-8") + + +def _context_array_snapshot(context: Any) -> _ArraySnapshot: + """Return a reusable immutable-on-disk snapshot of ``context.data``.""" + revision = int(getattr(context.args, "data_revision", 0)) + signature = tuple( + sorted( + ( + str(name), + id(value), + tuple(np.asarray(value).shape), + np.asarray(value).dtype.str, + ) + for name, value in context.data.items() + ) + ) + with _ARRAY_SNAPSHOT_LOCK: + current = _ARRAY_SNAPSHOTS.get(context) + if ( + current is not None + and current.revision == revision + and current.signature == signature + ): + return current + temporary = tempfile.TemporaryDirectory(prefix="srh-sandbox-arrays-") + root = Path(temporary.name) + _write_array_groups(root, {"context": context.data}) + snapshot = _ArraySnapshot(temporary, root, revision, signature) + _ARRAY_SNAPSHOTS[context] = snapshot + return snapshot + + +def _read_array_groups(root: Path) -> dict[str, dict[str, np.ndarray]]: + """Load worker-produced arrays with object deserialization disabled.""" + manifest_file = root / "arrays.json" + if not manifest_file.exists(): + return {} + manifest = json.loads(_read_regular_bytes(manifest_file).decode("utf-8")) + if not isinstance(manifest, dict): + raise SandboxExecutionError("Sandbox array manifest must be a dictionary") + groups: dict[str, dict[str, np.ndarray]] = {} + for group_name, values in manifest.items(): + if not isinstance(group_name, str) or not isinstance(values, dict): + raise SandboxExecutionError("Sandbox array manifest is malformed") + group: dict[str, np.ndarray] = {} + for name, filename in values.items(): + if not isinstance(name, str) or not isinstance(filename, str): + raise SandboxExecutionError("Sandbox array manifest is malformed") + path = root / "arrays" / filename + if path.parent != root / "arrays": + raise SandboxExecutionError("Sandbox returned an invalid array path") + with io.BytesIO(_read_regular_bytes(path)) as stream: + group[name] = np.load(stream, allow_pickle=False) + groups[group_name] = group + return groups + + +def _read_regular_bytes(path: Path, limit: int | None = None) -> bytes: + """Read an ordinary file without following worker-created symlinks.""" + try: + metadata = path.lstat() + except FileNotFoundError: + raise SandboxExecutionError(f"Sandbox result file is missing: {path.name}") from None + if not stat.S_ISREG(metadata.st_mode): + raise SandboxExecutionError(f"Sandbox result path is not a regular file: {path.name}") + if limit is not None and metadata.st_size > limit: + raise SandboxExecutionError(f"Sandbox result file exceeded its size limit: {path.name}") + descriptor = os.open(path, os.O_RDONLY | os.O_CLOEXEC | os.O_NOFOLLOW) + try: + with os.fdopen(descriptor, "rb", closefd=False) as stream: + return stream.read() if limit is None else stream.read(limit + 1) + finally: + os.close(descriptor) + + +class _SandboxProcessRunner: + """Implement the private file protocol spoken by the sandbox worker.""" + + RESULT_METADATA_LIMIT = 16 * 1024 * 1024 + + def __init__(self) -> None: + try: + self.landlock_abi = landlock_abi() + except LandlockUnavailableError as exc: + raise SandboxUnavailableError( + "Linux Landlock is unavailable; refusing to execute untrusted code." + ) from exc + if self.landlock_abi < 3: + raise SandboxUnavailableError( + "Linux Landlock ABI 3 or newer is required; refusing to execute " + "untrusted code without file-truncation protection." + ) + + @staticmethod + def _runtime_source_root() -> Path: + return Path(__file__).resolve().parents[2] + + @staticmethod + def _safe_environment(*, root: str, temporary: str) -> dict[str, str]: + return { + "HOME": "/tmp/home", + "LANG": "C.UTF-8", + "LC_ALL": "C.UTF-8", + "MPLBACKEND": "Agg", + "MPLCONFIGDIR": f"{temporary}/matplotlib", + "NUMEXPR_NUM_THREADS": "1", + "OMP_NUM_THREADS": "1", + "OPENBLAS_NUM_THREADS": "1", + "MKL_NUM_THREADS": "1", + "PATH": f"{root}/bin:/usr/bin:/bin", + "PYTHONNOUSERSITE": "1", + "PYTHONPATH": root, + "TMPDIR": temporary, + "VECLIB_MAXIMUM_THREADS": "1", + } + + def _worker_command( + self, + *, + input_directory: Path, + array_directory: Path, + output_directory: Path, + temporary_directory: Path, + workspace: Path | None, + readonly_mounts: dict[str, Path], + writable_mounts: dict[str, Path], + protect_workspace_entries: bool, + removable_workspace_subtrees: list[Path], + ) -> tuple[list[str], dict[str, str], Path]: + """Build a worker command whose first action installs the sandbox policy.""" + runtime = Path(sys.prefix).resolve() + source = self._runtime_source_root().resolve() + readable = [input_directory, array_directory, runtime, source] + executable = [runtime] + for system_path in (Path("/usr"), Path("/bin"), Path("/lib"), Path("/lib64")): + if system_path.exists(): + readable.append(system_path) + executable.append(system_path) + writable = [output_directory, temporary_directory] + nonremovable_writable: list[Path] = [] + if workspace is not None: + working_directory = workspace.resolve() + if not working_directory.is_dir(): + raise FileNotFoundError(f"Workspace does not exist: {working_directory}") + readable.append(working_directory) + (nonremovable_writable if protect_workspace_entries else writable).append( + working_directory + ) + writable.extend(removable_workspace_subtrees) + for name, source_path in readonly_mounts.items(): + if not name or Path(name).name != name: + raise ValueError(f"Invalid read-only mount name: {name!r}") + readable.append(source_path.resolve()) + for name, source_path in writable_mounts.items(): + if not name or Path(name).name != name: + raise ValueError(f"Invalid writable mount name: {name!r}") + writable.append(source_path.resolve()) + else: + working_directory = temporary_directory + environment = self._safe_environment( + root=str(runtime), + temporary=str(temporary_directory), + ) + environment.update( + { + "SRH_SANDBOX_INPUT": str(input_directory), + "SRH_SANDBOX_ARRAYS": str(array_directory), + "SRH_SANDBOX_OUTPUT": str(output_directory), + "SRH_SANDBOX_READABLE": json.dumps([str(path) for path in readable]), + "SRH_SANDBOX_WRITABLE": json.dumps([str(path) for path in writable]), + "SRH_SANDBOX_NONREMOVABLE_WRITABLE": json.dumps( + [str(path) for path in nonremovable_writable] + ), + "SRH_SANDBOX_EXECUTABLE": json.dumps([str(path) for path in executable]), + "SRH_SANDBOX_CWD": str(working_directory), + } + ) + return ( + [ + str(runtime / "bin" / "python"), + "-I", + str(source / "sr_harness/runtime/sandbox_worker.py"), + ], + environment, + working_directory, + ) + + @staticmethod + def _terminate(process: subprocess.Popen[bytes]) -> None: + if process.poll() is not None: + return + try: + os.killpg(process.pid, signal.SIGTERM) + except ProcessLookupError: + return + try: + process.wait(timeout=1) + except subprocess.TimeoutExpired: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + + def run_program( + self, + code: str, + *, + stdin: str, + workspace: Workspace | str | Path | None, + timeout_seconds: int, + memory_limit_mb: int, + output_limit_bytes: int, + interruption_event: Event | None, + ) -> SandboxResult: + """Adapt plain Python execution to the private worker protocol.""" + result = self.run_protocol( + operation="code", + request={"program": code, "stdin_text": stdin}, + workspace=workspace, + timeout_seconds=timeout_seconds, + memory_limit_mb=memory_limit_mb, + output_limit_bytes=output_limit_bytes, + interruption_event=interruption_event, + ) + return SandboxResult( + exit_code=int(result.payload.get("exit_code", 0)), + stdout=str(result.payload.get("stdout", "")), + stderr=str(result.payload.get("stderr", "")), + duration_seconds=result.duration_seconds, + cpu_seconds=result.cpu_seconds, + peak_memory_bytes=result.peak_memory_bytes, + ) + + def run_protocol( + self, + *, + operation: str, + request: dict[str, Any], + arrays: dict[str, dict[str, Any]] | None = None, + array_snapshot: _ArraySnapshot | None = None, + workspace: Workspace | str | Path | None = None, + timeout_seconds: int = 30, + memory_limit_mb: int = 1024, + output_limit_bytes: int = 64 * 1024, + interruption_event: Event | None = None, + ) -> _ProtocolResult: + """Run one private protocol request in a confined worker. + + Args: + operation: Worker operation identifier. + request: JSON-compatible operation parameters. + arrays: Named input array groups serialized for this invocation. + array_snapshot: Reusable array snapshot. Mutually exclusive with arrays. + workspace: Managed workspace or plain workspace path. Passing a managed + workspace also applies its mounted-input and lock policies. + timeout_seconds: Wall-clock timeout. + memory_limit_mb: Additional address-space allowance in MB. + output_limit_bytes: Maximum captured Python text output. + interruption_event: Optional signal requesting prompt interruption. + + Returns: + Private structured payload and safely deserialized array results. + """ + with ( + tempfile.TemporaryDirectory(prefix="srh-sandbox-input-") as input_name, + tempfile.TemporaryDirectory(prefix="srh-sandbox-output-") as output_name, + tempfile.TemporaryDirectory(prefix="srh-sandbox-tmp-") as temporary_name, + ): + input_directory = Path(input_name) + output_directory = Path(output_name) + temporary_directory = Path(temporary_name) + (temporary_directory / "home").mkdir() + (temporary_directory / "matplotlib").mkdir() + complete_request = { + **request, + "operation": operation, + "memory_limit_mb": int(memory_limit_mb), + "output_limit_bytes": int(output_limit_bytes), + "timeout_seconds": int(timeout_seconds), + } + (input_directory / "request.json").write_text( + json.dumps(complete_request, ensure_ascii=False), encoding="utf-8" + ) + if arrays is not None and array_snapshot is not None: + raise ValueError("arrays and array_snapshot are mutually exclusive") + if array_snapshot is None: + _write_array_groups(input_directory, arrays or {}) + array_directory = input_directory + else: + array_directory = array_snapshot.root + workspace_manager = workspace if isinstance(workspace, Workspace) else None + resolved_workspace = ( + workspace_manager.path + if workspace_manager is not None + else Path(workspace) if workspace is not None else None + ) + resolved_mounts = { + logical.name: source + for logical, source in ( + workspace_manager.mount_map.items() + if workspace_manager is not None + else () + ) + } + readonly_mounts = { + name: source + for name, source in resolved_mounts.items() + if workspace_manager is not None + and workspace_manager.mount_mode(workspace_manager.path / name) == "read-only" + } + writable_mounts = { + name: source + for name, source in resolved_mounts.items() + if name not in readonly_mounts + } + command, environment, working_directory = self._worker_command( + input_directory=input_directory, + array_directory=array_directory, + output_directory=output_directory, + temporary_directory=temporary_directory, + workspace=resolved_workspace, + readonly_mounts=readonly_mounts, + writable_mounts=writable_mounts, + protect_workspace_entries=bool( + workspace_manager is not None and workspace_manager.has_locks + ), + removable_workspace_subtrees=( + _fully_unlocked_workspace_subtrees(workspace_manager) + if workspace_manager is not None and workspace_manager.has_locks + else [] + ), + ) + start = time.monotonic() + process = subprocess.Popen( + command, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE, + start_new_session=True, + env=environment, + cwd=working_directory, + ) + deadline = start + timeout_seconds + try: + while process.poll() is None: + if interruption_event is not None and interruption_event.is_set(): + self._terminate(process) + raise InterruptedError("Sandbox execution was stopped by the user") + if time.monotonic() >= deadline: + self._terminate(process) + raise TimeoutError( + "Sandbox subprocess did not return result before " + f"timeout={timeout_seconds} seconds and has been terminated." + ) + time.sleep(0.02) + stderr = (process.stderr.read() if process.stderr is not None else b"")[ + :output_limit_bytes + ] + finally: + if process.poll() is None: + self._terminate(process) + duration = time.monotonic() - start + result_file = output_directory / "result.json" + if not result_file.exists(): + detail = stderr.decode("utf-8", errors="replace").strip() + raise SandboxExecutionError( + f"Sandbox worker exited with code {process.returncode} without a result" + + (f": {detail}" if detail else "") + ) + result = json.loads( + _read_regular_bytes( + result_file, + self.RESULT_METADATA_LIMIT, + ).decode("utf-8") + ) + if not isinstance(result, dict): + raise SandboxExecutionError("Sandbox result must be a dictionary") + if error := result.pop("error", None): + raise SandboxExecutionError(str(error)) + usage = result.pop("_sandbox_usage", {}) + return _ProtocolResult( + payload=result, + arrays=_read_array_groups(output_directory), + duration_seconds=duration, + cpu_seconds=float(usage.get("cpu_seconds", 0.0)), + peak_memory_bytes=int(usage.get("peak_memory_bytes", 0)), + ) + + +class SandboxRunner: + """Execute Python code with optional workspace access in the OS sandbox.""" + + def __init__(self) -> None: + self._process_runner = _SandboxProcessRunner() + + def run( + self, + code: str, + *, + stdin: str = "", + workspace: Workspace | str | Path | None = None, + timeout_seconds: int = 30, + memory_limit_mb: int = 1024, + output_limit_bytes: int = 64 * 1024, + interruption_event: Event | None = None, + ) -> SandboxResult: + """Execute a Python program and capture its observable process result. + + Args: + code: Python source code to execute. + stdin: Text exposed as standard input. + workspace: Optional working directory. When omitted, user code receives no + persistent filesystem access. A managed workspace also enforces its + mount and lock policies. + timeout_seconds: Wall-clock timeout. + memory_limit_mb: Address-space memory limit in MB. + output_limit_bytes: Per-stream capture limit for standard output and error. + interruption_event: Optional signal requesting prompt interruption. + + Returns: + Captured process output and resource usage. + """ + return self._process_runner.run_program( + code, + stdin=stdin, + workspace=workspace, + timeout_seconds=timeout_seconds, + memory_limit_mb=memory_limit_mb, + output_limit_bytes=output_limit_bytes, + interruption_event=interruption_event, + ) + + +_DEFAULT_RUNNER: SandboxRunner | None = None + + +def get_sandbox_runner() -> SandboxRunner: + """Return the process-wide sandbox runner.""" + global _DEFAULT_RUNNER + if _DEFAULT_RUNNER is None: + _DEFAULT_RUNNER = SandboxRunner() + return _DEFAULT_RUNNER + + +def _run_sandbox_protocol( + operation: str, + request: dict[str, Any], + *, + arrays: dict[str, dict[str, Any]] | None = None, + array_snapshot: _ArraySnapshot | None = None, + workspace: Workspace | str | Path | None = None, + timeout_seconds: int = 30, + memory_limit_mb: int = 1024, + output_limit_bytes: int = 64 * 1024, + interruption_event: Event | None = None, +) -> _ProtocolResult: + """Run a structured internal protocol for trusted SRHarness adapters.""" + return get_sandbox_runner()._process_runner.run_protocol( + operation=operation, + request=request, + arrays=arrays, + array_snapshot=array_snapshot, + workspace=workspace, + timeout_seconds=timeout_seconds, + memory_limit_mb=memory_limit_mb, + output_limit_bytes=output_limit_bytes, + interruption_event=interruption_event, + ) diff --git a/src/sr_harness/runtime/sandbox_context.py b/src/sr_harness/runtime/sandbox_context.py new file mode 100644 index 0000000000000000000000000000000000000000..b29445d8b2eb6a5034d6d4c026ea4ab3ef7e60fc --- /dev/null +++ b/src/sr_harness/runtime/sandbox_context.py @@ -0,0 +1,49 @@ +"""Serialize the deliberately limited context exposed to untrusted code.""" + +from __future__ import annotations + +import argparse +from typing import Any + + +_UNSUPPORTED = object() +_ALLOWED_ARGUMENTS = { + "larger_is_better", + "ranking_metric", + "split_by", + "split_ood_variable", + "split_random_state", + "validation_fraction", +} + + +def _json_value(value: Any) -> Any: + """Convert a harmless argument value to JSON or mark it unsupported.""" + if value is None or isinstance(value, (str, int, float, bool)): + return value + if isinstance(value, (list, tuple)): + converted = [_json_value(item) for item in value] + return converted if all(item is not _UNSUPPORTED for item in converted) else _UNSUPPORTED + if isinstance(value, dict): + converted = {str(key): _json_value(item) for key, item in value.items()} + if all(item is not _UNSUPPORTED for item in converted.values()): + return converted + return _UNSUPPORTED + + +def sandbox_arguments(args: argparse.Namespace) -> dict[str, Any]: + """Return the evaluator/tool argument whitelist exposed to untrusted code. + + New ``AgentContext.args`` fields are private by default. Provider credentials, + proxy configuration, model settings, callbacks, and session objects therefore + remain in the server process unless this contract is deliberately expanded. + """ + result: dict[str, Any] = {} + for name in _ALLOWED_ARGUMENTS: + if not hasattr(args, name): + continue + value = getattr(args, name) + converted = _json_value(value) + if converted is not _UNSUPPORTED: + result[name] = converted + return result diff --git a/src/sr_harness/runtime/sandbox_worker.py b/src/sr_harness/runtime/sandbox_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..10b063641be1c246f618915ac69e7097d1c758dd --- /dev/null +++ b/src/sr_harness/runtime/sandbox_worker.py @@ -0,0 +1,543 @@ +"""Private entry point executed inside the Landlock sandbox.""" + +from __future__ import annotations + +import argparse +import contextlib +import inspect +import io +import json +import os +import resource +import sys +import traceback +import types +from pathlib import Path +from typing import Any + +import numpy as np + +_SOURCE_ROOT = Path(__file__).resolve().parents[2] +if str(_SOURCE_ROOT) not in sys.path: + sys.path.insert(0, str(_SOURCE_ROOT)) + +# The public package initializer imports model-provider SDKs that are irrelevant +# inside the evaluator sandbox. Register a normal package shell so importing +# trusted evaluator submodules does not execute that broad initializer. +if "sr_harness" not in sys.modules: + package = types.ModuleType("sr_harness") + package.__package__ = "sr_harness" + package.__path__ = [str(_SOURCE_ROOT / "sr_harness")] + sys.modules["sr_harness"] = package + + +class LimitedWriter(io.StringIO): + """Text buffer with a hard character limit.""" + + SUFFIX = "...[truncated]" + + def __init__(self, limit: int) -> None: + super().__init__() + self.limit = limit + + def write(self, text: str) -> int: + remaining = self.limit - self.tell() - len(self.SUFFIX) + if remaining <= 0: + return len(text) + if len(text) > remaining: + super().write(text[:remaining]) + super().write(self.SUFFIX) + return len(text) + return super().write(text) + + +def load_array_groups(root: Path) -> dict[str, dict[str, np.ndarray]]: + """Load trusted parent-produced arrays.""" + manifest = json.loads((root / "arrays.json").read_text(encoding="utf-8")) + return { + group_name: { + name: np.load(root / "arrays" / filename, mmap_mode="c", allow_pickle=False) + for name, filename in values.items() + } + for group_name, values in manifest.items() + } + + +def save_array_groups(root: Path, groups: dict[str, dict[str, Any]]) -> None: + """Save arrays for safe loading by the parent process.""" + array_root = root / "arrays" + array_root.mkdir(exist_ok=True) + manifest: dict[str, dict[str, str]] = {} + index = 0 + for group_name, values in groups.items(): + manifest[group_name] = {} + for name, value in values.items(): + array = np.asarray(value) + if array.dtype.hasobject: + raise TypeError(f"Sandbox result array {name!r} must not use object dtype") + filename = f"array-{index}.npy" + np.save(array_root / filename, array, allow_pickle=False) + manifest[group_name][str(name)] = filename + index += 1 + (root / "arrays.json").write_text(json.dumps(manifest), encoding="utf-8") + + +def apply_resource_limits(request: dict[str, Any]) -> None: + """Apply CPU and address-space limits before executing user code.""" + timeout_seconds = max(1, int(request["timeout_seconds"])) + memory_limit_mb = max(64, int(request["memory_limit_mb"])) + try: + pages = int(Path("/proc/self/statm").read_text().split()[0]) + current_address_space = pages * os.sysconf("SC_PAGE_SIZE") + except Exception: + current_address_space = 0 + memory_bytes = max(memory_limit_mb * 1024 * 1024, current_address_space + 256 * 1024 * 1024) + resource.setrlimit(resource.RLIMIT_AS, (memory_bytes, memory_bytes)) + resource.setrlimit(resource.RLIMIT_DATA, (memory_bytes, memory_bytes)) + resource.setrlimit(resource.RLIMIT_CPU, (timeout_seconds, timeout_seconds + 1)) + resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + file_size_limit = min(memory_limit_mb, 1024) * 1024 * 1024 + resource.setrlimit(resource.RLIMIT_FSIZE, (file_size_limit, file_size_limit)) + resource.setrlimit(resource.RLIMIT_NOFILE, (128, 128)) + + +def execute_program(request: dict[str, Any]) -> dict[str, Any]: + """Execute a general Python program and capture ordinary text streams.""" + stdout = LimitedWriter(int(request["output_limit_bytes"])) + stderr = LimitedWriter(int(request["output_limit_bytes"])) + stdin = io.StringIO(str(request.get("stdin_text", ""))) + namespace = {"__name__": "__sandbox__", "__package__": None} + original_stdin = sys.stdin + exit_code = 0 + try: + sys.stdin = stdin + with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): + try: + exec( + compile(str(request["program"]), "", "exec"), + namespace, + namespace, + ) + except BaseException: + exit_code = 1 + traceback.print_exc(limit=8, file=stderr) + finally: + sys.stdin = original_stdin + return { + "exit_code": exit_code, + "stdout": stdout.getvalue(), + "stderr": stderr.getvalue(), + } + + +def _execute_function( + source: str, + arguments: tuple[Any, ...], + expected_parameters: tuple[str, ...], + namespace: dict[str, Any], + filename: str, +) -> Any: + before = set(namespace) + exec(compile(source, filename, "exec"), namespace, namespace) + functions = [ + value + for name, value in namespace.items() + if name not in before and inspect.isfunction(value) and value.__module__ == "__sandbox__" + ] + matching = [ + function + for function in functions + if tuple(inspect.signature(function).parameters) == expected_parameters + ] + if len(matching) != 1: + expected = ", ".join(expected_parameters) + raise ValueError(f"{filename} must define exactly one function with signature ({expected})") + return matching[0](*arguments) + + +def _format_model(model: Any) -> str: + try: + return str(model["description"]) + except Exception: + try: + return ( + f"{str(model)} (`description` is not provided in model dict, " + "fallback to `str(model)`)" + ) + except Exception: + return ( + f"{repr(model)} (`description` is not provided in model dict, " + "fallback to `repr(model)`)" + ) + + +def evaluate_code( + request: dict[str, Any], arrays: dict[str, dict[str, np.ndarray]], output: Path +) -> dict[str, Any]: + """Fit and evaluate a Python-defined model inside the sandbox.""" + data = arrays["train"] + validation = arrays.get("validation", {}) + namespace: dict[str, Any] = { + "__name__": "__sandbox__", + "__package__": None, + "np": np, + "numpy": np, + } + model = _execute_function( + str(request["model_code"]), (data,), ("data",), namespace, "" + ) + predictions: dict[str, np.ndarray] = {} + prediction_groups = {"train": data, **({"validation": validation} if validation else {})} + predict_source = str(request["predict_code"]) + before = set(namespace) + exec(compile(predict_source, "", "exec"), namespace, namespace) + functions = [ + value + for name, value in namespace.items() + if name not in before + and inspect.isfunction(value) + and value.__module__ == "__sandbox__" + and tuple(inspect.signature(value).parameters) == ("data", "model") + ] + if len(functions) != 1: + raise ValueError( + "predict_code must define exactly one function with signature (data, model)" + ) + predict = functions[0] + for split_name, split_data in prediction_groups.items(): + predictions[split_name] = np.asarray(predict(split_data, model)) + candidate_data = dict(data) + candidate_data.pop(str(request["target"]), None) + try: + np.asarray(predict(candidate_data, model)) + is_candidate = True + except Exception: + is_candidate = False + save_array_groups(output, {"predictions": predictions}) + return {"model_str": _format_model(model), "is_candidate": is_candidate} + + +def _load_evaluator(source: str, filename: str): + """Load exactly one custom evaluator subclass inside the sandbox.""" + from sr_harness.evaluator.default_evaluator import DefaultEvaluator + from sr_harness.evaluator.graph_evaluator import GraphEvaluator + import sr_harness_engine as engine + + package = sys.modules["sr_harness"] + package.DefaultEvaluator = DefaultEvaluator + package.GraphEvaluator = GraphEvaluator + + module_name = f"sr_harness.evaluator.{Path(filename).stem}" + namespace: dict[str, Any] = { + "__name__": module_name, + "__package__": "sr_harness.evaluator", + "__file__": f"/app/sr_harness/evaluator/{Path(filename).name}", + "DefaultEvaluator": DefaultEvaluator, + "GraphEvaluator": GraphEvaluator, + "engine": engine, + "np": np, + "numpy": np, + } + exec(compile(source, namespace["__file__"], "exec", dont_inherit=True), namespace) + classes = [ + value + for value in namespace.values() + if isinstance(value, type) + and value not in {DefaultEvaluator, GraphEvaluator} + and issubclass(value, DefaultEvaluator) + and value.__module__ == module_name + ] + if len(classes) != 1: + raise ValueError("Define exactly one DefaultEvaluator subclass") + return classes[0]() + + +def _load_custom_tool(source: str, filename: str): + """Load exactly one user-authored BaseTool subclass inside the sandbox.""" + from sr_harness.tools.base_tool import BaseTool + + module_name = f"sr_harness.custom_tools.{Path(filename).stem}" + namespace: dict[str, Any] = { + "__name__": module_name, + "__package__": "sr_harness.custom_tools", + "__file__": f"/workspace/skills/{Path(filename).name}", + } + registry_before = dict(BaseTool.REGISTRY_DICT) + try: + exec(compile(source, namespace["__file__"], "exec", dont_inherit=True), namespace) + classes = [ + value + for value in namespace.values() + if isinstance(value, type) + and value is not BaseTool + and issubclass(value, BaseTool) + and value.__module__ == module_name + ] + if len(classes) != 1: + raise ValueError( + f"Custom tool must define exactly one BaseTool subclass, found {len(classes)}." + ) + tool_class = classes[0] + if any(registered is tool_class for registered in BaseTool.REGISTRY_DICT.values()): + raise ValueError( + "Custom tools must not use @BaseTool.register(...); set metadata.name " + "and let the loader register the sandbox proxy." + ) + metadata = tool_class.metadata + if not isinstance(metadata.name, str) or not metadata.name.strip(): + raise ValueError("Custom tool metadata.name must be a non-empty string.") + if not isinstance(metadata.description, str): + raise ValueError("Custom tool metadata.description must be a string.") + if not isinstance(metadata.parameters, dict): + raise ValueError("Custom tool metadata.parameters must be a dictionary.") + return tool_class + finally: + BaseTool.REGISTRY_DICT.clear() + BaseTool.REGISTRY_DICT.update(registry_before) + + +def _tool_evaluator(metadata: dict[str, Any]): + """Reconstruct the evaluator available to a sandboxed custom tool.""" + from sr_harness.evaluator.default_evaluator import DefaultEvaluator + from sr_harness.evaluator.graph_evaluator import GraphEvaluator + + kind = metadata.get("kind", "default") + if kind == "default": + return DefaultEvaluator() + if kind == "graph": + return GraphEvaluator() + if kind == "custom": + return _load_evaluator(str(metadata["source"]), str(metadata["filename"])) + raise ValueError(f"Unknown sandbox evaluator kind: {kind!r}") + + +def _build_tool_context(request: dict[str, Any], data: dict[str, np.ndarray], evaluator): + """Reconstruct the explicitly shared portion of AgentContext.""" + from sr_harness.core import AgentContext + + metadata = request["context"] + args = argparse.Namespace(**metadata.get("args", {})) + return AgentContext( + args=args, + data=data, + target=metadata.get("target"), + variable_descriptions=metadata.get("variable_descriptions"), + variable_axes={ + name: tuple(axes) for name, axes in metadata.get("variable_axes", {}).items() + }, + variable_structures=metadata.get("variable_structures"), + relation_names=set(metadata.get("relation_names", [])), + num_nodes=metadata.get("num_nodes"), + evaluator=evaluator, + workspace=None, + ) + + +def execute_custom_tool( + request: dict[str, Any], arrays: dict[str, dict[str, np.ndarray]] +) -> dict[str, Any]: + """Inspect or execute one custom tool entirely inside the sandbox.""" + from sr_harness.core import json_value + + tool_class = _load_custom_tool(str(request["source"]), str(request["filename"])) + action = str(request["action"]) + if action == "inspect": + return { + "class_name": tool_class.__name__, + "tool_name": tool_class.metadata.name.strip(), + "description": tool_class.metadata.description, + "parameters": tool_class.metadata.parameters, + } + if action != "execute": + raise ValueError(f"Unknown custom-tool action: {action}") + evaluator = _tool_evaluator(dict(request["context"].get("evaluator", {}))) + context = _build_tool_context(request, arrays["context"], evaluator) + tool = tool_class(context=context) + params = request.get("params", {}) + if not isinstance(params, dict): + raise TypeError("Custom tool parameters must be a dictionary") + result = tool.execute(**params) + if not isinstance(result, dict): + raise TypeError("Custom tool execute() must return a dictionary") + return { + "result": json_value(result), + "result_str": str(tool.format_result_dict(result)), + } + + +def _build_evaluator_context(request: dict[str, Any], data: dict[str, np.ndarray], evaluator): + """Reconstruct the minimal AgentContext visible to a custom evaluator.""" + from sr_harness.core import AgentContext + + metadata = request["context"] + args = argparse.Namespace(**metadata.get("args", {})) + return AgentContext( + args=args, + data=data, + target=metadata.get("target"), + variable_descriptions=metadata.get("variable_descriptions"), + variable_axes={ + name: tuple(axes) for name, axes in metadata.get("variable_axes", {}).items() + }, + variable_structures=metadata.get("variable_structures"), + relation_names=set(metadata.get("relation_names", [])), + num_nodes=metadata.get("num_nodes"), + evaluator=evaluator, + workspace=None, + ) + + +def execute_evaluator( + request: dict[str, Any], arrays: dict[str, dict[str, np.ndarray]], output: Path +) -> dict[str, Any]: + """Load a custom evaluator and perform one protocol operation.""" + import sr_harness_engine as engine + + evaluator = _load_evaluator(str(request["source"]), str(request["filename"])) + action = str(request["action"]) + if action == "inspect": + class_attributes = { + name: value + for name, value in vars(type(evaluator)).items() + if not name.startswith("_") and isinstance(value, (str, int, float, bool, type(None))) + } + return { + "class_name": type(evaluator).__name__, + "class_attributes": class_attributes, + } + context = _build_evaluator_context(request, arrays["context"], evaluator) + if action == "split": + splits = evaluator.split(context) + if set(splits) != {"train", "validation"}: + raise ValueError("Custom evaluator split() must return train and validation contexts") + save_array_groups(output, {name: split.data for name, split in splits.items()}) + return {} + expression = engine.parse(str(request["f"])) + target_expression = engine.parse(str(request["y"])) if request.get("y") is not None else None + candidate = bool(request.get("candidate")) + if action == "evaluate-formula": + splits = evaluator.split(context) + if set(splits) != {"train", "validation"}: + raise ValueError("Custom evaluator split() must return train and validation contexts") + fitted = expression + if request.get("fit"): + fitted = ( + evaluator.fit_candidate(expression, splits["train"]) + if candidate + else evaluator.fit(expression, target_expression, splits["train"]) + ) + metrics: dict[str, dict[str, float | int]] = {} + for split_name, split_context in splits.items(): + values = ( + evaluator.evaluate_candidate(fitted, split_context) + if candidate + else evaluator.evaluate(fitted, target_expression, split_context) + ) + if not isinstance(values, dict): + raise TypeError("Custom evaluator evaluate operation must return a dictionary") + normalized: dict[str, float | int] = {} + for name, value in values.items(): + if isinstance(value, (bool, np.bool_)) or not isinstance( + value, (int, float, np.integer, np.floating) + ): + raise TypeError(f"Evaluator metric {name!r} must be a float or int") + normalized[str(name)] = value.item() if isinstance(value, np.generic) else value + metrics[split_name] = normalized + save_array_groups(output, {name: split.data for name, split in splits.items()}) + return { + "expression": fitted.to_str(number_format=".17g"), + "metrics": metrics, + } + if action == "fit": + fitted = ( + evaluator.fit_candidate(expression, context) + if candidate + else evaluator.fit(expression, target_expression, context) + ) + if not isinstance(fitted, engine.Expression): + raise TypeError("Custom evaluator fit operation must return an Expression") + return {"expression": fitted.to_str(number_format=".17g")} + if action == "evaluate": + metrics = ( + evaluator.evaluate_candidate(expression, context) + if candidate + else evaluator.evaluate(expression, target_expression, context) + ) + if not isinstance(metrics, dict): + raise TypeError("Custom evaluator evaluate operation must return a dictionary") + normalized: dict[str, float | int] = {} + for name, value in metrics.items(): + if isinstance(value, (bool, np.bool_)) or not isinstance( + value, (int, float, np.integer, np.floating) + ): + raise TypeError(f"Evaluator metric {name!r} must be a float or int") + normalized[str(name)] = value.item() if isinstance(value, np.generic) else value + return {"metrics": normalized} + raise ValueError(f"Unknown evaluator action: {action}") + + +def _configure_sandbox() -> tuple[Path, Path, Path]: + """Consume launcher metadata and confine this worker before user imports.""" + input_root = Path(os.environ.pop("SRH_SANDBOX_INPUT")) + array_root = Path(os.environ.pop("SRH_SANDBOX_ARRAYS")) + output_root = Path(os.environ.pop("SRH_SANDBOX_OUTPUT")) + readable = json.loads(os.environ.pop("SRH_SANDBOX_READABLE")) + writable = json.loads(os.environ.pop("SRH_SANDBOX_WRITABLE")) + nonremovable_writable = json.loads(os.environ.pop("SRH_SANDBOX_NONREMOVABLE_WRITABLE")) + executable = json.loads(os.environ.pop("SRH_SANDBOX_EXECUTABLE")) + working_directory = Path(os.environ.pop("SRH_SANDBOX_CWD")) + from sr_harness.runtime.landlock import restrict_filesystem, restrict_system_calls + + restrict_filesystem( + readable=readable, + writable=writable, + nonremovable_writable=nonremovable_writable, + executable=executable, + ) + restrict_system_calls() + os.chdir(working_directory) + return input_root, output_root, array_root + + +def _sandbox_paths() -> tuple[Path, Path, Path]: + """Return protocol paths before the syscall filter is installed.""" + return ( + Path(os.environ["SRH_SANDBOX_INPUT"]), + Path(os.environ["SRH_SANDBOX_OUTPUT"]), + Path(os.environ["SRH_SANDBOX_ARRAYS"]), + ) + + +def main() -> None: + """Dispatch one trusted request and persist a JSON result.""" + input_root, output_root, _ = _sandbox_paths() + result_file = output_root / "result.json" + try: + request = json.loads((input_root / "request.json").read_text(encoding="utf-8")) + apply_resource_limits(request) + _, _, array_root = _configure_sandbox() + arrays = load_array_groups(array_root) + operation = request["operation"] + if operation in {"code", "workspace-code"}: + result = execute_program(request) + elif operation == "evaluate-code": + result = evaluate_code(request, arrays, output_root) + elif operation == "evaluator": + result = execute_evaluator(request, arrays, output_root) + elif operation == "custom-tool": + result = execute_custom_tool(request, arrays) + else: + raise ValueError(f"Unknown sandbox operation: {operation}") + usage = resource.getrusage(resource.RUSAGE_SELF) + result["_sandbox_usage"] = { + "cpu_seconds": usage.ru_utime + usage.ru_stime, + "peak_memory_bytes": int(usage.ru_maxrss) * 1024, + } + result_file.write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8") + except BaseException as exc: + error = f"{type(exc).__name__}: {exc}\n{traceback.format_exc(limit=8)}" + result_file.write_text(json.dumps({"error": error}, ensure_ascii=False), encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/src/sr_harness/runtime/workspace.py b/src/sr_harness/runtime/workspace.py new file mode 100644 index 0000000000000000000000000000000000000000..d1aeb3479bd5fff9a3c9e4fef22a923bf278793e --- /dev/null +++ b/src/sr_harness/runtime/workspace.py @@ -0,0 +1,686 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""Persistent workspace management for interactive SRHarness sessions.""" + +from __future__ import annotations + +import logging +import io +import os +import shutil +import stat +import ctypes +from collections.abc import Iterator +from pathlib import Path +from typing import IO, Literal + +from ..utils.openat2 import open_beneath +from ..utils import log_exception + +_logger = logging.getLogger(__name__) + +_LIBC = ctypes.CDLL(None, use_errno=True) +_RENAME_NOREPLACE = 1 + + +class Workspace: + """Manage a writable workspace with explicitly registered read-only inputs.""" + + def __init__( + self, + path: str | Path, + *, + read_only: bool = False, + ) -> None: + """Create or open a workspace. + + Args: + path: Existing or new workspace root. The caller owns the directory and + decides where it is created and when it is removed. + """ + self._path = Path(path).resolve() + self._read_only = bool(read_only) + if self._read_only: + if not self._path.is_dir(): + raise FileNotFoundError(f"Read-only workspace does not exist: {self._path}") + else: + self._path.mkdir(parents=True, exist_ok=True) + self._mount_map: dict[Path, Path] = {} + self._readonly_mounts: set[Path] = set() + self._lock_rules: dict[Path, bool] = {} + _logger.info(f"Initialized workspace at {self._path}") + + @property + def path(self) -> Path: + """Return the workspace root.""" + return self._path + + @property + def read_only(self) -> bool: + """Return whether every workspace mutation is disabled.""" + return self._read_only + + @property + def mount_map(self) -> dict[Path, Path]: + """Return logical workspace mount points mapped to their host sources.""" + return dict(self._mount_map) + + def mount_mode(self, path: str | Path) -> Literal["read-only", "read-write"] | None: + """Return the registered mount mode containing a logical workspace path. + + Args: + path: Absolute or workspace-relative logical path. + + Returns: + ``"read-only"`` or ``"read-write"`` for a mounted path, otherwise + ``None``. + """ + logical = Path(path) + if not logical.is_absolute(): + logical = self._path / logical + try: + logical.relative_to(self._path) + except ValueError: + raise ValueError("Mount queries must refer to a logical workspace path") from None + for root in (logical, *logical.parents): + if root in self._mount_map: + return "read-only" if root in self._readonly_mounts else "read-write" + if root == self._path: + break + return None + + @property + def lock_rules(self) -> dict[str, bool]: + """Return explicit lock overrides keyed by workspace-relative paths.""" + return { + str(path.relative_to(self._path)): locked + for path, locked in self._lock_rules.items() + } + + @property + def has_locks(self) -> bool: + """Return whether any path is effectively protected by a lock rule.""" + return any(self._lock_rules.values()) + + def is_locked(self, path: str | Path) -> bool: + """Return the effective lock state after applying the nearest override.""" + logical = Path(path) + if not logical.is_absolute(): + logical = self._path / logical + try: + logical.relative_to(self._path) + except ValueError: + raise ValueError("Lock queries must refer to a logical workspace path") from None + for candidate in (logical, *logical.parents): + if candidate == self._path.parent: + break + if candidate in self._lock_rules: + return self._lock_rules[candidate] + if candidate == self._path: + break + return False + + def contains_locked_paths(self, path: str | Path) -> bool: + """Return whether a path is or contains an explicitly locked subtree.""" + logical = Path(path) + if not logical.is_absolute(): + logical = self._path / logical + try: + logical.relative_to(self._path) + except ValueError: + raise ValueError("Lock queries must refer to a logical workspace path") from None + return self.is_locked(logical) or any( + locked and logical in rule.parents + for rule, locked in self._lock_rules.items() + ) + + def set_locked(self, relative_path: str, locked: bool) -> Path: + """Set an explicit lock rule on a workspace file or directory tree. + + Args: + relative_path: Workspace-relative file or directory path. + locked: Lock the path when true or explicitly unlock it when false. + + Returns: + The affected workspace path. + + Raises: + ValueError: If the path is invalid, missing, or belongs to a mounted input. + """ + path = self.resolve(relative_path) + if path is None or not path.exists(): + raise ValueError(f"File or directory not found: {relative_path}") + logical = self._path / Path(relative_path) + if self.mount_mode(logical) is not None: + raise ValueError("Mounted inputs cannot be locked or unlocked") + descendants = [rule for rule in self._lock_rules if logical in rule.parents] + for rule in descendants: + del self._lock_rules[rule] + inherited = self.is_locked(logical.parent) + if locked == inherited: + self._lock_rules.pop(logical, None) + else: + self._lock_rules[logical] = locked + self._apply_lock_permissions() + return path + + def load_lock_rules(self, rules: dict[str, bool]) -> None: + """Replace lock overrides from persisted workspace state. + + Args: + rules: Workspace-relative paths mapped to explicit lock states. + """ + parsed: dict[Path, bool] = {} + for relative_path, locked in rules.items(): + if not isinstance(relative_path, str) or not isinstance(locked, bool): + raise TypeError("Workspace lock rules must map path strings to booleans") + requested = Path(relative_path) + if requested.is_absolute() or not requested.parts or ".." in requested.parts: + raise ValueError(f"Invalid workspace lock path: {relative_path!r}") + logical = self._path / requested + if not logical.exists() or logical.is_symlink() or self.mount_mode(logical) is not None: + raise ValueError(f"Workspace lock path is unavailable: {relative_path!r}") + parsed[logical] = locked + self._lock_rules = parsed + self._apply_lock_permissions() + + def _apply_lock_permissions(self) -> None: + """Apply explicit lock rules through stable descriptors without following links.""" + if self._read_only: + return + mount_roots = set(self._mount_map) + paths = [self._path] + for current_name, directory_names, file_names in os.walk( + self._path, + followlinks=False, + ): + current = Path(current_name) + directory_names[:] = [ + name + for name in directory_names + if (current / name) not in mount_roots + and not (current / name).is_symlink() + ] + paths.extend(current / name for name in directory_names) + paths.extend( + current / name + for name in file_names + if (current / name) not in mount_roots + and not (current / name).is_symlink() + ) + for path in reversed(paths): + relative = path.relative_to(self._path) + try: + descriptor = open_beneath( + self._path, + relative, + disallow_symlinks=True, + flags=os.O_RDONLY | os.O_CLOEXEC, + ) + except FileNotFoundError: + continue + try: + mode = stat.S_IMODE(os.fstat(descriptor).st_mode) + updated = mode & ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH) + if not self.is_locked(path): + updated |= stat.S_IWUSR + os.fchmod(descriptor, updated) + finally: + os.close(descriptor) + + def resolve( + self, + relative_path: str, + *, + access: Literal["read", "write", "create", "remove"] = "read", + ) -> Path | None: + """Resolve a safe workspace-relative path. + + Args: + relative_path: Relative path supplied by the caller. + access: Intended operation. ``write`` changes existing content, ``create`` + adds a new entry, and ``remove`` deletes, moves, or replaces an + existing entry. + + Returns: + The resolved path, or ``None`` when the requested access is invalid. + """ + if access not in {"read", "write", "create", "remove"}: + raise ValueError(f"Unknown workspace access intent: {access}") + if self._read_only and access != "read": + return None + if not relative_path: + return self._path + if os.path.isabs(relative_path): + return None + if len(relative_path) >= 2 and relative_path[0].isalpha() and relative_path[1] == ":": + return None + requested = Path(relative_path) + if ".." in requested.parts: + return None + logical = self._path / requested + if requested.parts: + mount = self._path / requested.parts[0] + if source := self._mount_map.get(mount): + if access != "read" and mount in self._readonly_mounts: + return None + if access == "remove" and len(requested.parts) == 1: + return None + if source.is_file() and len(requested.parts) > 1: + return None + candidate = ( + (source / Path(*requested.parts[1:])).resolve() + if source.is_dir() + else source + ) + try: + candidate.relative_to(source if source.is_dir() else source.parent) + except ValueError: + return None + return candidate + if access != "read": + logical_component = self._path + for index, component in enumerate(requested.parts): + logical_component /= component + if logical_component.is_symlink(): + if access == "remove" and index == len(requested.parts) - 1: + return None if self.is_locked(logical_component) else logical_component + return None + candidate = logical.resolve() + try: + candidate.relative_to(self._path.resolve()) + except ValueError: + return None + if access != "read": + if access == "create": + probe = candidate.parent + while not probe.exists() and probe != self._path: + probe = probe.parent + logical_probe = self._path / probe.relative_to(self._path) + if probe.exists() and self.is_locked(logical_probe): + return None + return candidate + if candidate.exists() and self.is_locked(logical): + return None + if access == "remove" and self.contains_locked_paths(logical): + return None + if not candidate.exists(): + probe = candidate.parent + while not probe.exists() and probe != self._path: + probe = probe.parent + else: + probe = candidate + logical_probe = self._path / probe.relative_to(self._path) + if probe.exists() and self.is_locked(logical_probe): + return None + return candidate + + def safe_open( + self, + path: str | Path, + mode: Literal["r", "rb"] = "r", + *, + encoding: str | None = None, + errors: str | None = None, + ) -> IO: + """Open a readable file atomically within an authorized workspace root.""" + if mode not in {"r", "rb"}: + raise ValueError("safe_open only supports 'r' and 'rb'") + if mode == "rb" and (encoding is not None or errors is not None): + raise ValueError("binary mode doesn't take an encoding or errors argument") + requested = Path(path).expanduser() + if not requested.is_absolute(): + requested = Path.cwd() / requested + resolved = requested.resolve(strict=True) + try: + relative_path = resolved.relative_to(self._path) + except ValueError: + descriptor = None + else: + descriptor = open_beneath(self._path, relative_path) + if descriptor is None: + for source in self._mount_map.values(): + if source.is_file(): + if resolved == source: + descriptor = open_beneath( + source.parent, + source.name, + disallow_symlinks=True, + ) + break + continue + try: + relative_path = resolved.relative_to(source) + except ValueError: + continue + descriptor = open_beneath(source, relative_path) + break + if descriptor is None: + raise PermissionError(f"Path is outside the workspace: {path}") + raw = io.FileIO(descriptor, mode="rb", closefd=True) + if mode == "rb": + return raw + return io.TextIOWrapper(raw, encoding=encoding, errors=errors) + + def create_directory( + self, + relative_path: str, + *, + parents: bool = False, + exist_ok: bool = False, + ) -> Path: + """Create a directory without following mutable workspace symlinks. + + Args: + relative_path: Workspace-relative directory path. + parents: Create missing parent directories as needed. + exist_ok: Do not fail if the final directory already exists. + + Returns: + The logical path of the created directory. + """ + requested = self._relative_mutation_path(relative_path) + if requested == Path("."): + if exist_ok: + return self._path + raise FileExistsError(relative_path) + root, relative, logical = self._mutation_route(relative_path, access="create") + components = relative.parts + if not components: + if exist_ok: + return logical + raise FileExistsError(relative_path) + descriptor = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC) + try: + for index, component in enumerate(components): + final = index == len(components) - 1 + try: + os.mkdir(component, dir_fd=descriptor) + except FileExistsError: + if final and not exist_ok: + raise + if not parents and not final: + raise + if not final: + next_descriptor = os.open( + component, + os.O_RDONLY + | os.O_DIRECTORY + | os.O_CLOEXEC + | getattr(os, "O_NOFOLLOW", 0), + dir_fd=descriptor, + ) + os.close(descriptor) + descriptor = next_descriptor + finally: + os.close(descriptor) + return logical + + def open_for_write( + self, + relative_path: str, + mode: Literal["w", "wb", "x", "xb"] = "w", + *, + encoding: str | None = None, + errors: str | None = None, + ) -> IO: + """Open a workspace file for writing without following symbolic links. + + Args: + relative_path: Workspace-relative file path. + mode: Truncating or exclusive text/binary write mode. + encoding: Text encoding used by text modes. + errors: Text encoding error strategy used by text modes. + + Returns: + An open stream owned by the caller. + """ + if mode not in {"w", "wb", "x", "xb"}: + raise ValueError("open_for_write only supports 'w', 'wb', 'x', and 'xb'") + existing = self.resolve(relative_path) + access = "write" if existing is not None and existing.exists() else "create" + _, parent_fd, name, _ = self._open_mutation_parent(relative_path, access=access) + flags = os.O_WRONLY | os.O_CREAT | os.O_CLOEXEC | getattr(os, "O_NOFOLLOW", 0) + flags |= os.O_EXCL if "x" in mode else os.O_TRUNC + try: + descriptor = os.open(name, flags, 0o666, dir_fd=parent_fd) + finally: + os.close(parent_fd) + binary = os.fdopen(descriptor, "wb") + if "b" in mode: + if encoding is not None or errors is not None: + binary.close() + raise ValueError("binary mode doesn't take an encoding or errors argument") + return binary + import io + return io.TextIOWrapper(binary, encoding=encoding, errors=errors) + + def replace_file(self, source: str | Path, destination: str) -> Path: + """Atomically replace a workspace file with a caller-owned staging file.""" + existing = self.resolve(destination) + access = "write" if existing is not None and existing.exists() else "create" + _, parent_fd, name, logical = self._open_mutation_parent(destination, access=access) + try: + os.replace(source, name, dst_dir_fd=parent_fd) + finally: + os.close(parent_fd) + return logical + + def install(self, source: str | Path, destination: str) -> Path: + """Atomically install a caller-owned file or directory without overwriting.""" + source = Path(source) + if not source.is_absolute(): + source = Path.cwd() / source + _, destination_fd, destination_name, logical = self._open_mutation_parent( + destination, + access="create", + ) + try: + self._rename_no_replace( + getattr(os, "AT_FDCWD", -100), + os.fspath(source), + destination_fd, + destination_name, + ) + finally: + os.close(destination_fd) + return logical + + def move(self, source: str, destination: str, *, overwrite: bool = False) -> Path: + """Move a workspace entry using stable source and destination parents.""" + source_relative = self._relative_mutation_path(source) + destination_relative = self._relative_mutation_path(destination) + if source_relative == Path(".") or destination_relative == Path("."): + raise ValueError("The workspace root cannot be moved or replaced") + if source_relative in destination_relative.parents: + raise ValueError("A directory cannot be moved inside itself") + _, source_fd, source_name, _ = self._open_mutation_parent(source, access="remove") + destination_probe = self.resolve(destination) + destination_access = ( + "remove" + if overwrite and destination_probe is not None and destination_probe.exists() + else "create" + ) + _, destination_fd, destination_name, destination_logical = self._open_mutation_parent( + destination, + access=destination_access, + ) + try: + if overwrite: + os.rename( + source_name, + destination_name, + src_dir_fd=source_fd, + dst_dir_fd=destination_fd, + ) + else: + self._rename_no_replace( + source_fd, + source_name, + destination_fd, + destination_name, + ) + finally: + os.close(source_fd) + os.close(destination_fd) + return destination_logical + + def remove(self, relative_path: str, *, recursive: bool = False, missing_ok: bool = False) -> None: + """Remove a workspace entry without following symbolic links.""" + _, parent_fd, name, _ = self._open_mutation_parent(relative_path, access="remove") + try: + try: + metadata = os.stat(name, dir_fd=parent_fd, follow_symlinks=False) + except FileNotFoundError: + if missing_ok: + return + raise + if stat.S_ISDIR(metadata.st_mode): + if not recursive: + raise IsADirectoryError(relative_path) + shutil.rmtree(name, dir_fd=parent_fd) + else: + os.unlink(name, dir_fd=parent_fd) + finally: + os.close(parent_fd) + + def _relative_mutation_path(self, relative_path: str) -> Path: + if not relative_path: + return Path(".") + if os.path.isabs(relative_path): + raise ValueError(f"Invalid workspace path: {relative_path}") + if len(relative_path) >= 2 and relative_path[0].isalpha() and relative_path[1] == ":": + raise ValueError(f"Invalid workspace path: {relative_path}") + requested = Path(relative_path) + if ".." in requested.parts: + raise ValueError(f"Invalid workspace path: {relative_path}") + return requested + + def _mutation_route( + self, + relative_path: str, + *, + access: Literal["write", "create", "remove"], + ) -> tuple[Path, Path, Path]: + if self._read_only: + raise PermissionError("Workspace is read-only") + requested = self._relative_mutation_path(relative_path) + logical = self._path / requested + if requested.parts and (mount := self._path / requested.parts[0]) in self._mount_map: + if mount in self._readonly_mounts: + raise PermissionError("Mounted input is read-only") + if access == "remove" and len(requested.parts) == 1: + raise PermissionError("A mounted workspace entry cannot be removed") + source = self._mount_map[mount] + if source.is_file(): + if len(requested.parts) != 1: + raise ValueError(f"Invalid mounted file path: {relative_path}") + return source.parent, Path(source.name), logical + return source, Path(*requested.parts[1:]), logical + if access == "create": + if self.is_locked(logical): + raise PermissionError(f"Workspace path is locked: {relative_path}") + probe = logical.parent + while probe != self._path and not probe.exists(): + probe = probe.parent + if self.is_locked(probe): + raise PermissionError(f"Workspace path is locked: {relative_path}") + else: + if self.is_locked(logical): + raise PermissionError(f"Workspace path is locked: {relative_path}") + if access == "remove" and self.is_locked(logical.parent): + raise PermissionError( + f"Workspace parent directory is locked: {relative_path}" + ) + if access == "remove" and self.contains_locked_paths(logical): + raise PermissionError(f"Workspace path contains locked entries: {relative_path}") + return self._path, requested, logical + + def _open_mutation_parent( + self, + relative_path: str, + *, + access: Literal["write", "create", "remove"], + ) -> tuple[Path, int, str, Path]: + root, relative, logical = self._mutation_route(relative_path, access=access) + if relative == Path(".") or not relative.name: + raise ValueError("The workspace root cannot be modified") + descriptor = open_beneath( + root, + relative.parent, + disallow_symlinks=True, + flags=os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC, + ) + return root, descriptor, relative.name, logical + + @staticmethod + def _rename_no_replace(source_fd: int, source: str, destination_fd: int, destination: str) -> None: + result = _LIBC.renameat2( + source_fd, + os.fsencode(source), + destination_fd, + os.fsencode(destination), + _RENAME_NOREPLACE, + ) + if result != 0: + code = ctypes.get_errno() + raise OSError(code, os.strerror(code), destination) + + def mount(self, source: str | Path, *, readonly: bool = True) -> Path: + """Expose a host file or directory through a registered link. + + Args: + source: Existing host file or directory. + readonly: Whether workspace operations and sandboxed code may modify it. + + Returns: + The logical link inside the workspace. + """ + if self._read_only: + raise PermissionError("Workspace is read-only") + source = Path(source).expanduser().resolve() + if not source.exists(): + raise FileNotFoundError(f"Workspace input does not exist: {source}") + destination = self._path / source.name + if destination.is_symlink() and destination.resolve() == source: + self._mount_map[destination] = source + if readonly: + self._readonly_mounts.add(destination) + else: + self._readonly_mounts.discard(destination) + return destination + if destination.exists() or destination.is_symlink(): + raise FileExistsError( + f"Workspace input name {destination.name!r} is already in use; " + "rename one of the conflicting inputs." + ) + try: + os.symlink(source, destination, target_is_directory=source.is_dir()) + self._mount_map[destination] = source + if readonly: + self._readonly_mounts.add(destination) + except Exception as exc: + _logger.error( + f"Failed to add {source} to workspace: " + f"{log_exception(exc, with_traceback=False)}" + ) + raise + return destination + + def iter_files(self) -> Iterator[tuple[Path, Path]]: + """Yield logical and resolved paths for every workspace file.""" + mounted = set(self._mount_map) + for item in self._path.rglob("*"): + if any(parent in mounted for parent in (item, *item.parents)): + continue + if item.is_symlink(): + continue + if item.is_file(): + yield item.relative_to(self._path), item + for logical, source in self._mount_map.items(): + prefix = Path(logical.name) + if source.is_file(): + yield prefix, source + else: + for item in source.rglob("*"): + if item.is_file(): + yield prefix / item.relative_to(source), item diff --git a/src/sr_harness/skills/__init__.py b/src/sr_harness/skills/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..35e171d28c672279db31b2c0609cf2fe0e2e3245 --- /dev/null +++ b/src/sr_harness/skills/__init__.py @@ -0,0 +1 @@ +from .skill_manager import Skill, SkillManager \ No newline at end of file diff --git a/src/sr_harness/skills/discover-symbolic-laws/SKILL.md b/src/sr_harness/skills/discover-symbolic-laws/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..52e37718b6be9eb66bdbd1e0df50374bd9953e28 --- /dev/null +++ b/src/sr_harness/skills/discover-symbolic-laws/SKILL.md @@ -0,0 +1,344 @@ +--- +name: discover-symbolic-laws +description: Use this skill when solving a symbolic-regression problem from tabular numerical data, especially when direct formula guesses fail, predictive accuracy has not yielded a compact law, or numerical evidence is needed to choose transformations and discovery tools. +--- + +# Discover Symbolic Laws + +Treat symbolic regression as iterative scientific diagnosis. Make each computation answer one structural question, and distinguish a diagnostic surrogate from a final symbolic law. + +## Keep evidence compact + +- Compute over all samples inside a tool or script; return summaries only. +- Print shapes, domain flags, robust quantiles, fitted coefficients, stability, top candidates, and residual metrics. Do not print full arrays or feature libraries. +- Inspect at most 5–10 rows selected by an explicit rule such as largest residual or smallest candidate denominator. +- Bound candidate tables at 5–10 entries. Preserve the best compact formula before an expensive branch. +- Use deterministic random seeds and restrict BLAS threads when custom code invokes heavy numerical libraries. + +## Run the discovery loop + +### 1. Audit marginal distributions + +Establish finite coverage, signs, zero proximity, robust quantiles, mean, variance, dynamic range, and whether absolute, relative, or log error is informative. + +Start with: + +```text +statistics_analysis(n_bins=10, near_zero_threshold=1e-8) +``` + +Request expression statistics when testing a transformation: + +```text +statistics_analysis(variables=["y*x2", "log(y)"]) +``` + +Use a log only on a valid domain. If values cross zero, consider `sign(z)*log1p(abs(z))`, separate sign and magnitude, or an evidence-backed shift. +In SRHarness formulas, `log` (and its alias `ln`) is the natural logarithm. Use `log10`/`lg` or `log2` when base 10 or base 2 is intended. + +If `statistics_analysis` is unavailable and `code_executor` is available, run a bounded audit such as: + +```python +import numpy as np +# `data` denotes the dictionary supplied to the execution program. +for name, a in data.items(): + a = np.asarray(a, float).ravel() + finite = np.isfinite(a) + z = a[finite] + q = np.quantile(z, [0, .01, .25, .5, .75, .99, 1]) + print(name, "n", len(a), "finite", round(finite.mean(), 4), + "negative", round(np.mean(z < 0), 4), + "near_zero", round(np.mean(np.abs(z) <= 1e-8), 4), + "quantiles", np.round(q, 6).tolist(), + "mean", float(np.mean(z)), "std", float(np.std(z))) +``` + +### 2. Analyze relationships and collapse + +Call: + +```text +relationship_analysis( + variables=["x1", "x2", "x1/x2"], y="y", n_bins=5, + n_folds=5, collapse_model="bins" +) +``` + +Use feature-target Pearson/Spearman values, conditional target bins, and five-fold held-out bin-mean prediction scores to compare candidate coordinates. Enable `pairwise=true` only when predictor-predictor relationships matter; its output grows quadratically. + +Treat high in-sample but weak held-out collapse as overfitting. Try `collapse_model="spline"` for a smooth nonmonotone curve and `"isotonic"` for a monotone probe. These are structural probes, not final formulas. + +Pearson and Spearman both being weak does not prove irrelevance. Before removing a variable, inspect nonlinear relevance, nonmonotone shapes, and combinations such as sums, differences, products, ratios, or angular differences. + +### 3. Classify plausible structure + +Test cheap families before broad search: + +- additive or low-degree polynomial; +- multiplicative power law; +- rational, saturating, or singular; +- exponential or logarithmic; +- periodic or angular; +- separable or low-dimensional composite. + +Use behavior, not names. Large positive dynamic range suggests `log(y)`. A stable log-log slope suggests a power. Blow-up near small `xi` suggests inverse powers. Saturation suggests a rational or exponential approach to a limit. Repeated zero crossings suggest a periodic coordinate. + +After a one-dimensional collapse, inspect values near zero, extrema, poles, saturation levels, and both observed-range endpoints. Prefer `expm1(z)` over `exp(z)-1` near zero. + +### 4. Search for invariants and eliminate variables + +Test transformations that may become constant or reduce dimension: + +```text +y*g(xi), y/g(xi), log(abs(y))-log(abs(g(xi))) +y*product(xi**pi), residual/g(xi), residual*g(xi) +``` + +Use: + +```text +statistics_analysis(variables=["y*x1", "y*x1/x2", "y*x2/x1"]) +relationship_analysis(variables=["x1/(x3*x4)"], y="y*x2") +``` + +`statistics_analysis` can inspect several proposed invariants in one call. Compare their finite-sample coverage, range, median, variance, and spread; a stable mean alone does not establish an invariant. + +### 5. Linearize the selected hypothesis + +- Fit a multiplicative law with `power_law_fit(x=["x1", "x2"], y="y")`. +- Request snapping only after raw exponents are stable: `power_law_fit(..., snap_exponents=true, snap_tolerance=0.03)`. +- Inspect both raw and snapped candidates; accept snapping only when the tool reports `snap_accepted=true`. +- Fit a rational grid when shape evidence suggests a pole or saturation: + +```text +rational_fit( + x=["x1"], y="y", + numerator_degrees=[0,1,2], denominator_degrees=[0,1,2], + validation_fraction=0.2, top_k=5 +) +``` + +- Reject high-degree candidates with weak held-out improvement, ill conditioning, or dangerous denominator quantiles. +- Fit transformed additive models with `polynomial_fit`, `call_sindy`, or a small custom design matrix. +- For positive variables, try `call_sindy(y="log(y)", x=["log(x1)", "log(x2)", "log(x3)"], poly_degree=1, include_trig=false, threshold=0.01)`. +- Use SINDy for a modest sparse library. Use PySR only after narrowing variables, operators, and target transformations. + +Do not infer a law from correlation alone. Screen on a deterministic subset, select structure on held-out data, refit constants on all samples, then run the final evaluator. + +### 6. Analyze residual structure + +For each serious candidate, call: + +```text +evaluate_formula(f="candidate", show_diagnostics=true) +``` + +Inspect absolute and relative residual quantiles, extreme rows, finite coverage, and residual dependence. If residual structure remains, revise the factorization or discover the residual recursively. Fit a dominant additive term, subtract it, and repeat. + +Test exchange symmetry or antisymmetry between similarly distributed variables. Natural coordinates often appear as `xi+xj`, `xi-xj`, `xi*xj`, `xi/xj`, or angular differences. + +When errors concentrate near a zero or pole, distinguish a missing singular factor from finite-precision generation or an unstable algebraic form before adding polynomial terms. + +### 7. Recover exact structure + +- Snap exponents only when subset stability, snap distance, and full-data degradation all support it. +- When a proposed formula already contains numerical constants, use `constant_fit(eq="proposed_formula", y="y")` to compare nearby simple replacements at each numeric position. +- Inspect the Pareto front of R2 and Constant-Complexity; `constant_fit` does not fit a missing scalar or search for structure. Evaluate the selected replacement as a complete formula before submission. +- Prefer fewer operations when errors are indistinguishable. + +### 8. Validate and submit + +Separate discovery metrics from the final metric: + +- Use rank, trimmed, signed-log, relative, log, or collapse scores to reveal structure. +- Use the benchmark's original-domain metric and all valid samples to choose the final formula. +- Check extrema, near-zero targets, singular regions, and finite prediction coverage. + +Submit only after residuals are structureless at expected numerical precision, or explicitly retain the best compact approximation. Stop dense polynomial, Chebyshev, or genetic-programming branches when expression size grows faster than held-out improvement. + +## Custom diagnostic recipes + +Use these only when the corresponding specialized tool is absent or insufficient. Use `code_executor` **if available**. Adapt how the execution environment exposes `data`; keep output bounded. + +### Analyze one-dimensional shape + +Principle: after proposing a coordinate `z`, estimate whether `y=f(z)` generalizes, then inspect monotonicity, turning points, and local log-log elasticity. A flexible curve is evidence of dimensional collapse, not the final answer. + +```python +import numpy as np +from scipy.interpolate import UnivariateSpline +rng = np.random.default_rng(0) +z = np.asarray(data["x1"], float).ravel() +y = np.asarray(data["y"], float).ravel() +ok = np.isfinite(z) & np.isfinite(y) +z, y = z[ok], y[ok] +order = rng.permutation(len(y)); cut = int(.8*len(y)) +tr, te = order[:cut], order[cut:] +sort = np.argsort(z[tr]); zs, ys = z[tr][sort], y[tr][sort] +zu, inv = np.unique(zs, return_inverse=True) +yu = np.bincount(inv, weights=ys) / np.bincount(inv) +spline = UnivariateSpline(zu, yu, k=min(3, len(zu)-1), + s=len(zu)*np.var(yu)*1e-3, ext=3) +pred = spline(z[te]) +r2 = 1-np.sum((y[te]-pred)**2)/np.sum((y[te]-np.mean(y[tr]))**2) +grid = np.linspace(np.quantile(z,.01), np.quantile(z,.99), 200) +curve = spline(grid); slope = spline.derivative()(grid) +turns = np.flatnonzero(np.sign(slope[1:]) != np.sign(slope[:-1])) +pos = (grid > 0) & (np.abs(curve) > 0) +elasticity = grid[pos]*slope[pos]/curve[pos] +print("heldout_r2", float(r2), "turning_points", np.round(grid[turns[:8]],6).tolist(), + "elasticity_q", np.round(np.quantile(elasticity,[.1,.5,.9]),4).tolist()) +``` + +Example output: + +```text +heldout_r2 0.9987 turning_points [] elasticity_q [1.96, 2.01, 2.05] +``` + +Interpretation: strong held-out collapse, no turning point, and elasticity near 2 support `y ∝ z**2`. If elasticity grows roughly linearly with `z`, test an exponential. If it approaches a negative integer in the tail, test a rational denominator power. + +### Analyze nonlinear variable relevance + +Principle: tree ensembles and held-out permutation importance can reveal U-shaped, thresholded, or interaction-only dependence missed by Pearson and Spearman. Use them only to select variables and transformations. + +```python +import numpy as np +from sklearn.ensemble import ExtraTreesRegressor +from sklearn.inspection import permutation_importance +from sklearn.model_selection import train_test_split +names = [k for k in data if k != "y"] +X = np.column_stack([np.asarray(data[k],float).ravel() for k in names]) +y = np.asarray(data["y"],float).ravel() +ok = np.isfinite(X).all(1) & np.isfinite(y); X,y=X[ok],y[ok] +if len(y)>20000: + idx=np.random.default_rng(0).choice(len(y),20000,replace=False); X,y=X[idx],y[idx] +Xtr,Xte,ytr,yte=train_test_split(X,y,test_size=.2,random_state=0) +model=ExtraTreesRegressor(n_estimators=160,min_samples_leaf=3, + random_state=0,n_jobs=1).fit(Xtr,ytr) +imp=permutation_importance(model,Xte,yte,n_repeats=3,random_state=0,n_jobs=1) +ranking=sorted(zip(imp.importances_mean,names),reverse=True) +print("heldout_r2",float(model.score(Xte,yte)),"importance",[(n,round(float(v),4)) for v,n in ranking[:10]]) +``` + +Example output: + +```text +heldout_r2 0.97 importance [('x3', 1.41), ('x1', 0.52), ('x2', 0.003)] +``` + +Interpretation: investigate `x3` and its combinations first; do not submit the forest. Repeat on raw `y`, `sign(y)*log1p(abs(y))`, and a rank target when extremes dominate. A weak held-out model means its importance ranking is not trustworthy. + +### Diagnose numerical and domain sensitivity + +Principle: a structurally correct formula may look imperfect when data were generated in lower precision or when equivalent algebraic forms suffer cancellation. Quantify this rather than tweaking coefficients. + +```python +import numpy as np +x1=np.asarray(data["x1"],float); x2=np.asarray(data["x2"],float) +y=np.asarray(data["y"],float) +f64=x1/(np.exp(x2)-1) +f32=(x1.astype(np.float32)/np.expm1(x2.astype(np.float32))).astype(float) +for name,p in [("float64_exp_minus_1",f64),("float32_expm1",f32)]: + r=p-y; finite=np.isfinite(p)&np.isfinite(y) + print(name,"finite",round(float(finite.mean()),5), + "rmse",float(np.sqrt(np.mean(r[finite]**2))), + "max_abs",float(np.max(np.abs(r[finite])))) +den=np.expm1(x2) +idx=np.argsort(np.abs(den))[:5] +print("smallest_denominator",[(int(i),float(den[i]),float(y[i])) for i in idx]) +``` + +Example output: + +```text +float64_exp_minus_1 finite 1.0 rmse 0.0021 max_abs 0.18 +float32_expm1 finite 1.0 rmse 3.2e-07 max_abs 1.1e-05 +``` + +Interpretation: the large improvement under float32-compatible `expm1` suggests generation precision or cancellation, not a missing polynomial correction. Also inspect denominator, radicand, and log-argument quantiles and the fraction of total SSE contributed by the worst samples. + +### Analyze robust views and outlier influence + +Principle: extreme values can hide a structural dependence. Use robust views for discovery, but always validate the final law on untrimmed original data. + +```python +import numpy as np +y=np.asarray(data["y"],float).ravel() +for name,x in data.items(): + if name=="y": continue + x=np.asarray(x,float).ravel(); ok=np.isfinite(x)&np.isfinite(y) + xx,yy=x[ok],y[ok] + lo,hi=np.quantile(yy,[.01,.99]); keep=(yy>=lo)&(yy<=hi) + signed=np.sign(yy)*np.log1p(np.abs(yy)) + corr=lambda a,b: float(np.corrcoef(a,b)[0,1]) if np.std(a)>0 and np.std(b)>0 else float("nan") + print(name,"raw",corr(xx,yy),"trimmed",corr(xx[keep],yy[keep]), + "signed_log",corr(xx,signed), + "top1pct_y2_share",float(np.sort(yy*yy)[-max(1,len(yy)//100):].sum()/np.sum(yy*yy))) +``` + +Example output: + +```text +x2 raw 0.03 trimmed 0.81 signed_log 0.76 top1pct_y2_share 0.94 +``` + +Interpretation: `x2` is plausibly relevant even though raw correlation is weak; inspect singular or multiplicative transformations. Do not optimize only the trimmed metric—the extreme region may contain the most informative evidence about a pole. + +### Screen singular compensation + +```python +import numpy as np +y=np.asarray(data["y"],float) +for name,x in data.items(): + if name=="y": continue + x=np.asarray(x,float) + print("SINGULARITY",name) + for idx in np.array_split(np.argsort(np.abs(x)),10)[:4]: + print(" median_abs_x",float(np.median(np.abs(x[idx]))), + "median_abs_y",float(np.median(np.abs(y[idx])))) + for p in [-3,-2,-1,1,2,3]: + z=y*np.power(x,p); good=np.isfinite(z) + scale=np.median(np.abs(z[good]))+1e-300 + print(" p",p,"relative_mad",float(np.median(np.abs(z[good]-np.median(z[good])))/scale)) +``` + +If `y*x` stabilizes as `x→0`, test a `1/x` factor and rediscover the compensated target. + +### Analyze binned residuals + +```python +import numpy as np +r=y-pred +den=np.maximum(np.abs(y),np.quantile(np.abs(y),.01)+1e-300) +rr=r/den +print("residual_q",np.quantile(r,[0,.01,.5,.99,1]).tolist(), + "relative_q",np.quantile(rr,[0,.01,.5,.99,1]).tolist()) +for name,x in data.items(): + if name=="y": continue + edges=np.quantile(x,np.linspace(0,1,9)) + bins=np.clip(np.searchsorted(edges[1:-1],x),0,7) + summary=[] + for b in range(8): + z=r[bins==b] + summary.append((len(z),float(np.mean(z)),float(np.sqrt(np.mean(z*z))))) + print(name,"bins(n,mean,rmse)",summary) +idx=np.argsort(np.abs(rr))[-5:] +print("worst_indices",idx.tolist()) +``` + +### Fit a small motivated feature library + +```python +import numpy as np +y=np.asarray(data["y"],float) +terms={"1":np.ones_like(y),"x1":data["x1"],"1/x2":1/data["x2"], + "log(x1)":np.log(data["x1"]),"cos(x3-x4)":np.cos(data["x3"]-data["x4"])} +names=list(terms); A=np.column_stack([terms[n] for n in names]) +ok=np.isfinite(A).all(1)&np.isfinite(y) +b=np.linalg.lstsq(A[ok],y[ok],rcond=None)[0] +print("condition",float(np.linalg.cond(A[ok])), + "top_terms",sorted(zip(np.abs(b),names,b),reverse=True)[:10]) +``` + +Build only evidence-motivated terms. Treat a many-term approximation as a diagnostic, not a discovered law. diff --git a/src/sr_harness/skills/skill_manager.py b/src/sr_harness/skills/skill_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..d80df461fdbfb42f84be371a9d1d539286f431f2 --- /dev/null +++ b/src/sr_harness/skills/skill_manager.py @@ -0,0 +1,328 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +from __future__ import annotations + +import tempfile +import re +from dataclasses import dataclass +from logging import getLogger +from pathlib import Path +from typing import IO, TYPE_CHECKING, Any, Callable, Iterable + +import yaml + +if TYPE_CHECKING: + from ..runtime.workspace import Workspace + +_logger = getLogger(f"sr_harness.{__name__}") + + +@dataclass(frozen=True) +class Skill: + """Metadata for one runtime skill.""" + name: str + description: str + readonly: bool + skill_directory: Path + + +class SkillManager: + """Manage built-in, runtime, and custom skills through one interface.""" + + def __init__( + self, + built_in_directory: str | Path | None = None, + custom_directory: str | Path | None = None, + workspace: Workspace | None = None, + ): + package_directory = Path(__file__).parent + runtime_directory = Path(tempfile.mkdtemp(prefix="sr_agent_runtime_skills_")) + self.skill_directories: dict[str, Path] = { + "built-in": Path(built_in_directory or package_directory), + "runtime": runtime_directory, + "custom": ( + Path(custom_directory) + if custom_directory is not None + else runtime_directory / "custom" + ), + } + self.workspace = workspace + + def register_tool_docs(self, tool_cls_list: Iterable[type]) -> None: + """Materialize documentation from enabled tools as read-only runtime skills. + + Args: + tool_cls_list: Tool classes to register. + """ + for tool_cls in tool_cls_list: + doc = tool_cls.get_doc() + if doc is None: + continue + if not isinstance(doc, dict): + raise TypeError(f"{tool_cls.__name__}.get_doc() must return a dict or None.") + if set(doc) != {"name", "description", "content"}: + raise ValueError( + f"{tool_cls.__name__}.get_doc() must return exactly name, description, and content." + ) + if not all(isinstance(doc[key], str) and doc[key].strip() for key in doc): + raise ValueError(f"{tool_cls.__name__}.get_doc() values must be non-empty strings.") + name = self._validate_name(doc["name"]) + if name in self.load_skills(): + raise ValueError(f"Skill {name!r} is already registered.") + content = self._format_skill_file( + name=name, + description=doc["description"].strip(), + readonly=True, + body=doc["content"].strip(), + ) + skill_dir = self.skill_directories["runtime"] / name + skill_dir.mkdir(parents=True, exist_ok=False) + (skill_dir / "SKILL.md").write_text(content, encoding="utf-8") + + def load_tool_skills(self) -> list[tuple[Skill, str]]: + """Return registered tool skills together with their Python source. + + Returns: + Pairs containing the skill metadata and ``tool.py`` source. + """ + loaded = [] + for skill in self.load_skills().values(): + path = skill.skill_directory / "tool.py" + if path.is_file(): + opener = self._skill_opener(skill) + with opener(path, "r", encoding="utf-8") as f: + loaded.append((skill, f.read())) + return loaded + + def load_skills(self) -> dict[str, Skill]: + """Load skills. + + Returns: + dict[str, Skill]: The operation result. + """ + skills: dict[str, Skill] = {} + for scope, root in self.skill_directories.items(): + for skill_path in sorted(root.glob("*/SKILL.md")): + opener = ( + self.workspace.safe_open + if scope == "custom" and self.workspace is not None + else open + ) + with opener(skill_path, "r", encoding="utf-8") as f: + text = f.read() + metadata, _ = self._parse_skill_text(text, skill_path) + name = str(metadata.get("name", "")).strip() + description = str(metadata.get("description", "")).strip() + if not name: + _logger.warning(f"Skill file '{skill_path}' is missing frontmatter field: name, skip it") + continue + if not description: + _logger.warning(f"Skill file '{skill_path}' is missing frontmatter field: description, skip it") + continue + if name != skill_path.parent.name: + _logger.warning( + f"Skill name {name!r} in {skill_path!r} does not match directory name " + f"{skill_path.parent.name!r}; use {name!r} as the skill name" + ) + if name in skills: + raise ValueError(f"Skill {name!r} is provided by more than one skill directory.") + readonly = scope != "custom" or self._as_bool(metadata.get("readonly", False)) + skills[name] = Skill(name, description, readonly, skill_path.parent.absolute()) + return skills + + def get_skill(self, name: str) -> Skill: + """Return skill. + + Args: + name: Registered name. + + Returns: + Skill: The operation result. + """ + skills = self.load_skills() + if name in skills: + return skills[name] + available = ", ".join(skills) + raise ValueError(f"Skill '{name}' not found. Available skills: {available}") + + def search_skills(self, query: str, limit: int = 5) -> list[Skill]: + """Rank skills by lexical overlap in name and discovery description. + + Args: + query: Search query. + limit: Maximum number of results. + + Returns: + list[Skill]: The operation result. + """ + tokens = set(re.findall(r"[a-zA-Z][\w-]+|[\u4e00-\u9fff]{2,}", query.lower())) + ranked = [] + for skill in self.load_skills().values(): + pattern = r"[a-zA-Z][\w-]+|[\u4e00-\u9fff]{2,}" + name_tokens = set(re.findall(pattern, skill.name.lower().replace("-", " "))) + desc_tokens = set(re.findall(pattern, skill.description.lower())) + score = 3 * len(tokens & name_tokens) + len(tokens & desc_tokens) + ranked.append((score, skill.name, skill)) + ranked.sort(key=lambda item: (-item[0], item[1])) + matches = [skill for score, _, skill in ranked if score > 0] + return matches[:max(1, min(int(limit), 20))] + + def read_skill(self, name: str, file_path: str = "SKILL.md") -> str: + """Read skill. + + Args: + name: Registered name. + file_path: Path relative to the selected resource. + + Returns: + str: The operation result. + """ + skill = self.get_skill(name) + path = self._resolve_skill_file(skill, file_path) + if not path.is_file(): + raise ValueError(f"Skill file not found: {file_path}") + with self._skill_opener(skill)(path, "r", encoding="utf-8") as f: + return f.read() + + def get_skill_tree(self, name: str) -> list[str]: + """Return skill tree. + + Args: + name: Registered name. + + Returns: + list[str]: The operation result. + """ + skill_dir = self.get_skill(name).skill_directory + return [ + path.relative_to(skill_dir).as_posix() + ("/" if path.is_dir() else "") + for path in sorted(skill_dir.rglob("*")) + if "__pycache__" not in path.parts + and not (path.is_file() and path.suffix in {".pyc", ".pyo"}) + ] + + def set_skill( + self, + name: str, + content: str, + file_path: str = "SKILL.md", + force: bool = False, + ) -> Skill: + """Create a custom skill file or update a file in an editable skill. + + Args: + name: Registered name. + content: Text content. + file_path: Path relative to the selected resource. + force: Whether to overwrite an existing resource. + + Returns: + Skill: The operation result. + """ + name = self._validate_name(name) + skills = self.load_skills() + skill = skills.get(name) + if skill is None: + if file_path != "SKILL.md": + raise ValueError("A new skill must be created by writing SKILL.md first.") + skill_dir = self.skill_directories["custom"] / name + else: + if skill.readonly: + raise ValueError(f"Skill '{name}' is read-only and cannot be overwritten.") + skill_dir = skill.skill_directory + + target = self._resolve_path(skill_dir, file_path) + workspace_relative = None + if self.workspace is not None: + try: + workspace_relative = target.relative_to(self.workspace.path) + except ValueError: + pass + if workspace_relative is not None: + resolved = self.workspace.resolve(str(workspace_relative)) + target_exists = resolved is not None and resolved.exists() + else: + target_exists = target.exists() + if target_exists and not force: + raise ValueError(f"Skill file '{name}/{file_path}' already exists. Use force=True to replace it.") + if file_path == "SKILL.md": + metadata, _ = self._parse_skill_text(content, target) + declared_name = str(metadata.get("name", "")).strip() + description = str(metadata.get("description", "")).strip() + if declared_name != name: + raise ValueError(f"SKILL.md name {declared_name!r} must match {name!r}.") + if not description: + raise ValueError("SKILL.md frontmatter must contain a non-empty description.") + + if workspace_relative is not None: + self.workspace.create_directory( + str(workspace_relative.parent), + parents=True, + exist_ok=True, + ) + with self.workspace.open_for_write( + str(workspace_relative), + "w" if force else "x", + encoding="utf-8", + ) as stream: + stream.write(content) + else: + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(content, encoding="utf-8") + return self.get_skill(name) + + def _skill_opener(self, skill: Skill) -> Callable[..., IO]: + custom_directory = self.skill_directories["custom"].absolute() + if self.workspace is not None and skill.skill_directory.is_relative_to(custom_directory): + return self.workspace.safe_open + return open + + @staticmethod + def _validate_name(name: str) -> str: + name = name.strip() + if not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", name): + raise ValueError(f"Invalid skill name: {name!r}.") + return name + + @classmethod + def _resolve_skill_file(cls, skill: Skill, file_path: str) -> Path: + return cls._resolve_path(skill.skill_directory, file_path) + + @staticmethod + def _resolve_path(skill_dir: Path, file_path: str) -> Path: + relative = Path(file_path or "SKILL.md") + if relative.is_absolute() or ".." in relative.parts: + raise ValueError("file_path must be relative and stay inside the skill directory.") + return skill_dir / relative + + @staticmethod + def _parse_skill_text(text: str, path: Path) -> tuple[dict[str, Any], str]: + normalized = text.strip() + if not normalized.startswith("---\n"): + raise ValueError(f"Skill file '{path}' must start with YAML frontmatter") + try: + _, frontmatter, _ = normalized.split("---\n", 2) + except ValueError as exc: + raise ValueError(f"Skill file '{path}' has invalid YAML frontmatter") from exc + try: + metadata = yaml.safe_load(frontmatter.strip()) or {} + except yaml.YAMLError as exc: + raise ValueError(f"Skill file '{path}' has invalid YAML frontmatter") from exc + if not isinstance(metadata, dict): + raise ValueError( + f"Failed to parse frontmatter in skill file '{path}', expected a YAML mapping " + f"but got {type(metadata).__name__}" + ) + return metadata, normalized + + @staticmethod + def _as_bool(value: Any) -> bool: + return str(value).lower().strip() in {"true", "yes", "1", "on"} + + @staticmethod + def _format_skill_file(*, name: str, description: str, readonly: bool, body: str) -> str: + metadata = yaml.safe_dump( + {"name": name, "description": description, "readonly": readonly}, + sort_keys=False, + allow_unicode=True, + ) + return f"---\n{metadata}---\n\n{body}\n" diff --git a/src/sr_harness/skills/sr-harness-engine-graph-syntax/SKILL.md b/src/sr_harness/skills/sr-harness-engine-graph-syntax/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..9b45479792a61a0a18855dbea5be24cd3c4ec91e --- /dev/null +++ b/src/sr_harness/skills/sr-harness-engine-graph-syntax/SKILL.md @@ -0,0 +1,181 @@ +--- +name: sr-harness-engine-graph-syntax +description: Use this skill before writing, evaluating, or submitting SRHarness Engine formulas for graphs, networks, hypergraphs, node interactions, relation reductions, edge or hyperedge fields, gather operations, or message passing. +--- + +# Write graph and hypergraph formulas + +Read `sr-harness-engine-syntax` first for ordinary arithmetic, functions, fitted parameters, and general parser restrictions. This skill covers the indexed structural language used for graph and hypergraph models. + +Prefer structured Engine formulas over `evaluate_code`: indexed formulas retain interpretable structure, support parameter fitting and diagnostics, have measurable symbolic complexity, and can appear naturally in TopK and Pareto views. + +## Indexed structural expressions + +An expression containing symbolic indices such as `[i]`, `[i, j]`, or `[i, j, k]` uses the final array dimension as a structural dimension. Leading dimensions use ordinary element-wise broadcasting. + +Indices must be symbolic identifiers; integer indices and slices such as `x[0]` or `x[0:10]` are invalid. In `theta[i]`, `i` names a node dimension rather than selecting the element stored in a Python variable named `i`. + +The runtime must provide `num_nodes=N`. It is never inferred from a relation because isolated nodes may not occur in any relation row. + +Typical value shapes are: + +```text +node field: (..., N) +edge field: (..., E) +hyperedge field: (..., H) +scalar field: (..., 1) +binary relation: (E, 2) +ternary relation: (H, 3) +``` + +Relations must be declared as relations in `context.data`. Do not infer relation semantics from names such as `A` or `T`. + +Once an expression uses symbolic indices, index every non-singleton structural variable. Thus `x + x[i]` is invalid when `x.shape[-1] == N`; use `x[i] + x[i]`. A final singleton dimension may remain unindexed and broadcast naturally. + +Free indices become dense trailing output axes in first-appearance order: + +```text +x[i] -> (..., N) +x[i] + x[j] -> (..., N, N) +x[i] * x[j] * x[k] -> (..., N, N, N) +``` + +Multiple free indices are legal, but their cost grows as `N**r`. Avoid dense multi-index intermediates when a relation-restricted reduction or `gather` can request only needed components. + +## Relations and `sum[...]` + +A binary relation stores rows in `(target, source)` order. Therefore: + +```text +A[i, j] +``` + +binds `i` to the target column and `j` to the source column. A ternary relation stores `(target, source1, source2)` and is written `T[i, j, k]`. + +Use `sum[index](operand)` to reduce a named structural index: + +```text +sum[j](x[i] * x[j]) +sum[j, k](x[i] * x[j] * x[k]) +``` + +If the operand does not contain a reduced index, summing over that index multiplies the value by `N`. + +Use the two-argument form to restrict the reduction to a sparse relation: + +```text +sum[j](A[i, j], x[j] - x[i]) +sum[j, k](T[i, j, k], x[i] * x[j] * x[k]) +``` + +Mathematically, `sum[j](A[i, j], eq)` means `sum[j](A[i, j] * eq)`. The two-argument form is preferable because the evaluator can compute only relation-supported components instead of materializing a dense `N x N` tensor. + +An edge-aligned field with shape `(..., E)` uses the same complete relation indices: + +```text +sum[j](A[i, j], w[i, j] * sin(theta[j] - theta[i])) +``` + +A hyperedge-aligned field with shape `(..., H)` similarly uses all three indices. When several compatible relations make field association ambiguous, the data context must explicitly associate the field with its relation; changing the formula cannot resolve ambiguous data metadata. + +Relation expressions are numerical sparse tensors and support ordinary algebra: + +```text +sum[j](A1[i, j] + A2[i, j], x[j]) +sum[j](A1[i, j] * A2[i, j], x[j]) +sum[j](A1[i, j] + 0.5 * A2[i, j], x[j]) +``` + +The first expression adds overlapping relation values; it is not merely a support union. + +Do not bind the same index again inside its active scope. This is invalid: + +```text +sum[j](A[i, j], sum[j](x[j])) +``` + +Rename the inner index, for example to `k`. + +## Network and hypergraph examples + +Unnormalized Kuramoto-like dynamics: + +```text +omega[i] + param('K') * sum[j](A[i, j], sin(theta[j] - theta[i])) +``` + +Degree-normalized interaction: + +```text +omega[i] + param('K') * sum[j](A[i, j], sin(theta[j] - theta[i])) / sum[j](A[i, j], 1) +``` + +Node, edge-weighted, and hypergraph terms in one RHS: + +```text +(param('a') * x[i] ++ param('b') * sum[j](A[i, j], w[i, j] * tanh(x[j] - x[i])) ++ param('c') * sum[j, k](T[i, j, k], x[j] * x[k])) +``` + +Use parentheses when a denominator might be zero and inspect the data before submitting singular expressions. + +## `gather`: produce relation-aligned values + +`gather(relation, expression)` selects an indexed expression at the relation's stored coordinates and multiplies by relation values: + +```text +gather(A[i, j], x[i] + x[j]) -> (..., E) +gather(T[i, j, k], x[i] * x[j] * x[k]) -> (..., H) +``` + +The operand may use only a subset of relation indices; missing indices broadcast: + +```text +gather(A[i, j], x[i]) +``` + +The result behaves like an ordinary edge or hyperedge field: + +```text +2 * gather(A[i, j], x[i] + x[j]) +sin(gather(A[i, j], x[i] + x[j])) +gather(A[i, j], x[i] + x[j]) + w +``` + +It can be indexed again with the same complete relation indices inside another structural expression: + +```text +sum[j](A[i, j], gather(A[i, j], x[i] + x[j])[i, j] * x[j]) +``` + +Use `sum[...]` when the desired output is node-aligned after reduction. Use `gather(...)` when the desired output is relation-row-aligned. + +## `aggr`, `targ`, and `sour` convenience syntax + +For ordinary binary message passing, these forms are accepted: + +```text +aggr(A * targ(x) * sour(x)) +aggr(A, targ(x) * sour(x)) +aggr(A, targ(A, x) * sour(A, x)) +``` + +They compile to canonical indexed syntax: + +```text +sum[j](A[i, j], x[i] * x[j]) +``` + +`targ` reads the target endpoint and `sour` reads the source endpoint. They are only valid inside `aggr`. Nested `aggr` is legal because the desugaring pass generates fresh indices automatically. Prefer explicit indexed syntax for hypergraphs, unusual reductions, and formulas that need precise index control. + +## Graph and hypergraph checklist + +Before calling `evaluate_formula` or `submit_formula`: + +1. Confirm that `context.data` defines `num_nodes` explicitly. +2. Confirm relation metadata, endpoint order, structural-axis lengths, and any edge/hyperedge field association. +3. Index every non-singleton structural variable and keep reduction indices distinct across nested scopes. +4. Prefer relation-restricted `sum` over dense `N**r` expressions. +5. Use `gather` when relation-aligned output or an intermediate edge/hyperedge field is intended. +6. Inspect finite coverage, residual diagnostics, and train/validation metrics before submitting the formula. diff --git a/src/sr_harness/skills/sr-harness-engine-syntax/SKILL.md b/src/sr_harness/skills/sr-harness-engine-syntax/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..658efe1b82a14b77f62dab391b16e7e3f70f205a --- /dev/null +++ b/src/sr_harness/skills/sr-harness-engine-syntax/SKILL.md @@ -0,0 +1,98 @@ +--- +name: sr-harness-engine-syntax +description: Use this skill before writing, evaluating, or submitting ordinary SRHarness Engine formulas, especially formulas with fitted parameters, categorical grouped parameters, nonlinear functions, broadcasting, or delays. +--- + +# Write SRHarness Engine formulas + +Use SRHarness Engine syntax for candidate models whenever it can express the model. Prefer a structured formula over `evaluate_code`: engine formulas can be parsed, fitted, diagnosed, ranked by complexity, and presented in TopK and Pareto views. + +Pass only the right-hand-side expression to `evaluate_formula` or `submit_formula`. For a model such as `y = a*x + b`, submit `param('a') * x + param('b')`; pass the target separately through the tool's `y` argument when it is not the configured target. + +## Ordinary element-wise expressions + +Use these arithmetic operators: + +```text ++ - * / ** +``` + +They follow normal precedence and NumPy-style broadcasting. Fixed numerical literals are not fitted: + +```text +x1 + x2 +2.0 * sin(x1) +x1**2 + exp(-x2) +max(x1, x2) / (1 + abs(x3)) +``` + +Available one-argument functions are: + +```text +abs arccos arcsin arctan cos cosh cot csc exp inv +log log10 log2 pow2 pow3 sec sech sigmoid sign sin sinh +sqrt tan tanh +``` + +`log(x)` is the natural logarithm. The parser accepts `ln` as its alias, `lg` as an alias for base-10 `log10`, and `asin`/`acos`/`atan` as aliases for `arcsin`/`arccos`/`arctan`. Prefer the canonical names shown above in generated formulas. + +`min(a, b)` and `max(a, b)` accept exactly two arguments. Function names must be bare names: use `sin(x)`, never `np.sin(x)` or `numpy.sin(x)`. + +## Fitted parameters + +Declare every fitted scalar explicitly with `param`: + +```text +param('a') * x + param('b') +param('alpha', value=0.3) * x / (1 - param('alpha')) +``` + +The optional `value` is an initial/default numerical value. Repeated declarations with the same name refer to one shared parameter and must not provide conflicting initial values. When calling `evaluate_formula`, set `fit=true` to optimize unbound parameters. + +Do not invent a bare variable name for a coefficient. Write `param('a') * x`, not `a * x`. Bare names denote data variables in the symbolic language. + +For a coefficient shared within each category and allowed to differ between categories, use `grouped_param`: + +```text +grouped_param(category) * x +grouped_param(category, name='slope', default=0.0) * x +grouped_param(category, name='slope', value={'A': 1.0, 'B': 2.0}) * x +``` + +Do not one-hot encode a categorical variable merely to express category-specific coefficients. + +## Graph and hypergraph expressions + +Indexed node, edge, and hyperedge expressions are documented separately. Before writing a formula with symbolic indices, relations, `sum[...]`, `gather`, `aggr`, `targ`, or `sour`, use `read_skill` to read `sr-harness-engine-graph-syntax`. + +## Delays + +Use: + +```text +x + delay(x, delta) +``` + +`delay(value, delta)` reads the value at `t - delta`. The default evaluator interpolates along the first array axis and returns `NaN` outside available history. A specialized ODE or DDE evaluator may supply its own history resolver and integration protocol. The expression describes only the RHS; it does not choose an integrator or loss. + +## Syntax that is not allowed + +The parser does not execute Python. Do not use: + +```text +y = x + 1 # assignment; provide only the RHS +np.sin(x) # attribute access +custom_function(x) # unregistered function +lambda x: x # lambda +__import__('os') # arbitrary Python +``` + +## Evaluation checklist + +Before calling `evaluate_formula` or `submit_formula`: + +1. Use names that exist in `context.data`; declare coefficients with `param`. +2. Use `fit=true` if the formula contains unbound `param` or `grouped_param` nodes. +3. Check domains and finite coverage before submitting expressions containing division, logarithms, roots, or delays. +4. Inspect residual diagnostics and train/validation metrics; a parsable formula is not necessarily a valid scientific model. +5. Submit structured formulas whenever possible. Use code-defined models only when the engine truly cannot express the candidate. diff --git a/src/sr_harness/tools/README.md b/src/sr_harness/tools/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a20fb07f675872701f6347f6c371b01b994d94d3 --- /dev/null +++ b/src/sr_harness/tools/README.md @@ -0,0 +1,160 @@ +# 工具开发指南 + +> 完整的 SRHarness 使用文档和 API Reference:[`docs/index.md`](../../../docs/index.md) + +本目录包含可供 `SRAgent` 调用的工具。新工具需继承 `BaseTool`,注册一个稳定的工具名,并实现 `execute()` 方法和可选的 `format_result_dict()` 类方法。 + +## 最小示例 + +```python +from typing import Any, Dict + +from .base_tool import BaseTool, ToolMetadata + + +@BaseTool.register("my_tool") +class MyTool(BaseTool): + metadata = ToolMetadata(name="my_tool") + + def execute(self, value: str, limit: int = 10) -> Dict[str, Any]: + """简短描述工具的功能。 + + Args: + value: value 的描述。 + limit: limit 的描述。 + """ + return {"value": value, "limit": limit} +``` + +## 必要组件 + +- 继承 `BaseTool`。 +- 添加 `@BaseTool.register("tool_name")` 使工具被发现。 +- 设置 `metadata = ToolMetadata(name="tool_name")`。 +- 实现 `execute()`。 + - 其参数由 Agent 生成,因此应当尽量简单、且可序列化。 + - `execute()` 的返回值必须是一个 `Dict[str, Any]`,且不宜过长(会浪费 token) + - 如果返回的结果字典较大,建议同时重写 `format_result_dict(cls, result)` 类方法,将字典格式化为一段较短的文本供 Agent 阅读,从而节省 token。 +- 设置 `metadata` + - `metadata.name` 是工具的唯一标识符,必须与 `@BaseTool.register(...)` 中的名称一致。 + - `metadata.description` 和 `metadata.parameters` 可选,如果不设置,会自动从 `execute()` 的 docstring 和签名推断。 + - `metadata.description` 从 docstring 中 `Args:` 之前的部分提取。 + - `metadata.parameters` 从 `execute()` 的签名、类型提示、默认值和 `Args:` 描述推断。 + - 如果 Agent 调用工具的成功率过低,建议检查自动推断的 `description` 和 `parameters` 是否准确反映了工具的功能和参数要求。 + - 当自动推断不够精确时(例如需要更严格的 JSON Schema 约束、枚举说明、嵌套对象或特殊格式),可以手动设置 `ToolMetadata(description=..., parameters=...)`。手动指定的元数据不会被 `BaseTool` 覆盖。 + +## 运行时上下文 + +工具实例化时传入的上下文可通过 `self.context` 访问,用于存放数据、模型、缓存等不应放在参数列表中由 Agent 生成的值。目前包含以下字段: +- `self.context.data`: 原始数据,格式为 `{变量名: np.ndarray}`。 +- `self.context.target`: 目标变量名称字符串。除目标变量外的其他非轴变量都可以作为公式中的自变量。 +- `self.context.train_split` / `self.context.validation_split`: Evaluator 首次切分并缓存的只读上下文属性。 + +## 公式处理 + +在 `execute()` 中处理公式时,应使用 `sr_harness_engine`(如 `engine.parse()`、`Expression.fit()` 等)而非手动解析或计算。 +它是项目中公式表示、求值与参数优化的标准方式,与 `BaseTool.evaluate()` 及候选记录紧密集成。 + +## 公式与指标约定 + +如果工具会产生公式(例如拟合、评估、变换、搜索),应直接使用 `self.evaluate()` 返回统一候选字典: +- `formula` 是一个字符串,表示工具产生的公式。 +- `metrics` 包含该公式的评估指标。 +- `is_candidate` 表示是否可参与 best formula 排名。 +- `diagnostics` 包含可选的残差诊断;关闭时为空字典。 + +示例如下: +```python +return self.evaluate( + f=formula_symbol, + y=target_symbol, +) +``` + +`BaseTool.evaluate()` 会在目标恰为 `self.context.target` 且公式不包含目标变量时自动设置 `is_candidate=True`。 +特殊工具可在获得结果后覆盖字段,例如公式展示文本不是 `f.to_str()` 时: + +```python +result = self.evaluate( + f=formula_symbol, + y=target_symbol, +) +result["formula"] = custom_formula_text +return result +``` + +`f` 和 `y` 必须是 `sr_harness_engine.Expression`。`evaluate()` 会分别在训练集和验证集上调用 +`f.eval(data)` 与 `y.eval(data)`(不存在的验证集不会返回)。训练集和验证集结果统一保存在 +`data_split_results["train"]` 与 `data_split_results["validation"]` 中,各自包含 `metrics`,以及可选的 +`diagnostics`;不存在验证集时不返回 `validation` 字段。 +代码模型如果已经在沙箱中得到预测数组,应调用 `BaseTool.calculate_metrics()` 复用相同的指标定义。 +复杂度固定为 `len(f)`,不能由调用方覆盖。 +残差诊断默认开启;内部候选筛选可显式传入 `show_diagnostics=False`,最终入选公式应保留诊断。 + +## 错误处理 + +- **不影响正常运行的警告**:将警告信息汇总到结果字典的 `exceptions` 字段,以供 Agent 参考。 + - 例如某些输入变量解析失败但其余变量仍可用时,将失败信息追加到 `exceptions` 中即可。 +- **导致无法正常运行的错误**:直接 `raise` 抛出异常即可。 + - 抛出时可将已积累的警告信息一并包含在错误消息中,方便 Agent 理解上下文。例如: + ```python + if some_error_condition: + error_message = f"Error occurred due to XXX. Previous warnings: {exceptions}" + raise RuntimeError(error_message) + ``` + - `BaseTool.__call__()` 会接住工具 `execute()` 方法中抛出的异常,将其格式化为错误信息返回给 Agent。 + +## 工具注册 + +- `@BaseTool.register("tool_name")` 会使工具出现在 Agent 可用的工具列表中。 +- 因此,**尚未实现完善或测试不充分的工具不应注册** —— Agent 调用这类工具的成功率太低,不注册即可确保 Agent 无法使用它,避免浪费调用次数和 token。 +- 可以将 `@BaseTool.register(...)` 注释掉来暂时取消注册,待工具成熟后再启用。 + +## 自定义工具 + +`create_skill` 可创建说明型 skill,也可在 skill 目录中同时创建自定义工具; +`edit_tool` 用于修改已有的自定义工具: + +```text +skills//SKILL.md +skills//tool.py +``` + +`tool.py` 必须定义一个继承 `BaseTool` 的类,并设置唯一的 `metadata.name`。 +自定义工具不要使用 `@BaseTool.register(...)`,加载器会根据 `metadata.name` 统一注册。 +创建或编辑成功后,工具会立即尝试加载并注册到 `BaseTool`;重名工具会被拒绝。 + +## 创建 Skill + +调用 `create_skill(request="...")` 表达要沉淀的可复用经验;工具默认把当前 Agent 的 +system prompt、全部历史 messages 和本次工具调用消息传给配置的同一 provider/model; +也可以用 `history_messages=N` 只提供最近 N 条消息。内部 +完成若干轮澄清和草稿生成后才写入文件。 + +LLM 会选择一种类型: + +- `instructions`:只创建说明性 `SKILL.md`。 +- `data_analysis`:创建返回普通数据分析结果的 `tool.py`。 +- `formula_proposer`:创建公式提议工具;必须把 `self.evaluate(...)` 的结果直接 + 返回或合并进返回字典,保留 `formula`、`is_candidate` 和 `data_split_results` 等字段。 + +默认不覆盖已有 skill;传入 `force=true` 可替换可编辑 skill 的 `SKILL.md` 和 +`tool.py`,但不会修改目录中的其他文件,也不能覆盖只读 skill。自定义 `tool.py` +不得写 `@BaseTool.register(...)`,加载器会根据 `metadata.name` 注册工具。 + +## 自定义评估器与数据划分 + +SRHarness 提供普通一维数据实现 `sr_harness.DefaultEvaluator` 和图数据实现 +`sr_harness.GraphEvaluator`。用户可以用类方法覆盖 `fit()` 与 `evaluate()`,或只覆盖候选公式专用的 `fit_candidate()` 与 `evaluate_candidate()`,从 +`context.args` 提取所需参数后,再通过 `SRAgent(evaluator=...)` 注入自己的参数优化、 +数值积分或评价协议。 +评估器直接接收结构化 `Expression` 和当前数据划分的上下文;`fit()` 返回已绑定参数、 +可直接求值的 `Expression`,`evaluate()` 返回仅含数值的扁平 metrics 字典。复杂度和格式化由工具层负责。 +它适合 ODE 轨迹积分、网络动力学和其它不能用逐点回归评价的任务。 + +内置公式工具仍通过 `BaseTool.evaluate()` 复用统一的 train/validation 指标与残差诊断。 +`SRAgent` 的 `validation_fraction`、`split_by` 和 `split_random_state` 决定 Agent 可见数据内部的 +训练/验证划分;该划分不得接触 Benchmark 的隐藏测试集。自定义评估器可读取相同的 +`AgentContext` 数据,但应在自己的实现中清楚区分拟合数据、选择指标与最终报告指标。 + +完整示例见 [`docs/index.md` 的“自定义评估协议”](../../../docs/index.md)。 diff --git a/src/sr_harness/tools/__init__.py b/src/sr_harness/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..536358c7bc903a3200ad938a3bbdb65e60102579 --- /dev/null +++ b/src/sr_harness/tools/__init__.py @@ -0,0 +1,51 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""工具模块。 + +所有工具都应继承自 BaseTool,并实现 execute 方法,详见本目录下的 README.md +""" +from ..core import ToolCallResult, ToolMetadata +from .base_tool import BaseTool, ToolRunAbort +from .statistics_analysis import StatisticsTool +from .relationship_analysis import RelationshipAnalysisTool +from .evaluate_formula import EvaluateTool, SubmitFormulaTool +from .evaluate_code import EvaluateCodeTool +from .call_llm import LLMTool +from .polynomial_fit import PolynomialFitTool +from .harmonic_interaction_fit import HarmonicInteractionFitTool +from .power_law_fit import PowerLawFitTool +from .rational_fit import RationalFitTool +from .constant_fit import ConstantFitTool +from .code_executor import CodeExecutorTool +from .workspace_code_executor import WorkspaceCodeExecutorTool +from .read_skill import ReadSkill +from .create_skill import CreateSkill +from .edit_skill import EditSkill +from .edit_tool import EditTool +from .call_sindy import SINDyTool +from .call_pysr import PySRTool +from .predict_property import PropertyPredictorTool +from .workspace_shell import WorkspaceShellTool +from .subagent import SubagentTool +from .web_research import WebFetchTool, WebSearchTool +from .validate_context_data import ValidateContextDataTool +from .read_pdf import PDFReadTool +from .eic import EICTool +from .nd2 import ND2Tool +from .sr4mdl import SR4MDLTool +from .model_test import ModelTestTool +from .finish_search import FinishSearchTool +from .read_source import ReadSourceTool +from .validate_evaluator import ValidateEvaluatorTool + +__all__ = [ + "BaseTool", "CodeExecutorTool", "ConstantFitTool", + "CreateSkill", "EditSkill", "EditTool", "EICTool", "EvaluateCodeTool", + "EvaluateTool", "FinishSearchTool", "HarmonicInteractionFitTool", "LLMTool", "ModelTestTool", + "ND2Tool", "PDFReadTool", "PolynomialFitTool", "PowerLawFitTool", + "PropertyPredictorTool", "PySRTool", "RationalFitTool", "ReadSkill", + "ReadSourceTool", "RelationshipAnalysisTool", "SINDyTool", "SR4MDLTool", + "StatisticsTool", "SubagentTool", "SubmitFormulaTool", "ToolCallResult", + "ToolMetadata", "ToolRunAbort", "ValidateContextDataTool", + "ValidateEvaluatorTool", "WebFetchTool", "WebSearchTool", + "WorkspaceCodeExecutorTool", "WorkspaceShellTool", +] diff --git a/src/sr_harness/tools/base_tool.py b/src/sr_harness/tools/base_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..927099df84c43c70bf0b1c2dddb1b97e8cc03c41 --- /dev/null +++ b/src/sr_harness/tools/base_tool.py @@ -0,0 +1,889 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""工具基类定义。 + +所有工具都应继承自 BaseTool,并提供统一的接口。 +""" +from __future__ import annotations +import re +import time +import warnings +from numbers import Real +import numpy as np +import sr_harness_engine as engine +from pathlib import Path +from logging import getLogger +from scipy import stats +from docstring_parser import DocstringStyle, parse +from abc import ABC, abstractmethod +from types import NoneType, UnionType +from inspect import Parameter, signature +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Literal, Union, get_args, get_origin, get_type_hints +from ..utils import FactoryMixin, log_exception +from ..core import AgentContext +from ..core.tool import ToolCallResult, ToolMetadata +from ..evaluator import utils as evaluator_utils +if TYPE_CHECKING: + from ..skills import SkillManager + +_logger = getLogger(f'sr_harness.{__name__}') + +_ANSI_ESCAPE_RE = re.compile( + r"(?:\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|(?:\x1b\[|\x9b)[0-?]*[ -/]*[@-~]|\x1b[@-_])" +) + + +class ToolRunAbort(RuntimeError): + """Raise from a tool to bypass BaseTool.__call__ error handling.""" + + +class BaseTool(ABC, FactoryMixin): + """工具基类。所有工具都应继承此类,并设置 / 实现以下字段和方法: + - metadata: ToolMetadata 实例,提供工具的名称、描述和参数 schema(若不提供则尝试自动推断) + - execute(): 工具的核心执行方法,接受 LLM 生成的参数并返回结果字典。工具的 execute 方法应该尽量保持参数简单,复杂的上下文信息(如数据)可以通过工具实例的 context 属性传入。 + - format_result_dict(): 可选的类方法,用于将 execute 的结果字典格式化为字符串,供 LLM 阅读。默认实现是直接转换为字符串,不同工具可以根据需要重写此方法以提供更友好的结果展示。 + """ + metadata: ToolMetadata = None + MAX_FORMULA_LENGTH = 10000 + MAX_RESULT_STR_LENGTH = 64 * 1024 + FORMULA_DISPLAY_NUMBER_FORMAT = ".8g" + + def __init_subclass__(cls, **kwargs: Any) -> None: + """在子类定义时自动设置元数据""" + super().__init_subclass__(**kwargs) + if cls.metadata is None: + cls.metadata = ToolMetadata() + if cls.metadata.description is None: + cls.metadata.description = cls.infer_tool_description() + if cls.metadata.parameters is None: + cls.metadata.parameters = cls.infer_tool_parameters() + + def __init__(self, context: AgentContext | None = None) -> None: + """Initialize a tool with its authoritative runtime context. + + Args: + context: Context used by the tool. An empty context is created when + omitted for tools that do not require runtime data. + + Raises: + TypeError: If ``context`` is not an :class:`AgentContext`. + """ + if context is not None and not isinstance(context, AgentContext): + raise TypeError("context must be an AgentContext or None") + self.context = context if context is not None else AgentContext() + + @classmethod + def get_doc(cls) -> dict[str, str] | None: + """Return optional documentation to expose as a runtime skill.""" + return None + + @abstractmethod + def execute(self) -> Dict[str, Any]: + """Execute the tool and return its result. + + The parameters of this method are generated by the LLM and should therefore remain simple. Pass complex runtime context, such as data, through the tool instance's ``context`` attribute. Implementations must be safe for concurrent process or thread execution. + + The text before ``Args`` supplies ``metadata.description``; argument descriptions supply the parameter schema descriptions. The signature and type hints supply its JSON schema. Automatic inference supports common scalar, list, and dictionary types. Define ``ToolMetadata.parameters`` explicitly for more complex schemas. + + Returns: + A structured result dictionary.""" + pass + + @classmethod + def format_result_dict(cls, result: Dict[str, Any]) -> str: + """Format a tool result as text for the language model. + + Subclasses may override this method to provide a clearer presentation. + + Args: + result: Structured result returned by ``execute``. + + Returns: + Text to append to the model conversation.""" + return str(result) + + def cancel(self) -> None: + """Request cancellation when a tool offers no stronger primitive.""" + + def __call__(self, *args, **kwargs) -> ToolCallResult: + """工具调用入口""" + start_time = time.time() + try: + cancellation_event = getattr(self, "cancel_event", None) + if cancellation_event is not None and cancellation_event.is_set(): + raise InterruptedError("用户强制中止") + result = self.execute(*args, **kwargs) + if cancellation_event is not None and cancellation_event.is_set(): + raise InterruptedError("用户强制中止") + if not isinstance(result, dict): + _logger.critical(f"Tool {self.metadata.name} execute() should return a dict, but got {type(result)}, please check the implementation.") + result_str = self.format_result_dict(result) + result_str = self.truncate_result_str(_ANSI_ESCAPE_RE.sub("", str(result_str))) + meta_data = { + "timestamp": start_time, + "execution_time": time.time() - start_time, + "tool": self.metadata.name + } + return ToolCallResult(ok=True, result=result, result_str=result_str, meta_data=meta_data) + except ToolRunAbort: + raise + except Exception as e: + _logger.error(f"Error executing {self.metadata.name}: {log_exception(e)}") + exception_message = str(e).strip() or repr(e) + error_msg = ( + f"Error executing {self.metadata.name}:\n" + f" {type(e).__name__}: {exception_message}" + ) + error_msg = self.truncate_result_str(_ANSI_ESCAPE_RE.sub("", error_msg)) + meta_data = { + "timestamp": start_time, + "execution_time": time.time() - start_time, + "tool": self.metadata.name + } + return ToolCallResult(ok=False, result={'error': error_msg}, result_str=error_msg, meta_data=meta_data) + + @classmethod + def normalize_formula(cls, eq: str, *, strip_modules: bool = True) -> str: + """Validate and normalize an agent-provided formula before parsing it. + + Args: + eq: Formula text supplied by the agent. + strip_modules: Whether to remove supported module prefixes. + + Returns: + The normalized formula text.""" + if not isinstance(eq, str): + raise TypeError(f"Formula must be a string, got {type(eq).__name__}.") + eq = eq.strip() + if len(eq) > cls.MAX_FORMULA_LENGTH: + raise ValueError( + f"Formula is too long: {len(eq)} characters; " + f"maximum allowed is {cls.MAX_FORMULA_LENGTH}." + ) + eq = eq.replace("^", "**") + if strip_modules: + eq = eq.replace("np.", "").replace("numpy.", "").replace("math.", "") + return eq + + @classmethod + def parse_formula(cls, eq: str) -> engine.Expression: + """Normalize and parse a formula with constants supported by all tools. + + Args: + eq: Formula text supplied by the agent. + + Returns: + The parsed symbolic expression.""" + return engine.parse( + cls.normalize_formula(eq), + symbols={"pi": np.pi, "e": np.e}, + ) + + @classmethod + def truncate_result_str(cls, text: str) -> str: + """Bound text sent to the LLM while preserving the full raw result. + + Args: + text: Tool-result text to limit. + + Returns: + The original text or a length-limited prefix with a truncation note.""" + text = str(text) + limit = cls.MAX_RESULT_STR_LENGTH + if len(text) <= limit: + return text + suffix = "... (characters ignored)" + keep = max(0, limit - len(suffix) - 32) + ignored = len(text) - keep + suffix = f"... ({ignored} characters ignored)" + keep = max(0, limit - len(suffix)) + ignored = len(text) - keep + suffix = f"... ({ignored} characters ignored)" + return text[: max(0, limit - len(suffix))] + suffix + + @classmethod + def to_tool_list(cls, tools_used: list[str] | None = None) -> list[dict]: + """Load OpenAI-compatible function-tool definitions. + + Args: + tools_used: Tool names to include, or ``None`` for all registered tools. + + Returns: + Function-tool definitions in OpenAI-compatible format.""" + tool_list = [] + for name, tool_cls in cls.REGISTRY_DICT.items(): + if tools_used is None or tool_cls.metadata.name in tools_used: + tool_list.append(tool_cls.to_dict()) + return tool_list + + @classmethod + def load_tool_list(cls, tools_used: list[str] | None = None) -> list[dict]: + """Load tool metadata for text and JSON parsers. + + Args: + tools_used: Tool names to include, or ``None`` for all registered tools. + + Returns: + Names, descriptions, and parameter schemas for the selected tools.""" + tool_list = [] + for name, tool_cls in cls.REGISTRY_DICT.items(): + if tools_used is None or tool_cls.metadata.name in tools_used: + tool_list.append({ + "name": tool_cls.metadata.name, + "description": tool_cls.metadata.description, + "parameters": tool_cls.metadata.parameters, + }) + return tool_list + + @classmethod + def load_tool_classes(cls, tools_used: list[str] | None = None) -> list[type["BaseTool"]]: + """Load tool classes for native function calling. + + Args: + tools_used: Tool names to include, or ``None`` for all registered tools. + + Returns: + The selected registered tool classes.""" + tool_list = [] + for name, tool_cls in cls.REGISTRY_DICT.items(): + if tools_used is None or tool_cls.metadata.name in tools_used: + tool_list.append(tool_cls) + return tool_list + + @classmethod + def load_custom_tool(cls, source: str, *, path: str | Path) -> dict: + """Inspect one sandboxed ``BaseTool`` stored in a skill's ``tool.py``. + + Args: + source: Python source defining the custom tool. + path: Origin path used for diagnostics and source identity. + + Returns: + Metadata and a sandbox-backed proxy class for the tool.""" + path = Path(path).resolve() + if path.suffix != ".py": + raise ValueError(f"Custom tool source must be a Python file: {path}") + from .sandboxed_custom_tool import create_sandboxed_custom_tool + + for registered_name, registered_cls in list(cls.REGISTRY_DICT.items()): + if getattr(registered_cls, "source_path", None) == path: + del cls.REGISTRY_DICT[registered_name] + registry_before = dict(cls.REGISTRY_DICT) + try: + if len(source) > 50_000: + raise ValueError("Custom tool source exceeds 50000 characters") + # Parsing is side-effect free and preserves a useful SyntaxError for authors; + # importing and inspecting the module still happens only in the sandbox. + compile(source, str(path), "exec", dont_inherit=True) + tool_cls = create_sandboxed_custom_tool(source, path) + tool_name = tool_cls.metadata.name.strip() + if tool_name in registry_before: + raise ValueError(f"Tool name '{tool_name}' is already registered.") + cls.register(tool_name)(tool_cls) + return { + "tool_name": tool_name, + "path": str(path), + "class_name": tool_cls.__name__, + "tool_class": tool_cls, + } + except Exception: + cls.REGISTRY_DICT.clear() + cls.REGISTRY_DICT.update(registry_before) + raise + + @classmethod + def discover_custom_tools(cls, skill_manager: SkillManager) -> list[type["BaseTool"]]: + # 将 skill_manager 中发现的自定义工具注册到 BaseTool,并返回 tool class list + """Discover custom tools. + + Args: + skill_manager: The skill manager value. + + Returns: + list[type['BaseTool']]: The operation result. + """ + custom_tool_cls_list = [] + for skill, source in skill_manager.load_tool_skills(): + tool_path = skill.skill_directory / "tool.py" + try: + loaded = cls.load_custom_tool(source, path=tool_path) + custom_tool_cls_list.append(cls.REGISTRY_DICT[loaded["tool_name"]]) + except Exception as e: + _logger.warning(f"Skipping custom tool {tool_path}: {log_exception(e)}") + return custom_tool_cls_list + + @classmethod + def to_dict(cls) -> dict: + """Export an OpenAI-compatible function-tool definition. + + Returns: + The tool name, description, and JSON parameter schema.""" + return { + "type": "function", + "function": { + "name": cls.metadata.name, + "description": cls.metadata.description, + "parameters": cls.metadata.parameters + }, + } + + @classmethod + def infer_tool_description(cls) -> str: + """Extract a tool description from the text before ``Args`` in ``execute``. + + Returns: + The inferred description or a placeholder when none is provided.""" + doc = getattr(cls.execute, "__doc__", None) or "" + description_lines = [] + for line in doc.splitlines(): + line = line.strip() + if line == "Args:": + break + if line: + description_lines.append(line) + return "\n".join(description_lines) if description_lines else "(no description provided)" + + @classmethod + def infer_tool_parameters(cls) -> Dict[str, Any]: + """Infer a parameter schema from the ``execute`` signature and docstring. + + Automatic inference covers common Python and typing annotations. Complex constraints, enumerations, and formats should be declared explicitly in ``ToolMetadata.parameters``. + + Returns: + An object-shaped JSON schema for model-supplied arguments.""" + properties = {} + required = [] + + try: + sig = signature(cls.execute) + type_hints = get_type_hints(cls.execute) + descriptions = cls.parse_args_docstring(cls.execute) + except Exception as e: + _logger.warning(f"Failed to parse signature or type hints for {cls.__name__} since [{type(e).__name__}] {e}") + return {} + + for param_name, param in sig.parameters.items(): + if param_name == 'self': + continue + if param.kind in (Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD): + _logger.warning( + f"Parameter '{param_name}' in {cls.__name__}.execute is a variable positional or keyword parameter, " + f"which is not supported for automatic schema inference and will be ignored. " + f"Please specify its schema manually in ToolMetadata.parameters if needed." + ) + continue + + schema = {} + annotation = type_hints.get(param_name, param.annotation) # e.g., List[int], Optional[str], etc. + schema |= cls.parse_args_typehints(annotation) # e.g., {"type": "array", "items": {"type": "integer"}} for List[int] + schema |= {'description': descriptions[param_name]} + if param.default is not Parameter.empty: + schema |= {'default': param.default} + else: + required.append(param_name) + properties[param_name] = schema + + return { + "type": "object", + "properties": properties, + "required": required, + } + + @staticmethod + def parse_args_docstring(func: callable) -> dict[str, str]: + """Extract argument descriptions from a Google-style docstring. + + Args: + func: Callable whose docstring describes its parameters. + + Returns: + Descriptions keyed by parameter name.""" + docstring = getattr(func, "__doc__", None) + parsed = parse(docstring, style=DocstringStyle.GOOGLE) + description_dict = {} + for param in parsed.params: + if param.description is not None: + description_dict[param.arg_name] = param.description + set1 = set(description_dict.keys()) + set2 = set(signature(func).parameters.keys()) - {"self"} + if set1 - set2: + _logger.warning( + f"Descriptions found for parameters {set1 - set2} in {func.__qualname__} docstring, " + f"but these parameters are not in the function signature. Please check for typos or remove these descriptions." + ) + if set2 - set1: + _logger.warning( + f"Parameters {set2 - set1} in {func.__qualname__} signature do not have descriptions in the docstring. " + f"Please add descriptions for better LLM understanding." + ) + description_dict = description_dict | {param: "(no description provided)" for param in set2 - set1} + return description_dict + + @classmethod + def parse_args_typehints(cls, annotation: Any) -> Dict[str, Any]: + """Convert a common Python type annotation to JSON Schema. + + Args: + annotation: Type annotation to convert. + + Returns: + A JSON Schema fragment.""" + if annotation is Parameter.empty or annotation is Any: + return {} + + origin = get_origin(annotation) # e.g., list, dict, Union, etc. + args = get_args(annotation) # e.g., (int,) for List[int], (str, NoneType) for Optional[str], etc. + + if origin is Literal: + values = list(args) + schema = {"enum": values} + if non_none_values := [v for v in values if v is not None]: + schema["type"] = cls.parse_json_type(type(non_none_values[0])) + return schema + elif origin is list: + return {"type": "array", "items": cls.parse_args_typehints(args[0] if args else Any)} + elif origin is dict: + return {"type": "object"} + elif origin is tuple: + # Tuple without type args + if not args: + return {"type": "array", "items": {}} + # Variable-length tuple, e.g. Tuple[str, ...] + elif args[-1] is Ellipsis: + return {"type": "array", "items": cls.parse_args_typehints(args[0] if args else Any)} + item_schemas = [cls.parse_args_typehints(arg) for arg in args] + # Homogeneous fixed tuple, e.g. Tuple[str, str] + if all(schema == item_schemas[0] for schema in item_schemas): + return {"type": "array", "items": item_schemas[0], "minItems": len(args), "maxItems": len(args)} + # Heterogeneous fixed tuple, e.g. Tuple[str, int] + else: + # This is less position-strict than prefixItems, but more compatible with OpenAI/Azure/OpenRouter tool schemas. + # It means each item may match any of the tuple element schemas, while minItems/maxItems still enforce tuple length. + _logger.warning( + f"Tuple parameter with heterogeneous types detected in {cls.__name__}.execute. " + f"This is not recommended since it may lead to less precise schema and LLM confusion. " + f"Please consider using a more specific schema or adding descriptions to clarify the expected format." + ) + return {"type": "array", "items": {"anyOf": item_schemas}, "minItems": len(args), "maxItems": len(args)} + elif origin in (Union, UnionType): + schemas = [{"type": "null"} if arg is NoneType else cls.parse_args_typehints(arg) for arg in args] + return {"anyOf": schemas} + elif json_type := cls.parse_json_type(annotation): + return {"type": json_type} + else: + _logger.warning( + f"Unsupported type annotation '{annotation}' in {cls.__name__}.execute. " + f"Automatic schema inference will not be able to parse this type, and it will be treated as an untyped parameter. " + f"Please consider using basic types (int, float, str, bool) or common generics (List, Dict) for better compatibility, " + f"or directly specify the parameter schema in ToolMetadata.parameters if a more complex structure is needed." + ) + return {} + + @staticmethod + def parse_json_type(value_type: Any) -> str: + """Map a Python literal type to a JSON Schema type name. + + Args: + value_type: Python type to inspect. + + Returns: + A JSON type name, or an empty string for an unsupported type.""" + if value_type is bool: + return "boolean" + if value_type is int: + return "integer" + if value_type is float: + return "number" + if value_type is str: + return "string" + if value_type is list: + return "array" + if value_type is dict: + return "object" + return "" + + @classmethod + def calculate_metrics(cls, f: engine.Expression, y_true: np.ndarray, y_pred: np.ndarray) -> Dict[str, Any]: + """Calculate metrics for precomputed target and prediction arrays. + + This helper lets code-defined models reuse the symbolic tools' metric definitions. + + Args: + f: Candidate expression used to compute structural complexity. + y_true: Observed target values. + y_pred: Predicted target values. + + Returns: + Fit, correlation, information-criterion, and complexity metrics.""" + return evaluator_utils.regression_metrics(f, y_true, y_pred) + + def evaluate( + self, + f: engine.Expression, + y: engine.Expression, + show_diagnostics: bool = True, + fit: bool = False, + ) -> Dict[str, Any]: + """Evaluate a symbolic prediction against a symbolic target. + + Metrics, including formula complexity, are supplied by the active evaluator. Residual diagnostics include an error profile, worst samples, and strong residual-variable correlations. + + Args: + f: Symbolic prediction expression. + y: Symbolic target expression. + show_diagnostics: Whether to include residual diagnostics. + fit: Whether to fit parameters on the training split before scoring. + + Returns: + Candidate eligibility and metrics for each available data split.""" + if not isinstance(f, engine.Expression) or not isinstance(y, engine.Expression): + raise TypeError("f and y must both be sr_harness_engine.Expression instances.") + if self.context.target is None: + raise ValueError("context.target must be configured before evaluating formulas") + + evaluator = self.context.evaluator + + target = self.context.target + var_names = {var.name for var in f.iter_preorder() if isinstance(var, engine.Variable)} + ineligibility_reasons = [] + if y.to_str() != target: + ineligibility_reasons.append(f"the left-hand side of the equation is not {target}") + if target in var_names: + ineligibility_reasons.append(f"the right-hand side of the equation depends on {target}") + is_candidate = not ineligibility_reasons + + isolated_evaluation = getattr(evaluator, "_evaluate_formula_isolated", None) + isolated_metrics = None + if isolated_evaluation is not None: + fitted_f, isolated_metrics, isolated_splits = isolated_evaluation( + f, y, self.context, fit=fit, candidate=is_candidate, + ) + train_context = isolated_splits["train"] + validation_context = isolated_splits["validation"] + self.context._split_cache = isolated_splits + else: + train_context = self.context.train_split + validation_context = self.context.validation_split + + fitted_f = fitted_f if isolated_metrics is not None else f + if fit and isolated_metrics is None: + fitted_f = ( + evaluator.fit_candidate(f, train_context) + if is_candidate + else evaluator.fit(f, y, train_context) + ) + if not isinstance(fitted_f, engine.Expression): + raise TypeError(f"{type(evaluator).__name__}.fit() must return an Expression") + if missing := engine.unbound_parameters(fitted_f): + raise ValueError(f"unbound parameters: {', '.join(missing)}") + + def evaluate_split(split_context: AgentContext, *, max_samples: int | None = None): + result = isolated_metrics.get("train" if split_context is train_context else "validation") if isolated_metrics is not None else ( + evaluator.evaluate_candidate(fitted_f, split_context) + if is_candidate + else evaluator.evaluate(fitted_f, y, split_context) + ) + if not isinstance(result, dict): + raise TypeError(f"{type(evaluator).__name__}.evaluate() must return a dictionary") + metrics = {} + for name, value in result.items(): + if isinstance(value, (bool, np.bool_)) or not isinstance(value, Real): + raise TypeError(f"Evaluator metric {name!r} must be a float or int") + metrics[str(name)] = value.item() if isinstance(value, np.generic) else value + split = {"metrics": metrics} + if show_diagnostics: + num_nodes = split_context.num_nodes + split["diagnostics"] = self.residual_diagnostics( + y_true=np.asarray(y.eval(split_context.data, num_nodes=num_nodes)), + y_pred=np.asarray(fitted_f.evaluate(split_context.data, num_nodes=num_nodes)), + data=split_context.data, + target_expression=y.to_str(), + **({"max_samples": max_samples} if max_samples is not None else {}), + ) + return split + + data_split_results = {"train": evaluate_split(train_context, max_samples=10)} + if validation_context.data: + data_split_results["validation"] = evaluate_split(validation_context) + for split_name, split_result in data_split_results.items(): + metrics = split_result.get("metrics") or {} + if not np.isfinite(metrics.get("mse", float("nan"))): + ineligibility_reasons.append( + f"the formula does not produce a finite MSE on the {split_name} set" + ) + evaluation = { + "formula": fitted_f.to_str(number_format='.8g'), + "target_expression": y.to_str(number_format='.8g'), + "is_candidate": not ineligibility_reasons, + "candidate_ineligibility_reasons": ineligibility_reasons, + "data_split_results": data_split_results, + } + return evaluation + + def failed_evaluation(self, formula: str = "(None)") -> Dict[str, Any]: + """Build the common result shape when a formula-producing backend fails. + + Args: + formula: Formula or placeholder to report. + Returns: + A non-candidate result with infinite error metrics.""" + empty_metrics = { + "mse": float("inf"), + "rmse": float("inf"), + "mae": float("inf"), + "mape": float("inf"), + "r2": -float("inf"), + "aic": float("inf"), + "bic": float("inf"), + "pearson_r": -float("inf"), + "spearman_r": -float("inf"), + "complexity": float("inf"), + } + data_split_results = { + 'train': {'metrics': None}, + 'validation': {'metrics': None}, + } + if self.context.target is None: + raise ValueError("context.target must be configured before reporting a failed evaluation") + data_split_results['train']['metrics'] = empty_metrics + if not self.context.validation_split.data: + data_split_results.pop('validation') + else: + data_split_results['validation']['metrics'] = empty_metrics + return { + "formula": formula, + "target_expression": self.context.target, + "is_candidate": False, + "candidate_ineligibility_reasons": ["no valid formula was produced"], + "data_split_results": data_split_results, + } + + @classmethod + def format_evaluation_result(cls, result: Dict[str, Any], title: str = "Formula evaluation") -> str: + """Format the common formula-evaluation schema for an LLM. + + Args: + result: Evaluation mapping produced by ``evaluate``. + title: Heading shown above the formatted result. + + Returns: + Concise formula, metric, warning, and diagnostic text.""" + split_results = result["data_split_results"] + train_result = split_results["train"] + metrics = train_result["metrics"] + lhs = result.get("target_expression", "LHS") + formula = result["formula"] + try: + formula = engine.parse(formula).to_str( + number_format=cls.FORMULA_DISPLAY_NUMBER_FORMAT + ) + except Exception: + # Some tools use a free-form model description instead of an + # SRHarness Engine expression. Preserve those descriptions verbatim. + pass + lines = [ + f"{title}:", + f" {lhs} = {formula}", + ] + for reason in result.get("candidate_ineligibility_reasons", []): + lines.append(f" (Note: this formula is not eligible for submission since {reason}.)") + validation_result = split_results.get("validation") + validation_metrics = validation_result["metrics"] if validation_result else None + + def three_significant_digits(value: Any) -> str: + if isinstance(value, (int, float, np.number)): + return format(value, "#.3g").removesuffix(".") + return str(value) + + def metric_pair(name: str) -> str: + train_value = three_significant_digits(metrics.get(name, float("nan"))) + validation_value = ( + three_significant_digits(validation_metrics.get(name, float("nan"))) + if validation_metrics else "N/A" + ) + return f"{train_value} | {validation_value}" + + lines.extend([ + "Fit quality (Train-set | Validation-set):", + f" RMSE={metric_pair('rmse')};", + f" MAE={metric_pair('mae')};", + f" R2={metric_pair('r2')};", + f" Formula Complexity={three_significant_digits(metrics.get('complexity', '?'))};", + ]) + standard_metric_names = { + "mse", "rmse", "mae", "mape", "r2", "aic", "bic", + "pearson_r", "spearman_r", "complexity", + } + custom_metric_names = sorted( + (set(metrics) | set(validation_metrics or {})) - standard_metric_names + ) + if custom_metric_names: + lines.append("Evaluator-specific metrics (Train-set | Validation-set):") + lines.extend( + f" {name}={metric_pair(name)};" for name in custom_metric_names + ) + if validation_metrics: + train_rmse = metrics.get("rmse", float("nan")) + validation_rmse = validation_metrics.get("rmse", float("nan")) + if (np.isfinite(train_rmse) and np.isfinite(validation_rmse) + and validation_rmse > max(2.0 * train_rmse, train_rmse + 1e-12)): + lines.append( + "Warning: validation error is substantially larger than training error; " + "the candidate may be overfitting or the validation domain may differ." + ) + if diagnostics := train_result.get("diagnostics"): + samples = diagnostics.get("worst_samples", [])[:10] + if samples: + input_names = result.get("analyzed_input_expressions") or [ + name for name in samples[0]["row"] if name != lhs + ] + lines.extend([ + "Error extremes (Top-10 sorted by |residual|):", + f" ({' | '.join([*input_names, lhs, 'residual'])})", + ]) + for sample in samples: + values = [sample["row"].get(name, float("nan")) for name in input_names] + values.extend([sample["y_true"], sample["y_pred"] - sample["y_true"]]) + lines.append(" " + " | ".join(three_significant_digits(value) for value in values)) + if correlations := diagnostics.get("strongest_residual_correlations"): + strongest = correlations[0] + lines.extend([ + "Largest residual correlation among other analyzed variables " + "(criterion=max(|Pearson|, |Spearman|)):", + f" variable={strongest['variable']}", + f" Pearson(residual, {strongest['variable']})={three_significant_digits(strongest['pearson'])};", + f" Spearman(residual, {strongest['variable']})={three_significant_digits(strongest['spearman'])};", + ]) + return "\n".join(lines) + + @classmethod + def residual_diagnostics( + cls, + y_true: np.ndarray, + y_pred: np.ndarray, + data: Dict[str, Any] = None, + target_expression: str = None, + max_samples: int = 3, + max_correlations: int = 5, + ) -> Dict[str, Any]: + """Return compact diagnostics for prediction residuals. + + Args: + y_true: Observed target values. + y_pred: Predicted target values. + data: Optional variables used to explain residual patterns. + target_expression: Target label included in diagnostic rows. + max_samples: Maximum number of worst samples to include. + max_correlations: Maximum number of residual correlations to include. + + Returns: + Error profile, worst samples, and strongest residual correlations.""" + y_true, y_pred = np.broadcast_arrays( + np.asarray(y_true, dtype=float), + np.asarray(y_pred, dtype=float), + ) + y_true = y_true.flatten() + y_pred = y_pred.flatten() + residual = y_pred - y_true + absolute_error = np.abs(residual) + finite_error = np.isfinite(residual) + + target_scale = float(np.median(np.abs(y_true[np.isfinite(y_true)]))) if np.any(np.isfinite(y_true)) else 0.0 + relative_floor = max(np.finfo(float).eps, target_scale * 1e-12) + relative_valid = finite_error & np.isfinite(y_true) & (np.abs(y_true) > relative_floor) + relative_error = np.full_like(absolute_error, np.nan, dtype=float) + relative_error[relative_valid] = absolute_error[relative_valid] / np.abs(y_true[relative_valid]) + + finite_absolute = absolute_error[finite_error] + finite_relative = relative_error[np.isfinite(relative_error)] + error_profile = { + "median_signed_residual": float(np.median(residual[finite_error])) if np.any(finite_error) else float("nan"), + "p95_absolute_error": float(np.quantile(finite_absolute, 0.95)) if finite_absolute.size else float("nan"), + "max_absolute_error": float(np.max(finite_absolute)) if finite_absolute.size else float("nan"), + "p95_relative_error": float(np.quantile(finite_relative, 0.95)) if finite_relative.size else float("nan"), + "max_relative_error": float(np.max(finite_relative)) if finite_relative.size else float("nan"), + "relative_error_defined_ratio": float(np.mean(relative_valid)), + } + + numeric_data = {} + for name, values in (data or {}).items(): + array = np.asarray(values) + if array.size == y_true.size and np.issubdtype(array.dtype, np.number): + numeric_data[name] = array.flatten() + + rank_score = np.where(finite_error, absolute_error, -np.inf) + sample_limit = max(0, int(max_samples)) + worst_indices = ( + np.argsort(rank_score)[-sample_limit:][::-1] + if sample_limit else np.array([], dtype=int) + ) + worst_samples = [] + for index in worst_indices: + if not np.isfinite(rank_score[index]): + continue + worst_samples.append({ + "index": int(index), + "row": {name: float(values[index]) for name, values in numeric_data.items()}, + "y_true": float(y_true[index]), + "y_pred": float(y_pred[index]), + "absolute_error": float(absolute_error[index]), + "relative_error": float(relative_error[index]), + }) + + correlation_arrays = dict(numeric_data) + if target_expression and target_expression not in correlation_arrays: + correlation_arrays[target_expression] = y_true + correlations = [] + for name, values in correlation_arrays.items(): + pearson, spearman = cls.correlation_coefficients(values, residual) + strength = max(abs(pearson), abs(spearman)) + if np.isfinite(strength): + correlations.append({ + "variable": name, + "pearson": pearson, + "spearman": spearman, + "strength": strength, + }) + correlations.sort(key=lambda item: item["strength"], reverse=True) + + return { + "error_profile": error_profile, + "worst_samples": worst_samples, + "strongest_residual_correlations": correlations[:max(0, int(max_correlations))], + } + + @staticmethod + def correlation_coefficients(x: np.ndarray, y: np.ndarray) -> tuple[float, float]: + """Return finite-sample Pearson and Spearman coefficients. + + Undefined correlations, including constant inputs, are returned as NaN. Warnings for these mathematically valid edge cases are suppressed. + + Args: + x: First numeric sample. + y: Second numeric sample. + + Returns: + Pearson and Spearman correlation coefficients.""" + x = np.asarray(x, dtype=float).flatten() + y = np.asarray(y, dtype=float).flatten() + finite = np.isfinite(x) & np.isfinite(y) + if np.count_nonzero(finite) < 2: + return float("nan"), float("nan") + x, y = x[finite], y[finite] + with np.errstate(invalid="ignore", divide="ignore"), warnings.catch_warnings(): + warnings.simplefilter("ignore") + pearson = float(np.corrcoef(x, y)[0, 1]) + spearman = float(stats.spearmanr(x, y).statistic) + return pearson, spearman + + +def is_numeric_array(data: List[Any]) -> bool: + """Run the ``is numeric array`` operation. + + Args: + data: Data arrays keyed by variable name. + + Returns: + bool: The operation result. + """ + arr = np.asarray(data) + return np.issubdtype(arr.dtype, np.integer) or np.issubdtype(arr.dtype, np.floating) diff --git a/src/sr_harness/tools/call_llm.py b/src/sr_harness/tools/call_llm.py new file mode 100644 index 0000000000000000000000000000000000000000..b87e35eebf107961bad60ccd967e0cfae5586199 --- /dev/null +++ b/src/sr_harness/tools/call_llm.py @@ -0,0 +1,36 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""LLM 调用工具。提供统一的 LLM 调用接口,支持多种 LLM 提供商。""" + +from typing import Dict, Any, List +from .base_tool import BaseTool, ToolMetadata + + +# @BaseTool.register('call_llm') # 不注册这个工具,因为它用处不大 +class LLMTool(BaseTool): + """Implementation of the l l m tool.""" + metadata = ToolMetadata(name="call_llm") + + def execute( + self, + llm_provider: str, + llm_model: str, + messages: List[Dict[str, str]] | str, + ) -> Dict[str, Any]: + """Call LLM API. + + Args: + llm_provider: LLM provider name, e.g., "openai", "deepseek", "gemini". + llm_model: Model name, e.g., "gpt-4o-mini", "deepseek-chat". + messages: List of messages, each as [{"role": "user"|"assistant", "content": "..."}, ...]. + """ + from ..api import BaseAPI + + api = BaseAPI.create(llm_provider, model=llm_model) + content = "" + for response in (llm_result := api(messages, n=1)): + content = response.content or "" + return { + "content": content, + "token_usage": llm_result.token_usage, + "money_usage": llm_result.money_usage, + } diff --git a/src/sr_harness/tools/call_pysr.py b/src/sr_harness/tools/call_pysr.py new file mode 100644 index 0000000000000000000000000000000000000000..9e941e659934bb6b10121990ffae0d9d49e6314c --- /dev/null +++ b/src/sr_harness/tools/call_pysr.py @@ -0,0 +1,284 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""PySR 符号回归工具。 + +调用 PySR (https://github.com/MilesCranmer/PySR) 进行基于遗传规划的符号回归, +使用 Julia 后端的 SymbolicRegression.jl 进化搜索简洁的数学表达式。 +""" +import re +import os +import logging +import numpy as np +from pathlib import Path +from typing import Dict, Any, List +from .base_tool import BaseTool, ToolMetadata, is_numeric_array + +_logger = logging.getLogger(f'sr_harness.{__name__}') + +DEFAULT_TIMEOUT = 30 +MAX_TIMEOUT = 120 + + +@BaseTool.register('call_pysr') +class PySRTool(BaseTool): + """Implementation of the py s r tool.""" + metadata = ToolMetadata(name="call_pysr") + UNARY_ALIASES = { + "acos": "acos", + "arccos": "acos", + "arcsin": "asin", + "arctan": "atan", + "asin": "asin", + "atan": "atan", + "lg": "log10", + "ln": "log", + } + + def execute( + self, + binary_operators: List[str], + unary_operators: List[str], + x: List[str] = None, + y: str = None, + timeout: int = 30, + maxsize: int = 25, + max_samples: int = 500, + show_diagnostics: bool = True, + ) -> Dict[str, Any]: + """Run PySR (genetic programming symbolic regression) to evolve mathematical expressions that fit the data. + PySR perform evolutionary search for symbolic formulas. + It is powerful for discovering complex nonlinear relationships including trigonometric, exponential, sqrt, and nested functions. + However, it is also computationally intensive and requires careful tuning of operators and variables to find good formulas within reasonable time. + You MUST specify the binary and unary operators based on your hypothesis about the data. + + This tool can return candidate formulas for submission when `y` is the target variable and `x` does not depend on the target variable. + + Args: + binary_operators: List of binary operators for PySR to use. Choose from: "+", "-", "*", "/", "^". + Select operators you believe are relevant to the underlying formula. + unary_operators: List of unary operators for PySR to use. Choose from: "sin", "cos", "exp", "log", "sqrt", "square", "cube", "abs", "tanh", "sign". Select operators based on your hypothesis about the data. + x: List of input feature names to use. If not specified, all features except target are used. + Expressions are also supported, e.g., ["sin(x1)", "(x1-x2)**2"]. + y: Target variable name. If not specified, the default target variable is used. + Expressions are also supported, e.g., "log(y)", "y - x1" + timeout: Maximum search time in seconds (default 30, max 120). + If PySR did not find a good formula in a previous run, increase timeout (e.g., 60 or 90) to give it more search time. + maxsize: Maximum expression complexity in number of nodes (10-40). Larger allows more complex formulas. + max_samples: Maximum number of data samples to use for fitting (for speed). Data is subsampled if larger. + show_diagnostics: Whether final metrics should include compact residual diagnostics. + """ + data = self.context.data + y = y if y is not None else self.context.target + if y is None: + raise ValueError("y is required when context.target is not configured") + y = y.strip().strip('"').strip("'") + x = x or [var for var in data if var != y and is_numeric_array(data[var])] + exceptions = [] + + # Clamp timeout + timeout = max(10, min(timeout, MAX_TIMEOUT)) + + try: + eq_y = self.parse_formula(y) + data_y = eq_y.eval(data).flatten() + if not is_numeric_array(data_y): + raise ValueError(f"Target '{y}' did not produce numeric values.") + except Exception as e: + raise ValueError( + f"Failed to compute target '{y}': {str(e)}" + + "\nOther exceptions: " + "; ".join(exceptions) + ) + y_vec = data_y + + features = {'exprs': [], 'arrays': [], 'internal_names': [], 'original_exprs': []} + for idx, xi in enumerate(x, 1): + try: + eq_x = self.parse_formula(xi) + data_x = eq_x.eval(data).flatten() + if not is_numeric_array(data_x): + raise ValueError(f"Feature '{xi}' did not produce numeric values.") + features['exprs'].append(eq_x) + features['arrays'].append(data_x) + features['internal_names'].append(f"x{idx}") + features['original_exprs'].append(xi) + assert data_x.shape == data_y.shape, f"Feature '{xi}' shape {data_x.shape} does not match target shape {data_y.shape}." + except Exception as e: + exceptions.append(f"Failed to compute feature '{xi}': {str(e)}") + if len(features['exprs']) == 0: + raise ValueError( + "No valid input variables available for fitting.\n" + + "Other exceptions: " + "; ".join(exceptions) + ) + X_matrix = np.column_stack(features['arrays']) + + # Subsample if too many points + if len(y_vec) > max_samples: + rng = np.random.default_rng(42) + idx = rng.choice(len(y_vec), size=max_samples, replace=False) + X_fit = X_matrix[idx] + y_fit = y_vec[idx] + else: + X_fit = X_matrix + y_fit = y_vec + + unary_operators = [self.UNARY_ALIASES.get(name, name) for name in unary_operators] + formula_str, pareto_front, _ = self._run_pysr( + X_fit, y_fit, features['internal_names'], binary_operators, unary_operators, + timeout, maxsize + ) + formula_str = self._restore_feature_names(formula_str, features['internal_names'], features['original_exprs']) + eq_f = self.parse_formula(formula_str) + evaluation = self.evaluate(f=eq_f, y=eq_y, show_diagnostics=show_diagnostics) + all_formulas = [] + for item in pareto_front: + formula = self._restore_feature_names(item["formula"], features['internal_names'], features['original_exprs']) + try: + eq_f_pareto = self.parse_formula(formula) + detail = self.evaluate(f=eq_f_pareto, y=eq_y, show_diagnostics=False) + all_formulas.append(detail) + except Exception as e: + exceptions.append(f"Failed to evaluate formula {formula!r}: {type(e).__name__}: {e}") + + # Generate retry hint if result is poor and timeout can be increased + retry_hint = None + split_results = evaluation["data_split_results"] + selected_split = "validation" if "validation" in split_results else "train" + selected_metrics = split_results[selected_split]["metrics"] + mse = selected_metrics.get("mse", float("inf")) + if mse > 1e-3 and timeout < MAX_TIMEOUT: + suggested_timeout = min(timeout * 2, MAX_TIMEOUT) + retry_hint = ( + f"PySR did not find a good formula within {timeout}s. " + f"Consider retrying with timeout={suggested_timeout} for more thorough search." + ) + + return { + **evaluation, + "method": "PySR", + # "backend_complexity": complexity, + "all_formulas": all_formulas, + "config": { + "timeout": timeout, + "maxsize": maxsize, + "binary_operators": binary_operators, + "unary_operators": unary_operators, + }, + "exceptions": exceptions, + "retry_hint": retry_hint, + } + + def _run_pysr(self, X, y, x_names, binary_ops, unary_ops, timeout, maxsize): + """Run PySR (Julia-based symbolic regression).""" + # ``juliapkg`` otherwise follows an active CONDA_PREFIX when this + # project's Python executable is symlinked into a virtualenv. That + # prefix may be system-owned, so use a writable per-user project. + if "PYTHON_JULIAPKG_PROJECT" not in os.environ: + cache_root = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) + julia_project = cache_root / "sr_harness" / "julia_env" + julia_project.mkdir(parents=True, exist_ok=True) + os.environ["PYTHON_JULIAPKG_PROJECT"] = str(julia_project) + os.environ['PYTHON_JULIACALL_HANDLE_SIGNALS'] = 'yes' + + from pysr import PySRRegressor + import tempfile + + tmpdir = tempfile.mkdtemp(prefix="pysr_") + + try: + model = PySRRegressor( + niterations=100, + timeout_in_seconds=timeout, + maxsize=maxsize, + populations=15, + binary_operators=binary_ops, + unary_operators=unary_ops, + temp_equation_file=True, + tempdir=tmpdir, + verbosity=0, + progress=False, + parallelism='serial', + random_state=42, + ) + model.fit(X, y, variable_names=x_names) + + # Get all equations sorted by loss, pick the one with lowest loss + eqs_df = model.equations_ + best_row = eqs_df.loc[eqs_df['loss'].idxmin()] + formula_str = str(best_row['equation']) + formula_str = self._clean_pysr_formula(formula_str, x_names) + complexity = int(best_row.get('complexity', 0)) + + pareto_front = [] + for _, row in eqs_df.nsmallest(min(5, len(eqs_df)), 'loss').iterrows(): + pareto_front.append({ + "formula": self._clean_pysr_formula(str(row['equation']), x_names), + "loss": float(row['loss']), + "complexity": int(row['complexity']), + }) + + return formula_str, pareto_front, complexity + finally: + import shutil + shutil.rmtree(tmpdir, ignore_errors=True) + + def _clean_pysr_formula(self, formula: str, x_names: List[str]) -> str: + """Clean PySR output for SRHarness Engine compatibility. + PySR already uses variable_names in output when provided via fit(), + so we only need to handle special functions and operators. + """ + formula = formula.strip() + formula = formula.replace("square(", "pow2(") + formula = formula.replace("cube(", "pow3(") + formula = formula.replace("^", "**") + return formula if formula else "0" + + def _restore_feature_names( + self, + formula: str, + internal_names: List[str], + original_expressions: List[str], + ) -> str: + """Replace PySR feature names with original variables or expressions.""" + restored = formula + replacements = dict(zip(internal_names, original_expressions)) + placeholders = {name: f"__pysr_feature_{idx}__" for idx, name in enumerate(replacements)} + for name in sorted(replacements, key=len, reverse=True): + restored = re.sub(rf"\b{re.escape(name)}\b", placeholders[name], restored) + for name, expr in replacements.items(): + expr = expr.replace("^", "**").replace("np.", "") + restored = restored.replace(placeholders[name], f"({expr})") + try: + restored = self.parse_formula(restored).to_str() + except: + _logger.warning(f"Failed to parse restored formula {restored!r}, returning unparsed version.") + return restored + + @classmethod + def format_result_dict(cls, result: Dict[str, Any]) -> str: + """Format a tool result for the language model. + + Args: + result: Result mapping to format or update. + + Returns: + str: The operation result. + """ + parts = [ + f"Symbolic-regression backend used: {result['method']}.", + cls.format_evaluation_result(result, title="Best formula found"), + ] + if result.get('all_formulas'): + parts.append("Other formulas offering accuracy-versus-complexity trade-offs:") + for eq in result['all_formulas'][:5]: + split_results = eq["data_split_results"] + split_name = "validation" if "validation" in split_results else "train" + metrics = split_results[split_name]["metrics"] + rmse = metrics.get("rmse", np.sqrt(metrics.get("mse", float("nan")))) + parts.append( + f" - {eq['formula']} | {split_name.title()} RMSE={rmse:.6g}, " + f"formula complexity={metrics['complexity']}" + ) + if result.get('retry_hint'): + parts.append(f"Retry suggestion: {result['retry_hint']}") + if result.get('exceptions'): + parts.append(f"Warnings: {'; '.join(result['exceptions'])}") + return "\n".join(parts) diff --git a/src/sr_harness/tools/call_sindy.py b/src/sr_harness/tools/call_sindy.py new file mode 100644 index 0000000000000000000000000000000000000000..d693e395b2bd9d0638089dfbca65e7b6b23d5417 --- /dev/null +++ b/src/sr_harness/tools/call_sindy.py @@ -0,0 +1,275 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""SINDy 符号回归工具。 + +使用 PySINDy (Sparse Identification of Nonlinear Dynamics) 对数据进行符号回归。 +通过将目标变量 y 视为状态变量 X 的"导数",利用 SINDy 的稀疏回归框架 +发现 y = f(X) 的简洁数学表达式。 +""" +import re +import logging +import numpy as np +import sr_harness_engine as engine +from typing import Dict, Any, List +from .base_tool import BaseTool, ToolMetadata, is_numeric_array + +_logger = logging.getLogger(f'sr_harness.{__name__}') + + +@BaseTool.register('call_sindy') +class SINDyTool(BaseTool): + """Implementation of the s i n dy tool.""" + metadata = ToolMetadata(name="call_sindy") + + def execute( + self, + x: List[str] = None, + y: str = None, + poly_degree: int = 3, + include_trig: bool = False, + threshold: float = 0.1, + max_samples: int = 5000, + show_diagnostics: bool = True, + ) -> Dict[str, Any]: + """Run SINDy (Sparse Identification of Nonlinear Dynamics) to discover symbolic expressions from data. + SINDy builds a library of candidate nonlinear functions and uses sparse regression (STLSQ) to find + a parsimonious combination that explains the target variable. + Best suited for polynomial, interaction, and trigonometric relationships. + + This tool can return candidate formulas for submission when `y` is the target variable and `x` does not depend on the target variable. + + Args: + x: List of input feature names to use. If not specified, all features except target are used. + Expressions are also supported, e.g., ["sin(x1)", "(x1-x2)**2"]. + y: Target variable name. If not specified, the default target variable is used. + Expressions are also supported, e.g., "log(y)", "y - x1" + poly_degree: Maximum polynomial degree for the feature library (1-5). Higher values find more complex relationships but are slower. + include_trig: Whether to include sin/cos terms in the feature library. Enable this if you suspect trigonometric relationships. + threshold: Sparsity threshold for STLSQ optimizer (0.01-1.0). Larger values produce sparser (simpler) formulas. + max_samples: Maximum number of data samples to use for fitting (for speed). Data is subsampled if larger. + show_diagnostics: Whether final metrics should include compact residual diagnostics. + """ + data = self.context.data + y = y if y is not None else self.context.target + if y is None: + raise ValueError("y is required when context.target is not configured") + y = y.strip().strip('"').strip("'") + x = x or [var for var in data if var != y and is_numeric_array(data[var])] + exceptions = [] + + poly_degree = max(1, min(poly_degree, 5)) + threshold = max(0.01, min(threshold, 1.0)) + + try: + eq_y = self.parse_formula(y) + data_y = eq_y.eval(data).flatten() + if not is_numeric_array(data_y): + raise ValueError(f"Target '{y}' did not produce numeric values.") + except Exception as e: + raise ValueError( + f"Failed to compute target '{y}': {str(e)}" + + "\nOther exceptions: " + "; ".join(exceptions) + ) + y_vec = data_y + + features = {'exprs': [], 'arrays': [], 'internal_names': [], 'original_exprs': []} + for idx, xi in enumerate(x, 1): + try: + eq_x = self.parse_formula(xi) + data_x = eq_x.eval(data).flatten() + if not is_numeric_array(data_x): + raise ValueError(f"Feature '{xi}' did not produce numeric values.") + features['exprs'].append(eq_x) + features['arrays'].append(data_x) + features['internal_names'].append(f"x{idx}") + features['original_exprs'].append(xi) + assert data_x.shape == data_y.shape, f"Feature '{xi}' shape {data_x.shape} does not match target shape {data_y.shape}." + except Exception as e: + exceptions.append(f"Failed to compute feature '{xi}': {str(e)}") + if len(features['exprs']) == 0: + raise ValueError( + "No valid input variables available for fitting.\n" + + "Other exceptions: " + "; ".join(exceptions) + ) + X_matrix = np.column_stack(features['arrays']) + + if len(y_vec) > max_samples: + rng = np.random.default_rng(42) + idx = rng.choice(len(y_vec), size=max_samples, replace=False) + X_fit = X_matrix[idx] + y_fit = y_vec[idx] + else: + X_fit = X_matrix + y_fit = y_vec + + try: + formula_str = self._run_sindy( + X_fit, y_fit, features['internal_names'], poly_degree, include_trig, threshold + ) + if not formula_str: + raise ValueError("SINDy returned an empty formula.") + formula_str = self._restore_feature_names(formula_str, features['internal_names'], features['original_exprs']) + eq_f = self.parse_formula(formula_str) + evaluation = self.evaluate(f=eq_f, y=eq_y, show_diagnostics=show_diagnostics) + except Exception as e: + evaluation = self.failed_evaluation() + exceptions.append(f"SINDy fitting failed: {type(e).__name__}: {e}") + + return { + **evaluation, + "config": { + "method": "SINDy", + "poly_degree": poly_degree, + "include_trig": include_trig, + "threshold": threshold, + "max_samples": max_samples, + }, + "exceptions": exceptions, + } + + def _run_sindy( + self, + X, + y, + x_names: List[str], + poly_degree: int, + include_trig: bool, + threshold: float, + ) -> str: + """Run PySINDy static regression and return a cleaned formula.""" + import pysindy as ps + + feature_libs = [ps.PolynomialLibrary(degree=poly_degree, include_interaction=True)] + if include_trig: + feature_libs.append(ps.FourierLibrary(n_frequencies=2)) + + lib = ps.ConcatLibrary(feature_libs) if len(feature_libs) > 1 else feature_libs[0] + model = ps.SINDy( + feature_library=lib, + optimizer=ps.STLSQ(threshold=threshold, alpha=0.05), + ) + # Use SINDy's fit with x_dot=y to perform static regression y = f(X) + model.fit(X, t=1, x_dot=y.reshape(-1, 1), feature_names=x_names) + + equations = model.equations() + if not equations: + return "0" + return self._clean_formula(equations[0], x_names) + + def _clean_formula(self, equation_str: str, x_names: List[str]) -> str: + """Clean up SINDy output formula for SRHarness Engine.""" + formula = equation_str.strip() + # Remove leading/trailing whitespace around operators + formula = re.sub(r'\s+', ' ', formula) + formula = re.sub(r'\+\s+-', '-', formula) + + # SINDy outputs like " 1.000 x1^2 + 3.000 x1 x2" + # Parse terms: coefficient * feature_product + terms = [] + # Split on + and - while keeping the sign + parts = re.split(r'(?=[+-])', formula) + for part in parts: + part = part.strip() + if not part: + continue + # Match coefficient and variables + match = re.match(r'^([+-]?\s*[\d.]+)\s+(.+)$', part) + if match: + coef_str = match.group(1).replace(' ', '') + coef = float(coef_str) + var_part = match.group(2).strip() + if abs(coef) < 1e-10: + continue + # Clean variable part: "x1^2" -> "x1**2", "x1 x2" -> "x1*x2" + var_part = var_part.replace('^', '**') + var_part = re.sub(r'(\w)\s+(\w)', r'\1*\2', var_part) + # Round near-integer coefficients + if abs(coef - round(coef)) < 0.005 and abs(coef) < 1000: + coef = int(round(coef)) + if coef == 1: + terms.append(var_part) + elif coef == -1: + terms.append(f"-{var_part}") + else: + terms.append(f"{coef}*{var_part}") + else: + # Just a constant or something we can't parse + try: + val = float(part) + if abs(val) > 1e-10: + terms.append(str(val)) + except ValueError: + if part.strip(): + terms.append(part.strip()) + + if not terms: + return "0" + formula = " + ".join(terms) + formula = formula.replace("+ -", "- ") + return formula + + def _restore_feature_names( + self, + formula: str, + internal_names: List[str], + original_expressions: List[str], + ) -> str: + """Replace SINDy feature names with original variables or expressions.""" + restored = formula + replacements = dict(zip(internal_names, original_expressions)) + placeholders = {name: f"__sindy_feature_{idx}__" for idx, name in enumerate(replacements)} + restored = self._replace_square_calls(restored) + for name in sorted(replacements, key=len, reverse=True): + restored = re.sub(rf"\b{re.escape(name)}\b", placeholders[name], restored) + for name, expr in replacements.items(): + expr = expr.replace("^", "**").replace("np.", "") + restored = restored.replace(placeholders[name], f"({expr})") + try: + restored = self.parse_formula(restored).to_str() + except: + _logger.warning(f"Failed to parse restored formula {restored!r}, returning unparsed version.") + return restored + + @staticmethod + def _replace_square_calls(formula: str) -> str: + """Replace square(expr) with (expr)**2, preserving nested parentheses.""" + token = "square(" + while token in formula: + start = formula.find(token) + arg_start = start + len(token) + depth = 1 + idx = arg_start + while idx < len(formula) and depth: + if formula[idx] == "(": + depth += 1 + elif formula[idx] == ")": + depth -= 1 + idx += 1 + if depth: + break + arg = formula[arg_start:idx - 1] + formula = f"{formula[:start]}({arg})**2{formula[idx:]}" + return formula + + @classmethod + def format_result_dict(cls, result: Dict[str, Any]) -> str: + """Format a tool result for the language model. + + Args: + result: Result mapping to format or update. + + Returns: + str: The operation result. + """ + if result["formula"] == "(None)": + warnings = "; ".join(result.get("exceptions", [])) or "No further error detail was provided." + return f"SINDy did not produce a valid formula. Details: {warnings}" + config = result["config"] + parts = [cls.format_evaluation_result(result, title="SINDy fitted formula")] + parts.append( + f"Search configuration: polynomial degree up to {config['poly_degree']}; " + f"trigonometric features {'enabled' if config['include_trig'] else 'disabled'}; " + f"coefficient sparsity threshold={config['threshold']}." + ) + if result.get('exceptions'): + parts.append(f"Warnings: {'; '.join(result['exceptions'])}") + return "\n".join(parts) diff --git a/src/sr_harness/tools/code_executor.py b/src/sr_harness/tools/code_executor.py new file mode 100644 index 0000000000000000000000000000000000000000..b848cfe310fce4a32a8242d964e9d59e2a1eed42 --- /dev/null +++ b/src/sr_harness/tools/code_executor.py @@ -0,0 +1,155 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""Execute data-only Python programs in an operating-system sandbox.""" + +from __future__ import annotations + +import io +import json +from typing import Any, Dict + +from ..runtime import get_sandbox_runner +from ..utils import bounded_value +from .base_tool import BaseTool, ToolMetadata + + +class LimitedWriter(io.StringIO): + """String buffer retained for bounded-output shell utilities.""" + + SUFFIX = "...[truncated]" + + def __init__(self, limit: int): + super().__init__() + self.limit = limit + + def write(self, text: str) -> int: + remaining = self.limit - self.tell() - len(self.SUFFIX) + if remaining <= 0: + return len(text) + if len(text) > remaining: + super().write(text[:remaining]) + super().write(self.SUFFIX) + return len(text) + return super().write(text) + + +@BaseTool.register("code_executor") +class CodeExecutorTool(BaseTool): + """Implementation of the code executor tool.""" + + metadata = ToolMetadata(name="code_executor") + DEFAULT_TIMEOUT_SECONDS = 30 + DEFAULT_MEMORY_LIMIT_MB = 1024 + DEFAULT_OUTPUT_LIMIT_BYTES = 64 * 1024 + MAX_TIMEOUT_SECONDS = 120 + MAX_MEMORY_LIMIT_MB = 4096 + MAX_OUTPUT_LIMIT_BYTES = 1024 * 1024 + + def execute( + self, + program: str, + timeout_seconds: int = DEFAULT_TIMEOUT_SECONDS, + memory_limit_mb: int = DEFAULT_MEMORY_LIMIT_MB, + output_limit_bytes: int = DEFAULT_OUTPUT_LIMIT_BYTES, + ) -> Dict[str, Any]: + """Execute Python code and return printed output. + 1) Use `import sys, json; data_dict = json.loads(sys.stdin.read())` to + access data mapping variable names to lists. + 2) Use `print()` to produce output. + 3) The code is executed in an operating-system sandbox with resource limits. + 4) Installed scientific Python libraries are available. Files outside the + ephemeral sandbox, networking, and child-process creation are unavailable. + + Args: + program: Python code string to execute, starting with `import sys, json; + data_dict = json.loads(sys.stdin.read())` to access input data. + timeout_seconds: Wall-clock timeout in seconds. The effective value is capped. + memory_limit_mb: Address-space memory limit in MB. The effective value is capped. + output_limit_bytes: Limit on the amount of output (in bytes) that can be produced. + """ + timeout_seconds = self.bounded_int( + timeout_seconds, self.DEFAULT_TIMEOUT_SECONDS, 1, self.MAX_TIMEOUT_SECONDS + ) + memory_limit_mb = self.bounded_int( + memory_limit_mb, self.DEFAULT_MEMORY_LIMIT_MB, 64, self.MAX_MEMORY_LIMIT_MB + ) + output_limit_bytes = self.bounded_int( + output_limit_bytes, self.DEFAULT_OUTPUT_LIMIT_BYTES, 1024, self.MAX_OUTPUT_LIMIT_BYTES + ) + stdin_text = json.dumps(self.serialization(self.context.data), ensure_ascii=False) + result = get_sandbox_runner().run( + self.extract_code(program), + stdin=stdin_text, + timeout_seconds=timeout_seconds, + memory_limit_mb=memory_limit_mb, + output_limit_bytes=output_limit_bytes, + interruption_event=getattr(self, "cancel_event", None), + ) + if result.exit_code != 0: + raise RuntimeError(result.stderr or f"Sandboxed program exited with {result.exit_code}") + return { + "stdout": result.stdout, + "stderr": result.stderr, + "duration": result.duration_seconds, + "cpu_seconds": result.cpu_seconds, + "peak_memory_bytes": result.peak_memory_bytes, + "timeout_seconds": timeout_seconds, + "memory_limit_mb": memory_limit_mb, + "output_limit_bytes": output_limit_bytes, + } + + @classmethod + def format_result_dict(cls, result: Dict[str, Any]) -> str: + """Format a tool result for the language model. + + Args: + result: Result mapping to format or update. + + Returns: + str: The operation result. + """ + parts = [] + if result["stdout"]: + parts.append(result["stdout"].rstrip()) + if result["stderr"]: + parts.append(f"Program stderr:\n{result['stderr'].rstrip()}") + if not parts: + parts.append("Program completed successfully and printed no output.") + parts.append(f"(Execution duration: {result['duration']:.3f} seconds.)") + return "\n".join(parts) + + @classmethod + def extract_code(cls, code: str) -> str: + """Extract Python source from an optional Markdown fence.""" + raw_code = str(code).strip() + if "```python" in raw_code: + return raw_code.split("```python")[-1].split("```")[0].strip() + if "```" not in raw_code: + return raw_code + parts = raw_code.split("```") + if len(parts) <= 1: + return raw_code + potential_code = parts[1] + if "\n" not in potential_code: + return potential_code.strip() + first_line, rest = potential_code.split("\n", 1) + return rest.strip() if first_line.strip().isalpha() else potential_code.strip() + + @classmethod + def serialization(cls, value: Any) -> Any: + """Convert context data to JSON-compatible values.""" + if value is None or isinstance(value, (str, int, float, bool)): + return value + if isinstance(value, dict): + return {str(key): cls.serialization(item) for key, item in value.items()} + if isinstance(value, (list, tuple, set)): + return [cls.serialization(item) for item in value] + if hasattr(value, "tolist"): + return cls.serialization(value.tolist()) + if hasattr(value, "item"): + return cls.serialization(value.item()) + raise TypeError(f"unsupported data type {type(value).__name__}") + + @classmethod + def bounded_int(cls, value: Any, default: int, minimum: int, maximum: int) -> int: + """Return a bounded integer tool argument.""" + return bounded_value(value, min=minimum, max=maximum, default=default, converter=int) diff --git a/src/sr_harness/tools/constant_fit.py b/src/sr_harness/tools/constant_fit.py new file mode 100644 index 0000000000000000000000000000000000000000..19b4c1af213d092fd45974062daa66b183d0a8ff --- /dev/null +++ b/src/sr_harness/tools/constant_fit.py @@ -0,0 +1,225 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""Explore simple replacements for numeric constants in a supplied expression.""" + +from fractions import Fraction +from itertools import product +from math import prod +from typing import Any, Dict + +import sr_harness_engine as engine +import numpy as np + +from .base_tool import BaseTool, ToolMetadata + + +@BaseTool.register("constant_fit") +class ConstantFitTool(BaseTool): + """Implementation of the constant fit tool.""" + metadata = ToolMetadata("constant_fit") + NEAR_RELATIVE_TOLERANCE = 0.05 + MAX_SIMPLE_CANDIDATES_PER_NUMBER = 4 + MAX_COMBINATIONS = 50000 + + def execute(self, eq: str, y: str = None, use_eq_as_y: bool = False) -> Dict[str, Any]: + """Compare nearby simple constants at each numeric position in eq. + + Search nearby integers and fractions (denominator <= 12, numerator <= 32), + pi, e, sqrt(2)..sqrt(10), + and signed half/double multiples of these named constants. Candidates + must be within 5% relative distance of the original number. The Pareto + front maximizes validation R2 if validation data exist, otherwise train + R2, and minimizes the count of original numeric constants left unchanged. + + Args: + eq: Required formula containing at least one numeric constant. + y: Target variable or expression; overrides use_eq_as_y when supplied. + use_eq_as_y: If y is omitted, compare against original eq rather + than the tool context's target variable. + """ + if y is not None and not isinstance(y, str): + raise TypeError("y must be a string expression or None.") + original = engine.parse( + self.normalize_formula(eq), + symbols={"pi": engine.Variable("pi"), "e": engine.Variable("e")}, + ) + leaves = [node for node in original.iter_preorder() if isinstance(node, engine.Number)] + if not leaves: + return {"exceptions": ["eq contains no numerical constants to replace."]} + numbers = [] + for index, node in enumerate(leaves, 1): + value = float(node.value) + if not np.isfinite(value): + return {"exceptions": [f"Number{index} is not finite."]} + numbers.append({ + "id": f"Number{index}", + "original": node.to_str(), + "choices": self._nearby_constants(value, node.to_str()), + }) + total = prod(len(item["choices"]) for item in numbers) + if total > self.MAX_COMBINATIONS: + return {"exceptions": [ + f"The {len(numbers)} numeric constants yield {total} combinations; " + f"the limit is {self.MAX_COMBINATIONS}. Supply a smaller expression." + ], "numbers": numbers} + + target_expression = y if y is not None else ( + original.to_str() if use_eq_as_y else self.context.target + ) + target_symbol = self.parse_formula(target_expression) + train = self.context.train_split.data + validation = self.context.validation_split.data + train_target = self._values(target_symbol, train) + validation_target = self._values(target_symbol, validation) if validation else None + + evaluated = [] + invalid = 0 + for choices in product(*(item["choices"] for item in numbers)): + expression = original.copy() + original_leaves = [node for node in expression.iter_preorder() if isinstance(node, engine.Number)] + for leaf, choice in zip(original_leaves, choices): + replacement = engine.parse( + choice["expression"], + symbols={"pi": engine.Variable("pi"), "e": engine.Variable("e")}, + ) + expression = expression.replace(leaf, replacement) + formula = expression.to_str() + try: + candidate = self.parse_formula(formula) + train_r2 = self._r2(train_target, self._values(candidate, train)) + validation_r2 = ( + self._r2(validation_target, self._values(candidate, validation)) + if validation else None + ) + except (ArithmeticError, TypeError, ValueError, KeyError): + invalid += 1 + continue + if not np.isfinite(train_r2) or (validation and not np.isfinite(validation_r2)): + invalid += 1 + continue + evaluated.append({ + "formula": formula, + "constant_complexity": sum(choice["is_original"] for choice in choices), + "train_r2": train_r2, + "validation_r2": validation_r2, + "choices": {item["id"]: choice["label"] for item, choice in zip(numbers, choices)}, + "replacements": {item["id"]: choice["label"] for item, choice in zip(numbers, choices) + if not choice["is_original"]}, + }) + + primary = "validation_r2" if validation else "train_r2" + best_at_complexity = {} + for item in evaluated: + complexity = item["constant_complexity"] + current = best_at_complexity.get(complexity) + if current is None or (item[primary], item["formula"]) > (current[primary], current["formula"]): + best_at_complexity[complexity] = item + pareto = [] + best_r2 = -float("inf") + for complexity in sorted(best_at_complexity): + item = best_at_complexity[complexity] + if item[primary] > best_r2: + pareto.append(item) + best_r2 = item[primary] + return { + "target_expression": target_expression, + "primary_metric": primary, + "numbers": numbers, + "pareto_front": pareto, + "evaluated_combinations": len(evaluated), + "invalid_combinations": invalid, + "total_combinations": total, + "near_relative_tolerance": self.NEAR_RELATIVE_TOLERANCE, + } + + @classmethod + def _nearby_constants(cls, value: float, original: str) -> list[Dict[str, Any]]: + options = [] + + def add(label: str, expression: str, candidate: float): + distance = abs(candidate - value) / max(abs(value), np.finfo(float).tiny) + if distance <= cls.NEAR_RELATIVE_TOLERANCE and expression not in {x["expression"] for x in options}: + options.append({"label": label, "expression": expression, "value": candidate, + "relative_distance": distance, "is_original": False}) + + integer = round(value) + if abs(integer) <= 1000: + add(str(integer), str(integer), float(integer)) + fraction = Fraction(value).limit_denominator(12) + if fraction.denominator != 1 and abs(fraction.numerator) <= 32: + rational = f"Number({fraction.numerator}) / Number({fraction.denominator})" + add(str(fraction), rational, float(fraction)) + named = {"pi": np.pi, "e": np.e} + named.update({f"sqrt({n})": np.sqrt(n) for n in range(2, 11) if n not in (4, 9)}) + for label, base in named.items(): + for factor, prefix in ((0.5, "0.5*"), (1.0, ""), (2.0, "2*"), + (-0.5, "-0.5*"), (-1.0, "-"), (-2.0, "-2*")): + add(f"{prefix}{label}", f"{prefix}{label}", factor * base) + options.sort(key=lambda x: (x["relative_distance"], len(x["expression"]), x["expression"])) + return [{"label": original, "expression": original, "value": value, "relative_distance": 0.0, + "is_original": True}, *options[:cls.MAX_SIMPLE_CANDIDATES_PER_NUMBER]] + + @staticmethod + def _values(symbol: engine.Expression, data: Dict[str, Any]) -> np.ndarray: + with np.errstate(all="ignore"): + return np.asarray(symbol.eval(data), dtype=float).ravel() + + @staticmethod + def _r2(target: np.ndarray, prediction: np.ndarray) -> float: + if prediction.size == 1 and target.size != 1: + prediction = np.full_like(target, float(prediction[0])) + if prediction.shape != target.shape or target.size == 0: + return float("nan") + if not np.all(np.isfinite(target) & np.isfinite(prediction)): + return float("nan") + denominator = float(np.sum((target - np.mean(target)) ** 2)) + numerator = float(np.sum((target - prediction) ** 2)) + if denominator == 0: + return 1.0 if numerator == 0 else float("nan") + return float(1 - numerator / denominator) + + @classmethod + def format_result_dict(cls, result: Dict[str, Any]) -> str: + """Format a tool result for the language model. + + Args: + result: Result mapping to format or update. + + Returns: + str: The operation result. + """ + if "exceptions" in result: + return "Constant fitting not applicable: " + "; ".join(result["exceptions"]) + + def format_r2(value: float) -> str: + displayed = format(value, "#.3g").removesuffix(".") + if value < 1 and float(displayed) == 1: + for precision in range(4, 18): + displayed = format(value, f"#.{precision}g").removesuffix(".") + if float(displayed) < 1: + break + return displayed + + lines = [ + f"Target expression: {result['target_expression']}", + f"Nearby constants (relative distance <= {result['near_relative_tolerance']:.1%}; " + f"at most {cls.MAX_SIMPLE_CANDIDATES_PER_NUMBER} simple candidates per Number):", + ] + for item in result["numbers"]: + labels = [choice["label"] for choice in item["choices"] + if not choice["is_original"] and choice["label"] != item["original"]] + if labels: + lines.append(f" {item['original']} -> {labels}") + lines.append( + f"Evaluated {result['evaluated_combinations']}/{result['total_combinations']} combinations; " + f"invalid={result['invalid_combinations']}." + ) + metric_name = "Validation-set R2" if result["primary_metric"] == "validation_r2" else "Train-set R2" + lines.append(f"Pareto front (maximize #Simplified Constants and {metric_name}):") + lines.append(" (#Simplified Constants | Train-set R2 | Validation-set R2 | Formula)") + for item in result["pareto_front"]: + validation = format_r2(item["validation_r2"]) if item["validation_r2"] is not None else "N/A" + simplified = len(result["numbers"]) - item["constant_complexity"] + lines.append( + f" {simplified} | {format_r2(item['train_r2'])} | {validation} | {item['formula']}" + ) + return "\n".join(lines) diff --git a/src/sr_harness/tools/create_skill.py b/src/sr_harness/tools/create_skill.py new file mode 100644 index 0000000000000000000000000000000000000000..fa6268f91113c1a4a6233a857936a3b9b81accb7 --- /dev/null +++ b/src/sr_harness/tools/create_skill.py @@ -0,0 +1,304 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +from __future__ import annotations +import re +import ast +import yaml +import json +import shutil +from enum import Enum, auto +from copy import deepcopy +from typing import Any, Dict +from logging import getLogger +from ..utils import bounded_value, parse_json_with_template +from .base_tool import BaseTool, ToolMetadata + +_logger = getLogger(f"sr_harness.{__name__}") +_SKILL_NAME_PATTERN = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$") + + +class AuthoringState(Enum): + """Implementation of the authoring state.""" + PREPARE = auto() + AUTHOR = auto() + CONTINUE = auto() + DONE = auto() + +_RESPONSE_TEMPLATE = { + "status": str, + "skill_type": str, + "questions": [str], + "draft": { + "name": str, + "description": str, + "content": str, + "tool_code": str, + "readonly": bool, + }, +} + +_DATA_ANALYSIS_DEMO = '''import numpy as np +from sr_harness.tools import BaseTool, ToolMetadata + +class VariableRangeAnalysis(BaseTool): + metadata = ToolMetadata(name="variable_range_analysis", description="Summarize one variable.") + + def execute(self, variable: str) -> dict: + values = np.asarray(self.context.data[variable], dtype=float) + finite = values[np.isfinite(values)] + return {"variable": variable, "minimum": float(finite.min()), "maximum": float(finite.max())} +''' + +_FORMULA_PROPOSER_DEMO = '''from sr_harness.tools import BaseTool, ToolMetadata + +class SquareFormulaProposer(BaseTool): + metadata = ToolMetadata(name="square_formula_proposer", description="Propose a squared formula.") + + def execute(self, variable: str) -> dict: + formula = self.parse_formula(f"{variable}**2") + target = self.parse_formula(self.context.target) + return self.evaluate(f=formula, y=target) +''' + +_TYPE_GUIDANCE = { + "instructions": "Create an instruction-only skill. Leave tool_code empty and write reusable SKILL.md guidance.", + "data_analysis": "Create a data-analysis BaseTool. Inspect self.context.data and return a normal analysis dictionary. Demo:\n" + _DATA_ANALYSIS_DEMO, + "formula_proposer": "Create a formula-proposal BaseTool. Return or merge self.evaluate(...) output, preserving formula, is_candidate, and data_split_results. Demo:\n" + _FORMULA_PROPOSER_DEMO, +} + +_AUTHORING_PROMPT = '''Create a reusable Agent Skill from the conversation buffer and the current create_skill request. +First decide skill_type as exactly one of instructions, data_analysis, or formula_proposer. +Use the selected type guidance and its demo. Ask only questions that cannot be resolved from context; on later internal rounds resolve them using your best supported judgment. +Do not preserve one-off answers, secrets, or unsupported guesses. +Custom tool code must import BaseTool and ToolMetadata from sr_harness.tools, define exactly one BaseTool subclass with unique metadata.name, avoid @BaseTool.register(...), and return a dict. + +Return exactly one JSON object: +{"status":"needs_input" or "ready", "skill_type":"instructions" or "data_analysis" or "formula_proposer", "questions":["question"], "draft":{"name":"lowercase-hyphenated", "description":"trigger description", "content":"Markdown without frontmatter", "tool_code":"Python source or empty", "readonly":false}} +Use status=ready only when the draft is complete and questions is empty.''' + + +@BaseTool.register("create_skill") +class CreateSkill(BaseTool): + """Implementation of the create skill.""" + metadata = ToolMetadata(name="create_skill") + + def execute( + self, + request: str = "", + force: bool = False, + history_messages: int | None = None, + ) -> Dict[str, Any]: + """Create a reusable skill in one tool call. The tool passes the current Agent + buffer and request to the configured LLM, determines whether the skill is + instruction-only, data-analysis, or formula-proposal, supplies the matching + demo, iterates internally to complete the draft, and then writes the skill. + + Args: + request: Explain the reusable capability or lesson to capture. The current + Agent conversation and the tool-call message are supplied automatically. + force: Replace an existing editable skill's SKILL.md and tool.py. Other files + are preserved; read-only skills cannot be replaced. + history_messages: Number of most recent Agent messages to provide to the + authoring LLM. Defaults to all available messages. + """ + request = request.strip() + if not request: + raise ValueError("request must describe the skill to create.") + if history_messages is not None: + try: + history_messages = int(history_messages) + except (TypeError, ValueError) as exc: + raise ValueError("history_messages must be a non-negative integer.") from exc + if history_messages < 0: + raise ValueError("history_messages must be a non-negative integer.") + max_rounds = bounded_value( + getattr(self.context.args, "skill_authoring_rounds", None), + min=1, max=8, default=4, converter=int, + ) + messages = [] + draft = {"name": "", "description": "", "content": "", "tool_code": "", "readonly": False} + skill_type = "" + questions: list[str] = [] + state = AuthoringState.PREPARE + round_index = 0 + + while True: + if state is AuthoringState.PREPARE: + source_messages = getattr(self.context.args, "messages", None) or [] + if history_messages is not None: + source_messages = source_messages[-history_messages:] if history_messages else [] + messages.extend(deepcopy(source_messages)) + messages.append({"role": "user", "content": f"{_AUTHORING_PROMPT}\n\nCreate-skill request:\n{request}"}) + state = AuthoringState.AUTHOR + + elif state is AuthoringState.AUTHOR: + if round_index >= max_rounds: + raise ValueError(f"Skill authoring did not produce a ready draft within {max_rounds} rounds.") + guidance = _TYPE_GUIDANCE.get(skill_type, "Choose the skill type first.") + payload = { + "request": request, + "selected_type": skill_type, + "guidance": guidance, + "current_draft": draft, + "pending_questions": questions, + } + call_messages = [*messages, {"role": "user", "content": json.dumps(payload, ensure_ascii=False, default=str)}] + if callback := getattr(self.context.args, "skill_authoring_callback", None): + raw_response = callback(call_messages) + else: + raw_response = self._call_configured_llm(call_messages) + if isinstance(raw_response, dict): + raw_response = json.dumps(raw_response, ensure_ascii=False) + response = parse_json_with_template(str(raw_response), _RESPONSE_TEMPLATE) + skill_type = response["skill_type"].strip().lower() + if skill_type not in _TYPE_GUIDANCE: + raise ValueError(f"Skill authoring LLM returned unsupported skill_type: {skill_type!r}") + status = response["status"].strip().lower() + if status not in {"needs_input", "ready"}: + raise ValueError(f"Skill authoring LLM returned unsupported status: {response['status']!r}") + questions = [question.strip() for question in response["questions"] if question.strip()] + draft = response["draft"] + round_index += 1 + state = AuthoringState.DONE if status == "ready" else AuthoringState.CONTINUE + + elif state is AuthoringState.CONTINUE: + messages.extend([ + {"role": "assistant", "content": json.dumps(response, ensure_ascii=False)}, + {"role": "user", "content": ( + "Continue internally. Resolve the pending questions from the supplied " + "conversation and produce the complete draft; do not wait for another user." + )}, + ]) + state = AuthoringState.AUTHOR + + elif state is AuthoringState.DONE: + if questions: + raise ValueError("A ready skill draft must not contain clarification questions.") + result = self._save_draft(draft, skill_type=skill_type, force=force) + return {"status": "created", "rounds": round_index, **result} + + def _call_configured_llm(self, messages: list[dict[str, str]]) -> str: + provider = getattr(self.context.args, "llm_provider", None) + model = getattr(self.context.args, "llm_model", None) + if not provider or not model: + raise ValueError("create_skill requires llm_provider/llm_model context or a skill_authoring_callback.") + from ..api import BaseAPI + + result = BaseAPI.create(provider, model=model)( + messages, n=1, max_tokens=min(int(getattr(self.context.args, "llm_max_tokens", 4096) or 4096), 4096), + ) + content = "" + for response in result: + content = response.content or "" + if not content.strip(): + raise ValueError("Skill authoring LLM returned an empty response.") + return content + + def _save_draft(self, draft: dict[str, Any], *, skill_type: str, force: bool) -> dict[str, Any]: + name, description, content, tool_code, readonly = self._validate_draft(draft, skill_type) + assert hasattr(self.context.args, "skill_manager"), "skill_manager must be provided in context.args." + manager = self.context.args.skill_manager + existed = name in manager.load_skills() + stored_readonly = readonly if skill_type == "instructions" else False + skill_content = ( + "---\n" + + yaml.safe_dump( + {"name": name, "description": description, "readonly": stored_readonly}, + sort_keys=False, + allow_unicode=True, + ) + + "---\n\n" + + content + + "\n" + ) + skill = manager.set_skill(name, skill_content, force=force) + skill_dir = skill.skill_directory + tool_path = skill_dir / "tool.py" + if skill_type == "instructions": + resolved = tool_path.resolve() + for tool_name, tool_cls in list(BaseTool.REGISTRY_DICT.items()): + if getattr(tool_cls, "source_path", None) == resolved: + del BaseTool.REGISTRY_DICT[tool_name] + if self.context.workspace is not None: + relative_tool = str(tool_path.relative_to(self.context.workspace.path)) + self.context.workspace.remove(relative_tool, missing_ok=True) + else: + tool_path.unlink(missing_ok=True) + return {"success": True, "name": name, "skill_type": skill_type, "readonly": readonly} + manager.set_skill(name, tool_code + "\n", "tool.py", force=force) + try: + loaded = BaseTool.load_custom_tool(tool_code, path=tool_path) + except Exception: + if not existed: + if self.context.workspace is not None: + self.context.workspace.remove( + str(skill_dir.relative_to(self.context.workspace.path)), + recursive=True, + missing_ok=True, + ) + else: + shutil.rmtree(skill_dir, ignore_errors=True) + raise + if readonly: + final_content = skill_content.replace("readonly: false", "readonly: true", 1) + manager.set_skill(name, final_content, force=True) + return {"success": True, "name": name, "skill_type": skill_type, "readonly": readonly, **loaded} + + @classmethod + def _validate_draft(cls, draft: dict[str, Any], skill_type: str) -> tuple[str, str, str, str, bool]: + name = draft["name"].strip() + description = draft["description"].strip() + content = draft["content"].strip() + tool_code = draft["tool_code"].strip() + readonly = bool(draft["readonly"]) + if not _SKILL_NAME_PATTERN.fullmatch(name): + raise ValueError("Skill name must use lowercase letters, digits, and hyphens and cannot start or end with a hyphen.") + if not description or not content: + raise ValueError("Skill description and content cannot be empty.") + if content.startswith("---"): + try: + _, _, content = content.split("---\n", 2) + except ValueError as exc: + raise ValueError("Skill content contains invalid YAML frontmatter.") from exc + content = content.strip() + if skill_type == "instructions" and tool_code: + raise ValueError("Instruction-only skill drafts must leave tool_code empty.") + if skill_type != "instructions" and not tool_code: + raise ValueError(f"{skill_type} skill drafts must include tool_code.") + if skill_type == "formula_proposer" and not cls._returns_base_evaluate(tool_code): + raise ValueError("Formula-proposal tool code must return BaseTool.evaluate(...) output by calling self.evaluate(...).") + return name, description, content, tool_code, readonly + + @classmethod + def _returns_base_evaluate(cls, tool_code: str) -> bool: + tree = ast.parse(tool_code) + names = {target.id for node in ast.walk(tree) if isinstance(node, ast.Assign) and cls._is_evaluate_call(node.value) for target in node.targets if isinstance(target, ast.Name)} + + def contains(value: ast.AST | None) -> bool: + if cls._is_evaluate_call(value): + return True + if isinstance(value, ast.Name): + return value.id in names + if isinstance(value, ast.Dict): + return any(contains(item) for item in value.values) + return False + + return any(isinstance(node, ast.Return) and contains(node.value) for node in ast.walk(tree)) + + @staticmethod + def _is_evaluate_call(node: ast.AST | None) -> bool: + return isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "evaluate" and isinstance(node.func.value, ast.Name) and node.func.value.id == "self" + + @classmethod + def format_result_dict(cls, result: Dict[str, Any]) -> str: + """Format a tool result for the language model. + + Args: + result: Result mapping to format or update. + + Returns: + str: The operation result. + """ + text = f"Created {result['skill_type']} skill {result['name']!r}." + if result.get("tool_name"): + text += f" Registered custom tool {result['tool_name']!r}." + return text diff --git a/src/sr_harness/tools/edit_skill.py b/src/sr_harness/tools/edit_skill.py new file mode 100644 index 0000000000000000000000000000000000000000..4a606617f30a256329da56b39ef4f093ea634ad2 --- /dev/null +++ b/src/sr_harness/tools/edit_skill.py @@ -0,0 +1,133 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +from typing import Any, Dict, List, Tuple +from .base_tool import BaseTool, ToolMetadata + + +@BaseTool.register("edit_skill") +class EditSkill(BaseTool): + """Implementation of the edit skill.""" + metadata = ToolMetadata(name="edit_skill") + SEARCH_MARKER = "<<<<<<< SEARCH" + SEPARATOR_MARKER = "=======" + REPLACE_MARKER = ">>>>>>> REPLACE" + + def execute(self, name: str, patch: str) -> Dict[str, Any]: + """Edit an existing skill with exact search/replace blocks. + Use this when an existing skill is clearly relevant but should be corrected, + refined, or extended based on concrete results from the current or recent work. + You do not need to find a perfect formula or reach MSE = 0.0 before editing + a skill; edit it when an attempt reveals a useful reusable tactic. + Prefer small, evidence-backed edits. Do not overwrite broad guidance with a + one-off dataset detail, a final formula, or an unverified guess. If no existing + skill matches the reusable lesson, create a new skill instead. + + Args: + name: The exact skill name to edit. + patch: One or more SEARCH/REPLACE blocks. Each SEARCH text must + match exactly once in the target skill file. Format: + + <<<<<<< SEARCH + old text copied exactly from the skill file + ======= + new replacement text + >>>>>>> REPLACE + + Use multiple blocks for multiple focused edits. + """ + name = name.strip() + replacements = self._parse_patch(patch) + assert hasattr(self.context.args, "skill_manager"), "skill_manager must be provided in context.args." + manager = self.context.args.skill_manager + if name not in manager.load_skills(): + raise ValueError(f"Skill '{name}' does not exist and cannot be edited.") + elif manager.get_skill(name).readonly: + raise ValueError(f"Skill '{name}' is read-only and cannot be edited.") + else: + old_content = manager.read_skill(name) + new_content, exceptions = self._apply_replacements(old_content, replacements) + manager.set_skill(name, new_content, force=True) + return { + "skill": name, + "requested_replacements": len(replacements), + "applied_replacements": len(replacements) - len(exceptions), + "exceptions": exceptions, + } + + @classmethod + def format_result_dict(cls, result: Dict[str, Any]) -> str: + """Format a tool result for the language model. + + Args: + result: Result mapping to format or update. + + Returns: + str: The operation result. + """ + text = ( + f"Edited skill {result['skill']!r}: " + f"Detected {result['requested_replacements']} requested replacements, " + f"applied {result['applied_replacements']} replacements." + ) + if result["exceptions"]: + text += "\nExceptions: " + "; ".join(result["exceptions"]) + return text + + def _parse_patch(self, patch: str) -> List[Tuple[str, str]]: + lines = patch.splitlines(keepends=True) + + index = 0 + replacements = [] + while index < len(lines): + if not lines[index].strip(): + index += 1 + continue + if lines[index].strip() != self.SEARCH_MARKER: + raise ValueError( + f"Expected {self.SEARCH_MARKER!r} at line {index + 1}, " + f"got {lines[index].strip()!r}." + ) + + index += 1 + old_lines = [] + while index < len(lines) and lines[index].strip() != self.SEPARATOR_MARKER: + old_lines.append(lines[index]) + index += 1 + if index >= len(lines): + raise ValueError(f"Missing {self.SEPARATOR_MARKER!r} marker in patch.") + + index += 1 + new_lines = [] + while index < len(lines) and lines[index].strip() != self.REPLACE_MARKER: + new_lines.append(lines[index]) + index += 1 + if index >= len(lines): + raise ValueError(f"Missing {self.REPLACE_MARKER!r} marker in patch.") + + index += 1 + old_text = "".join(old_lines) + new_text = "".join(new_lines) + if not old_text: + raise ValueError("SEARCH block cannot be empty.") + replacements.append((old_text, new_text)) + + if not replacements: + raise ValueError("Patch must contain at least one SEARCH/REPLACE block.") + + return replacements + + def _apply_replacements(self, content: str, replacements: List[Tuple[str, str]]) -> Tuple[str, List[str]]: + exceptions = [] + for old_text, new_text in replacements: + if (count := content.count(old_text)) == 0: + exceptions.append( + f"SEARCH text {old_text!r} was not found in " + f"the skill file, skip this replacement." + ) + elif count > 1: + exceptions.append( + f"SEARCH text {old_text!r} matched more than " + f"once. Include more surrounding context." + ) + else: + content = content.replace(old_text, new_text, 1) + return content, exceptions diff --git a/src/sr_harness/tools/edit_tool.py b/src/sr_harness/tools/edit_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..3cfe4f98412a437916c1f8dfcde1ca72fe06c9cd --- /dev/null +++ b/src/sr_harness/tools/edit_tool.py @@ -0,0 +1,113 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +from typing import Any, Dict, List, Tuple +from .base_tool import BaseTool, ToolMetadata + + +@BaseTool.register("edit_tool") +class EditTool(BaseTool): + """Implementation of the edit tool.""" + metadata = ToolMetadata( + name="edit_tool", + description=( + "Edit and reload a previously created custom tool. Pass the skill " + "directory name (not metadata.name) and one or more exact SEARCH/" + "REPLACE blocks: `<<<<<<< SEARCH\\nold\\n=======\\nnew\\n>>>>>>> " + "REPLACE`. SEARCH text must match exactly once; failed patches do " + "not modify files. A failed reload leaves the edited tool unavailable. Custom " + "tools must not use `@BaseTool.register(...)`; the loader registers " + "them from `metadata.name`." + ), + ) + SEARCH_MARKER = "<<<<<<< SEARCH" + SEPARATOR_MARKER = "=======" + REPLACE_MARKER = ">>>>>>> REPLACE" + + def execute(self, name: str, tool_patch: str, skill_patch: str = "") -> Dict[str, Any]: + """Edit and reload a custom tool using exact search/replace blocks. + + Args: + name: Exact skill name containing the custom tool. + tool_patch: One or more exact SEARCH/REPLACE blocks for tool.py, + using ``<<<<<<< SEARCH`` + old text + ``=======`` + new text + + ``>>>>>>> REPLACE``. SEARCH text must match exactly once. The + resulting tool must not use ``@BaseTool.register(...)``. + skill_patch: Optional blocks in the same format applied to the + complete SKILL.md file. ``name`` is the skill directory name, + not the tool's metadata.name. + """ + assert hasattr(self.context.args, "skill_manager"), "skill_manager must be provided in context.args." + manager = self.context.args.skill_manager + skill = manager.get_skill(name.strip()) + if skill.readonly: + raise ValueError(f"Skill '{name}' is read-only and cannot be edited.") + tool_path = skill.skill_directory / "tool.py" + old_tool = manager.read_skill(name, "tool.py") + old_skill = manager.read_skill(name) + new_tool, warnings = self._apply_replacements(old_tool, self._parse_patch(tool_patch)) + new_skill = old_skill + if skill_patch.strip(): + new_skill, skill_warnings = self._apply_replacements(old_skill, self._parse_patch(skill_patch)) + warnings.extend(skill_warnings) + if warnings: + return {"success": False, "skill": name, "warnings": warnings, "tool_name": None} + + manager.set_skill(name, new_tool, "tool.py", force=True) + loaded = BaseTool.load_custom_tool(new_tool, path=tool_path) + if new_skill != old_skill: + manager.set_skill(name, new_skill, force=True) + return {"success": True, "skill": name, "warnings": [], **loaded} + + def _parse_patch(self, patch: str) -> List[Tuple[str, str]]: + lines = patch.splitlines(keepends=True) + index, replacements = 0, [] + while index < len(lines): + if not lines[index].strip(): + index += 1 + continue + if lines[index].strip() != self.SEARCH_MARKER: + raise ValueError(f"Expected {self.SEARCH_MARKER!r} at line {index + 1}.") + index += 1 + old_lines = [] + while index < len(lines) and lines[index].strip() != self.SEPARATOR_MARKER: + old_lines.append(lines[index]); index += 1 + if index >= len(lines): + raise ValueError(f"Missing {self.SEPARATOR_MARKER!r} marker in patch.") + index += 1 + new_lines = [] + while index < len(lines) and lines[index].strip() != self.REPLACE_MARKER: + new_lines.append(lines[index]); index += 1 + if index >= len(lines): + raise ValueError(f"Missing {self.REPLACE_MARKER!r} marker in patch.") + index += 1 + if not old_lines: + raise ValueError("SEARCH block cannot be empty.") + replacements.append(("".join(old_lines), "".join(new_lines))) + if not replacements: + raise ValueError("Patch must contain at least one SEARCH/REPLACE block.") + return replacements + + def _apply_replacements(self, content: str, replacements: List[Tuple[str, str]]) -> Tuple[str, List[str]]: + warnings = [] + for old_text, new_text in replacements: + count = content.count(old_text) + if count == 0: + warnings.append(f"SEARCH text {old_text!r} was not found.") + elif count > 1: + warnings.append(f"SEARCH text {old_text!r} matched more than once.") + else: + content = content.replace(old_text, new_text, 1) + return content, warnings + + @classmethod + def format_result_dict(cls, result: Dict[str, Any]) -> str: + """Format a tool result for the language model. + + Args: + result: Result mapping to format or update. + + Returns: + str: The operation result. + """ + if not result.get("success"): + return f"Custom tool edit failed for skill {result['skill']!r}: " + "; ".join(result["warnings"]) + return f"Edited and reloaded custom tool {result['tool_name']!r} in skill {result['skill']!r}." diff --git a/src/sr_harness/tools/eic.py b/src/sr_harness/tools/eic.py new file mode 100644 index 0000000000000000000000000000000000000000..958c680f957390e882224cf8331892f66ff2f312 --- /dev/null +++ b/src/sr_harness/tools/eic.py @@ -0,0 +1,320 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""Effective Information Criterion diagnostics for expression subtrees.""" +from __future__ import annotations + +from collections import defaultdict +from typing import Any, Dict + +import sr_harness_engine as engine +import numpy as np +from sr_harness_engine.tree import replace_at_path, with_children + +from .base_tool import BaseTool, ToolMetadata + + +@BaseTool.register("evaluate_eic") +class EICTool(BaseTool): + """Diagnose numerical information loss throughout an expression tree.""" + + metadata = ToolMetadata(name="evaluate_eic") + + def execute( + self, + f: str, + noise_level: float = 0.001, + repeats: int = 8, + random_state: int = 0, + zero_epsilon: float = 1e-6, + ) -> Dict[str, Any]: + """Evaluate whole-formula and per-subtree EIC diagnostics. + + Relative Gaussian noise is injected after every non-leaf operation, following the EIC + paper's recursive algorithm. The formula EIC is the maximum over all subtree EIC values, + which exposes unstable internal structures even when an outer operation masks them. + + Args: + f: Formula to assess. + noise_level: Relative Gaussian noise injected after each operation. + repeats: Independent perturbation runs to average, between 1 and 100. + random_state: Random seed for reproducibility. + zero_epsilon: Denominator fallback used only where a clean subtree output is zero. + """ + if not 0 < noise_level < 1: + raise ValueError("noise_level must be between 0 and 1") + if zero_epsilon <= 0: + raise ValueError("zero_epsilon must be positive") + repeats = max(1, min(int(repeats), 100)) + formula = self.parse_formula(f) + data = self.context.data + paths = self._collect_paths(formula) + samples: dict[tuple[int, ...], list[float]] = defaultdict(list) + finite: dict[tuple[int, ...], list[float]] = defaultdict(list) + overall_samples = [] + rng = np.random.default_rng(random_state) + + for _ in range(repeats): + run: dict[tuple[int, ...], dict[str, Any]] = {} + self._evaluate_recursive( + formula, data, rng, noise_level, zero_epsilon, (), run + ) + for path, values in run.items(): + samples[path].append(values["eic"]) + finite[path].append(values["finite_fraction"]) + overall_samples.append(max(values["eic"] for values in run.values())) + + clean_output = np.asarray(formula.eval(data), dtype=float) + subtree_stats = [] + mean_eic = {path: float(np.mean(values)) for path, values in samples.items()} + for path, node in paths: + child_paths = [path + (i,) for i in range(len(node.operands))] + child_peak = max((mean_eic[p] for p in child_paths), default=0.0) + descendant_peak = max( + ( + value + for descendant_path, value in mean_eic.items() + if len(descendant_path) > len(path) + and descendant_path[:len(path)] == path + ), + default=0.0, + ) + node_eic = mean_eic[path] + impact = self._output_impact(formula, path, data, clean_output) + diagnosis = self._diagnose( + node_eic, + child_peak, + descendant_peak, + impact, + bool(node.operands), + ) + subtree_stats.append({ + "path": "root" if not path else "root/" + "/".join(map(str, path)), + "expression": node.to_str(number_format=self.FORMULA_DISPLAY_NUMBER_FORMAT), + "node_type": type(node).__name__, + "eic": node_eic, + "eic_std": float(np.std(samples[path])), + "introduced_eic": max(0.0, node_eic - child_peak), + "output_impact": impact, + "finite_fraction": float(np.mean(finite[path])), + "diagnosis": diagnosis, + }) + + output = subtree_stats[0] + worst = max(subtree_stats, key=lambda item: item["eic"]) + result = { + "formula": formula.to_str(number_format=self.FORMULA_DISPLAY_NUMBER_FORMAT), + "eic": float(np.mean(overall_samples)), + "eic_std": float(np.std(overall_samples)), + "output_eic": output["eic"], + "output_eic_std": output["eic_std"], + "noise_level": noise_level, + "zero_epsilon": zero_epsilon, + "repeats": repeats, + "finite_fraction": output["finite_fraction"], + "worst_subtree": worst["path"], + "subtrees": subtree_stats, + "tree": self._annotated_tree(formula, subtree_stats), + "implementation": "recursive operator-noise Monte Carlo with subtree diagnostics", + "source": "https://github.com/tsinghua-fib-lab/EIC", + } + target = self.context.target + if target and self.context.data: + result |= self.evaluate( + f=formula, + y=self.parse_formula(target), + show_diagnostics=False, + ) + result["eic_diagnostics"] = { + key: result[key] + for key in ( + "eic", "eic_std", "output_eic", "output_eic_std", + "worst_subtree", "tree", + ) + } + return result + + def _evaluate_recursive( + self, node, data, rng, noise_level, zero_epsilon, path, records + ): + if isinstance(node, engine.Variable): + clear = np.asarray(data[node.name], dtype=float) + noisy = clear + eic = 0.0 + elif isinstance(node, engine.Number): + clear = np.asarray(node.value, dtype=float) + noisy = clear + eic = 0.0 + elif isinstance(node, (engine.Parameter, engine.GroupedParameter)): + clear = np.asarray(node.eval(data), dtype=float) + noisy = clear + eic = 0.0 + else: + operands = [ + self._evaluate_recursive( + child, data, rng, noise_level, zero_epsilon, path + (i,), records + ) + for i, child in enumerate(node.operands) + ] + clear = self._apply_node(node, [item[0] for item in operands]) + noisy = self._apply_node(node, [item[1] for item in operands]) + noisy = noisy + noise_level * noisy * rng.normal(size=np.shape(noisy)) + eic = self._eic(clear, noisy, noise_level, zero_epsilon) + records[path] = { + "eic": eic, + "finite_fraction": float(np.mean(np.isfinite(clear))), + } + return clear, noisy + + @staticmethod + def _apply_node(node, operands): + local_data = {} + replacements = [] + for index, _ in enumerate(node.operands): + name = f"eic_operand_{index}" + replacements.append(engine.Variable(name)) + local_data[name] = operands[index] + local = with_children(node, tuple(replacements)) + with np.errstate(all="ignore"): + return np.asarray(local.eval(local_data), dtype=float) + + @staticmethod + def _eic(clear, noisy, noise_level: float, zero_epsilon: float) -> float: + with np.errstate(divide="ignore", invalid="ignore", over="ignore"): + denominator = clear + zero_epsilon * (clear == 0) + relative = (noisy - clear) / denominator + valid = relative[np.isfinite(relative)] + amplification = np.var(valid) / (noise_level**2) if valid.size else np.nan + if not np.isfinite(amplification): + return 30.0 + amplification = float(np.clip(amplification, 1e-30, 1e30)) + return max(0.0, 0.5 * np.log10(amplification)) + + @staticmethod + def _collect_paths(formula): + result = [] + + def visit(node, path): + result.append((path, node)) + for index, child in enumerate(node.operands): + visit(child, path + (index,)) + + visit(formula, ()) + return result + + @staticmethod + def _output_impact(formula, path, data, baseline) -> float | None: + """Estimate subtree relevance by replacing one path with zero.""" + try: + masked = replace_at_path(formula, path, engine.Number(0)) + prediction = np.asarray(masked.eval(data), dtype=float) + prediction = np.broadcast_to(prediction, np.shape(baseline)) + valid = np.isfinite(baseline) & np.isfinite(prediction) + if not np.any(valid): + return None + scale = float(np.sqrt(np.mean(np.square(baseline[valid])))) + error = float(np.sqrt(np.mean(np.square(prediction[valid] - baseline[valid])))) + return error / max(scale, 1e-300) + except Exception: + return None + + @staticmethod + def _diagnose( + eic: float, + child_peak: float, + descendant_peak: float, + impact: float | None, + is_operator: bool, + ) -> str: + if not is_operator: + return "leaf input/constant; no operator noise injected" + introduced = eic - child_peak + if impact is not None and impact < 1e-6: + if descendant_peak >= 1: + return ( + "negligible output impact masks a sensitive descendant; " + "likely redundant subtree" + ) + return "negligible output impact; candidate redundant subtree" + if descendant_peak - eic >= 1: + return ( + "attenuates or masks a more sensitive descendant; " + "inspect structural redundancy" + ) + if eic >= 3: + if introduced >= 0.5: + return "severe information loss introduced at this operation" + return "severe sensitivity inherited from a descendant subtree" + if eic >= 1: + if introduced >= 0.25: + return "noticeable numerical sensitivity introduced at this operation" + return "noticeable sensitivity propagated from descendants" + return "numerically stable on the supplied data" + + @staticmethod + def _annotated_tree(formula, subtrees: list[dict[str, Any]]) -> str: + lines = formula.to_tree(number_format=BaseTool.FORMULA_DISPLAY_NUMBER_FORMAT).splitlines() + if len(lines) != len(subtrees): + return formula.to_tree(number_format=BaseTool.FORMULA_DISPLAY_NUMBER_FORMAT) + annotated = [] + for line, item in zip(lines, subtrees): + impact = item["output_impact"] + impact_text = "n/a" if impact is None else f"{impact:.3g}" + annotated.append( + f"{line} ← EIC={item['eic']:.3g}, impact={impact_text}; " + f"{item['diagnosis']}" + ) + return "\n".join(annotated) + + @classmethod + def format_result_dict(cls, result: Dict[str, Any]) -> str: + """Format a tool result for the language model. + + Args: + result: Result mapping to format or update. + + Returns: + str: The operation result. + """ + return ( + f"Formula EIC (maximum over all subtrees): {result['eic']:.6g} " + f"± {result['eic_std']:.3g}\n" + f"Root-output EIC: {result['output_eic']:.6g} " + f"± {result['output_eic_std']:.3g}; worst subtree: {result['worst_subtree']}\n" + f"Finite root outputs: {result['finite_fraction']:.1%}\n\n" + f"Annotated expression tree:\n{result['tree']}" + ) + + @classmethod + def get_doc(cls) -> dict[str, str]: + """Return documentation exposed as a runtime skill. + + Returns: + dict[str, str]: The operation result. + """ + return { + "name": "eic-structural-stability", + "description": ( + "Use EIC subtree diagnostics to reject numerically unstable or redundant " + "candidate formula structures." + ), + "content": ( + "Use `evaluate_eic` after a candidate fits reasonably well. Compare candidates " + "on identical data, noise level, repeats, and seed. Lower EIC is preferable, but " + "EIC complements rather than replaces prediction error and complexity. Inspect " + "the annotated tree: a high introduced EIC localizes the operation causing " + "information loss; a high descendant EIC with low output impact indicates a " + "masked, potentially redundant subtree. The reported formula EIC is the maximum " + "over all subtrees, following the paper's recursive definition.\n\n" + "Source: https://github.com/tsinghua-fib-lab/EIC" + ), + } + + +""" +Real invocation and selected output (captured with NumPy 2.2.6): + +>>> EICTool(data={"x": np.linspace(1, 2, 16)}).execute( +... "x + x**2", repeats=2, random_state=7 +... ) +{'formula': 'x + x ** 2', 'eic': 0.002206316240862223, + 'output_eic': 0.002206316240862223, 'worst_subtree': 'root', ...} +""" diff --git a/src/sr_harness/tools/evaluate_code.py b/src/sr_harness/tools/evaluate_code.py new file mode 100644 index 0000000000000000000000000000000000000000..db4751edadc6e95fe73bc4755c372fc64b182b53 --- /dev/null +++ b/src/sr_harness/tools/evaluate_code.py @@ -0,0 +1,150 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""Evaluate Python-defined models inside a data-only OS sandbox.""" + +from __future__ import annotations + +from typing import Any, Dict + +import numpy as np +import sr_harness_engine as engine + +from ..runtime.sandbox import _run_sandbox_protocol +from .base_tool import BaseTool, ToolMetadata +from .code_executor import CodeExecutorTool + + +@BaseTool.register("evaluate_code") +class EvaluateCodeTool(BaseTool): + """Implementation of the evaluate code tool.""" + + metadata = ToolMetadata(name="evaluate_code") + DEFAULT_TIMEOUT_SECONDS = CodeExecutorTool.DEFAULT_TIMEOUT_SECONDS + DEFAULT_MEMORY_LIMIT_MB = CodeExecutorTool.DEFAULT_MEMORY_LIMIT_MB + DEFAULT_OUTPUT_LIMIT_BYTES = CodeExecutorTool.DEFAULT_OUTPUT_LIMIT_BYTES + MAX_TIMEOUT_SECONDS = CodeExecutorTool.MAX_TIMEOUT_SECONDS + MAX_MEMORY_LIMIT_MB = CodeExecutorTool.MAX_MEMORY_LIMIT_MB + MAX_OUTPUT_LIMIT_BYTES = CodeExecutorTool.MAX_OUTPUT_LIMIT_BYTES + + def execute( + self, + model_code: str, + predict_code: str, + y: str = None, + timeout_seconds: int = DEFAULT_TIMEOUT_SECONDS, + memory_limit_mb: int = DEFAULT_MEMORY_LIMIT_MB, + output_limit_bytes: int = DEFAULT_OUTPUT_LIMIT_BYTES, + show_diagnostics: bool = True, + ) -> Dict[str, Any]: + """Evaluate a Python-defined candidate model on the current dataset. + + If possible, first use ``read_skill`` to review ``sr-harness-engine-syntax`` and any + relevant companion documentation, such as ``sr-harness-engine-graph-syntax`` for graph + or hypergraph models. Prefer a structured SRHarness Engine formula when it can express + the candidate, and use this tool when it cannot do so conveniently. The code runs in a + restricted sandbox, then the tool computes metrics against the target and returns the + formatted model under the ``formula`` key. + + This tool can return candidate formulas for submission when `y` is the target + variable and `predict_code` does not depend on the target variable. + + Args: + model_code: Code containing exactly one function with signature + `def func(data)` plus optional top-level imports. `data` is a dictionary + mapping variable names to numeric arrays, including the target variable. + This function should return a Python dict as the fitted `model`, which + will be passed to `predict_code` and `format_code`. The returned model + should contain a `description` field that identifies the model with a + concise mathematical formula (e.g., y = aₖx² + bₖx + cₖ, + yᵢ = MLP1(xᵢ) + Σ Aᵢⱼ MLP2(xᵢ, xⱼ)). + predict_code: Code containing exactly one function with signature + `def func(data, model)` plus optional top-level imports. + The function should return the predicted value for the target `y`, + which must be array-like and compatible with the target shape. + y: Target variable name. Use target variable by default. + Expressions are also supported, e.g., "log(y)", "y - x1" + timeout_seconds: Wall-clock timeout in seconds. The effective value is capped. + memory_limit_mb: Address-space memory limit in MB. The effective value is capped. + output_limit_bytes: Limit on the amount of output (in bytes) that can be produced. + show_diagnostics: Whether metrics should include compact residual diagnostics. + """ + train_data = self.context.train_split.data + validation_data = self.context.validation_split.data + y = (y or self.context.target).strip().strip('"').strip("'") + eq_y = self.parse_formula(y) + timeout_seconds = CodeExecutorTool.bounded_int( + timeout_seconds, self.DEFAULT_TIMEOUT_SECONDS, 1, self.MAX_TIMEOUT_SECONDS + ) + memory_limit_mb = CodeExecutorTool.bounded_int( + memory_limit_mb, self.DEFAULT_MEMORY_LIMIT_MB, 64, self.MAX_MEMORY_LIMIT_MB + ) + output_limit_bytes = CodeExecutorTool.bounded_int( + output_limit_bytes, self.DEFAULT_OUTPUT_LIMIT_BYTES, 1024, self.MAX_OUTPUT_LIMIT_BYTES + ) + groups = {"train": train_data} + if validation_data: + groups["validation"] = validation_data + result = _run_sandbox_protocol( + operation="evaluate-code", + request={ + "model_code": CodeExecutorTool.extract_code(model_code), + "predict_code": CodeExecutorTool.extract_code(predict_code), + "target": self.context.target, + }, + arrays=groups, + timeout_seconds=timeout_seconds, + memory_limit_mb=memory_limit_mb, + output_limit_bytes=output_limit_bytes, + interruption_event=getattr(self, "cancel_event", None), + ) + predictions = result.arrays.get("predictions", {}) + opaque_f = engine.parse("__code_model_prediction__") + data_split_results: dict[str, dict[str, Any]] = {} + for split_name, split_values in groups.items(): + if split_name not in predictions: + raise ValueError(f"Sandbox did not return {split_name} predictions") + y_pred = np.asarray(predictions[split_name]) + y_true = np.asarray(eq_y.eval(split_values)) + y_pred, y_true = np.broadcast_arrays(y_pred, y_true) + metrics = self.calculate_metrics(opaque_f, y_true, y_pred) + metrics["complexity"] = len(model_code) + len(predict_code) + metrics.pop("aic", None) + metrics.pop("bic", None) + split_result: dict[str, Any] = {"metrics": metrics} + if show_diagnostics: + split_result["diagnostics"] = self.residual_diagnostics( + y_true=y_true, + y_pred=y_pred, + data=split_values, + target_expression=eq_y.to_str(), + ) + data_split_results[split_name] = split_result + return { + "formula": str(result.payload["model_str"]), + "is_candidate": bool(result.payload["is_candidate"]) + and eq_y.to_str() == self.context.target, + "data_split_results": data_split_results, + } + + @classmethod + def format_result_dict(cls, result: Dict[str, Any]) -> str: + """Format a tool result for the language model. + + Args: + result: Result mapping to format or update. + + Returns: + str: The operation result. + """ + text = cls.format_evaluation_result(result, title="Evaluated code-defined model") + marker = "Formula Complexity=" + if text.count(marker) > 1: + raise ValueError( + f"Expected at most one '{marker}' field in formatted evaluation output, " + f"but found {text.count(marker)}." + ) + text = text.replace(marker, "Code Complexity=") + return ( + text + "\n" + "(Note: The Code Complexity is measured as source-code character count, so it is not " + "directly comparable to Formula Complexity defined as the symbolic formula node count.)" + ) diff --git a/src/sr_harness/tools/evaluate_formula.py b/src/sr_harness/tools/evaluate_formula.py new file mode 100644 index 0000000000000000000000000000000000000000..55341fe0c0260a101f57fb42285a8d83daa4a279 --- /dev/null +++ b/src/sr_harness/tools/evaluate_formula.py @@ -0,0 +1,98 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""公式评估工具。 + +评估数学公式对数据的拟合能力,返回多种评价指标。 +""" +from typing import Dict, Any + +import numpy as np +import sr_harness_engine as engine +from .base_tool import BaseTool, ToolMetadata + + +@BaseTool.register('evaluate_formula') +class EvaluateTool(BaseTool): + """Implementation of the evaluate tool.""" + metadata = ToolMetadata(name="evaluate_formula") + + def execute( + self, + f: str, + y: str = None, + fit: bool = False, + show_diagnostics: bool = True, + ) -> Dict[str, Any]: + """Evaluate formula fit quality to data. + + This tool can return candidate formulas for submission when `y` is the target variable and `f` does not depend on the target variable. + + Args: + f: Formula string, e.g., "x1**2 + sin(x2) + 3.5 * tanh(x3)". + Common operators like sin, sinh, sec, sech, and sigmoid are all supported; do not use `numpy` or `np`. + y: Target variable name. Use target variable by default. + Expressions are also supported, e.g., "log(y)", "y - x1" + fit: Whether to optimize formula parameters using BFGS algorithm. + show_diagnostics: Whether the result should include a compact residual error profile, + the worst samples, and the strongest residual-variable correlations. + """ + data = self.context.data + y = y or self.context.target + y = y.strip().strip('"').strip("'") + eq_y = self.parse_formula(y) + eq_f = self.parse_formula(f) + variables = [var for var in eq_f.iter_preorder() if isinstance(var, engine.Variable)] + for var in variables: + if var.name not in data: + eq_f = eq_f.replace(var, engine.Parameter(var.name, np.random.rand())) + fit = True # If there are unknown variables, we must fit the formula to data. + + evaluation = self.evaluate( + f=eq_f, + y=eq_y, + show_diagnostics=show_diagnostics, + fit=fit, + ) + split_context = self.context.train_split + y_true = np.asarray(eq_y.eval( + split_context.data, num_nodes=split_context.num_nodes, + )) + parameters = engine.parameter_values(self.parse_formula(evaluation["formula"])) if fit else None + return { + **evaluation, + "parameters_optimized": fit, + **({"fitted_parameters": parameters} if parameters is not None else {}), + "training_samples": int(y_true.size), + } + + @classmethod + def format_result_dict(cls, result: Dict[str, Any]) -> str: + """Format a tool result for the language model. + + Args: + result: Result mapping to format or update. + + Returns: + str: The operation result. + """ + text = cls.format_evaluation_result(result, title="Evaluated formula") + if result.get("parameters_optimized"): + lines = text.splitlines() + lines.insert( + 2, + f" (Parameters are re-fitted on {result['training_samples']} train-set samples)", + ) + text = "\n".join(lines) + return text + +@BaseTool.register('submit_formula') +class SubmitFormulaTool(EvaluateTool): + """Implementation of the submit formula tool.""" + metadata = ToolMetadata( + name="submit_formula", + description=( + "Evaluate formula fit quality to data. " + "If you are satisfied enough with a formula, use this tool to submit it." + "You can submit any formula as many times as you want, but only the best formula will be considered. " + "It returns candidate formulas only when `y` is the default target and the formula does not contain the target itself." + ), + ) diff --git a/src/sr_harness/tools/finish_search.py b/src/sr_harness/tools/finish_search.py new file mode 100644 index 0000000000000000000000000000000000000000..f3d96ba855cd7c5c92319b0d3f4eaff6b6348250 --- /dev/null +++ b/src/sr_harness/tools/finish_search.py @@ -0,0 +1,51 @@ +"""Explicit request to stop an interactive symbolic-regression search.""" +from __future__ import annotations + +from .base_tool import BaseTool +from ..core import ToolMetadata + + +@BaseTool.register("finish_search") +class FinishSearchTool(BaseTool): + """Ask the harness to stop after its configured completion checks pass.""" + + metadata = ToolMetadata( + name="finish_search", + description=( + "Request that the current symbolic-regression search stop. The harness " + "checks its configured stopping policy and returns either a stopped status " + "or a reason why the search must continue." + ), + parameters={ + "type": "object", + "properties": { + "reason": { + "type": "string", + "description": "A concise explanation of why the search is ready to stop.", + }, + }, + "required": ["reason"], + "additionalProperties": False, + }, + ) + + def execute(self, reason: str) -> dict[str, str]: + """Return a request marker for the interactive agent to resolve. + + Args: + reason: Why the model considers the search complete. + + Returns: + A marker replaced by the interactive Agent with the stop-check result. + """ + return {"status": "requested", "reason": reason} + + @classmethod + def format_result_dict(cls, result: dict[str, str]) -> str: + """Format the resolved stop status for the model.""" + status = result.get("status") + if status == "stopped": + return "Search stopped. The run will pause at the next safe boundary." + if status == "rejected": + return f"Search cannot stop yet: {result.get('reason', 'completion check failed')}" + return "Search stop requested." diff --git a/src/sr_harness/tools/harmonic_interaction_fit.py b/src/sr_harness/tools/harmonic_interaction_fit.py new file mode 100644 index 0000000000000000000000000000000000000000..394c95e07a8a708016a333959f4ec58ce94ba4e5 --- /dev/null +++ b/src/sr_harness/tools/harmonic_interaction_fit.py @@ -0,0 +1,155 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""Fit a low-complexity polynomial plus oscillatory interaction. + +The frequency is searched using training observations only. This is useful for +equations where a state variable modulates a periodic forcing term. +""" + +from __future__ import annotations + +from typing import Any, Dict + +import sr_harness_engine as engine +import numpy as np +from scipy.optimize import minimize_scalar + +from .base_tool import BaseTool, ToolMetadata + + +# 这个工具太狭隘了,用处不大 +# @BaseTool.register("harmonic_interaction_fit") +class HarmonicInteractionFitTool(BaseTool): + """Implementation of the harmonic interaction fit tool.""" + metadata = ToolMetadata(name="harmonic_interaction_fit") + + def execute( + self, + carrier: str, + oscillator: str, + y: str = None, + degree: int = 2, + include_bias: bool = False, + max_cycles: float = 20.0, + grid_size: int = 320, + show_diagnostics: bool = True, + ) -> Dict[str, Any]: + """Fit y = polynomial(carrier) + carrier * sin(frequency * oscillator). + + Args: + carrier: State variable or expression that multiplies the sine term. + oscillator: Variable or expression used as the sine argument. + y: Target variable; defaults to the discovery target. + degree: Polynomial degree in carrier, from 1 through 4. + include_bias: Whether to fit an additive constant. + max_cycles: Largest number of cycles across the observed oscillator span. + grid_size: Number of initial frequency-grid points, from 64 through 2048. + show_diagnostics: Include residual diagnostics in the returned evaluation. + """ + target_name = (y or self.context.target).strip().strip('"').strip("'") + data = self.context.data + carrier_symbol = self.parse_formula(carrier) + oscillator_symbol = self.parse_formula(oscillator) + target_symbol = self.parse_formula(target_name) + target = np.asarray(target_symbol.eval(data), dtype=float).reshape(-1) + state = np.asarray(carrier_symbol.eval(data), dtype=float).reshape(-1) + phase = np.asarray(oscillator_symbol.eval(data), dtype=float).reshape(-1) + if not (target.shape == state.shape == phase.shape): + raise ValueError("Target, carrier, and oscillator must have the same shape.") + finite = np.isfinite(target) & np.isfinite(state) & np.isfinite(phase) + degree = min(max(int(degree), 1), 4) + grid_size = min(max(int(grid_size), 64), 2048) + if np.count_nonzero(finite) < degree + 4: + raise ValueError("Too few finite observations for harmonic interaction fit.") + yy, xx, tt = target[finite], state[finite], phase[finite] + span = float(np.ptp(tt)) + if span <= 0: + raise ValueError("Oscillator must vary across training observations.") + + base_terms = [np.ones_like(xx)] if include_bias else [] + base_terms.extend(xx ** power for power in range(1, degree + 1)) + base = np.column_stack(base_terms) + min_frequency = 2 * np.pi / (4 * span) + max_frequency = 2 * np.pi * max(float(max_cycles), 0.5) / span + frequencies = np.linspace(min_frequency, max_frequency, grid_size) + + def fit_at(frequency: float): + design = np.column_stack((base, xx * np.sin(frequency * tt))) + coefficients, _, rank, _ = np.linalg.lstsq(design, yy, rcond=None) + if rank < design.shape[1]: + return float("inf"), coefficients + residual = yy - design @ coefficients + return float(np.mean(residual * residual)), coefficients + + scores = np.asarray([fit_at(float(freq))[0] for freq in frequencies]) + if not np.any(np.isfinite(scores)): + raise ValueError("Harmonic design matrix is rank deficient at every frequency.") + # Refining several grid minima avoids choosing a sidelobe of the sine fit. + local_minima = [ + i for i in range(1, grid_size - 1) + if scores[i] <= scores[i - 1] and scores[i] <= scores[i + 1] + ] + local_minima.extend((0, grid_size - 1, int(np.nanargmin(scores)))) + candidate_indices = sorted(set(local_minima), key=lambda i: scores[i])[:8] + best = None + for i in candidate_indices: + left = float(frequencies[max(i - 1, 0)]) + right = float(frequencies[min(i + 1, grid_size - 1)]) + if left == right: + continue + refined = minimize_scalar( + lambda frequency: fit_at(float(frequency))[0], + bounds=(left, right), method="bounded", + options={"xatol": 1e-12}, + ) + score, coefficients = fit_at(float(refined.x)) + if best is None or score < best[0]: + best = (score, float(refined.x), coefficients) + if best is None: + i = int(np.nanargmin(scores)) + best = (float(scores[i]), float(frequencies[i]), fit_at(float(frequencies[i]))[1]) + + score, frequency, coefficients = best + terms = ["1"] if include_bias else [] + terms.extend( + f"({carrier_symbol.to_str()}) ** {power}" for power in range(1, degree + 1) + ) + terms.append( + f"({carrier_symbol.to_str()}) * sin(({frequency:.16g}) * ({oscillator_symbol.to_str()}))" + ) + formula = " + ".join( + f"({float(coefficient):.16g}) * ({term})" + for coefficient, term in zip(coefficients, terms) + if abs(coefficient) > 1e-14 + ) or "0" + evaluation = self.evaluate( + f=self.parse_formula(formula), + y=target_symbol, + show_diagnostics=show_diagnostics, + ) + return evaluation | { + "fit_configuration": { + "carrier": carrier_symbol.to_str(), + "oscillator": oscillator_symbol.to_str(), + "degree": degree, + "include_bias": include_bias, + "frequency": frequency, + "training_grid_mse": score, + }, + } + + @classmethod + def format_result_dict(cls, result: Dict[str, Any]) -> str: + """Format a tool result for the language model. + + Args: + result: Result mapping to format or update. + + Returns: + str: The operation result. + """ + text = cls.format_evaluation_result(result, title="Fitted harmonic interaction") + config = result["fit_configuration"] + return text + ( + f"\nHarmonic interaction: carrier={config['carrier']}, " + f"oscillator={config['oscillator']}, frequency={config['frequency']:.8g}." + ) diff --git a/src/sr_harness/tools/model_test.py b/src/sr_harness/tools/model_test.py new file mode 100644 index 0000000000000000000000000000000000000000..70a2a88aeea5ebde2f6ae2330711b15be1db92e4 --- /dev/null +++ b/src/sr_harness/tools/model_test.py @@ -0,0 +1,36 @@ +"""Internal tool used to verify model tool-calling support.""" +from __future__ import annotations + +from .base_tool import BaseTool +from ..core import ToolMetadata + + +class ModelTestTool(BaseTool): + """Report a requested value during a model connectivity test.""" + + metadata = ToolMetadata( + name="report_model_test", + description="Report the requested value to complete an SRHarness model test.", + parameters={ + "type": "object", + "properties": { + "answer": { + "type": "string", + "description": "The exact value requested by the model-test prompt.", + }, + }, + "required": ["answer"], + "additionalProperties": False, + }, + ) + + def execute(self, answer: str) -> dict[str, str]: + """Return the value supplied by the model-test request. + + Args: + answer: Exact value requested by the test prompt. + + Returns: + The reported answer. + """ + return {"answer": answer} diff --git a/src/sr_harness/tools/nd2.py b/src/sr_harness/tools/nd2.py new file mode 100644 index 0000000000000000000000000000000000000000..ab13a9da83fb90d8cfddbd45a4e695507e12f130 --- /dev/null +++ b/src/sr_harness/tools/nd2.py @@ -0,0 +1,383 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""ND2 neural symbolic regression for network dynamics.""" +from __future__ import annotations + +import os +import sys +from pathlib import Path +from typing import Any, Dict, List + +import numpy as np + +from .base_tool import BaseTool, ToolMetadata + + +@BaseTool.register("nd2") +class ND2Tool(BaseTool): + """Implementation of the n d2 tool.""" + metadata = ToolMetadata(name="nd2") + REPOSITORY = "https://github.com/tsinghua-fib-lab/ND2" + DEFAULT_BINARY = ["add", "sub", "mul", "div", "pow", "regular"] + DEFAULT_UNARY = [ + "neg", "abs", "inv", "exp", "logabs", "sin", "cos", "tan", + "sqrtabs", "pow2", "pow3", "tanh", "sigmoid", "aggr", "sour", + "targ", + ] + + def execute( + self, + vars_node: List[str] = None, + vars_edge: List[str] = None, + y: str = None, + root_type: str = "node", + binary_operators: List[str] = None, + unary_operators: List[str] = None, + timeout: int = 60, + episode_limit: int = 10000, + beam_size: int = 10, + max_coeff_num: int = 5, + ) -> Dict[str, Any]: + """Run NDformer-guided MCTS on node or edge dynamics in the current data. + + The context must contain adjacency `A` and/or edge list `G`, a target shaped + `(time, node)` or `(time, edge)`, and node/edge variables with matching final axes. + `ND2_HOME` must point to the official repository; `ND2_CHECKPOINT` defaults to + `$ND2_HOME/weights/checkpoint.pth`. + + Args: + vars_node: Node-level variable names. Inferred from the node axis when omitted. + vars_edge: Edge-level variable names. Inferred from the edge axis when omitted. + y: Target variable name. Defaults to the configured target. + root_type: Output expression type, either "node" or "edge". + binary_operators: ND2 binary tokens. Defaults to its standard binary vocabulary. + unary_operators: ND2 unary tokens. Defaults to its standard unary vocabulary. + timeout: Wall-time search limit in seconds, between 10 and 3600. + episode_limit: Maximum MCTS episodes, between 1 and 1000000. + beam_size: Number of expansions retained per MCTS step, between 1 and 100. + max_coeff_num: Maximum fitted scalar coefficients, between 0 and 20. + """ + status = self.backend_status() + if not status["installed"]: + raise RuntimeError( + "ND2 is not configured: clone the repository and set ND2_HOME." + ) + checkpoint = Path( + os.environ.get( + "ND2_CHECKPOINT", + Path(status["root"]) / "weights" / "checkpoint.pth", + ) + ).expanduser().resolve() + if not checkpoint.is_file(): + raise RuntimeError( + "ND2 checkpoint not found. Set ND2_CHECKPOINT to checkpoint.pth." + ) + if root_type not in {"node", "edge"}: + raise ValueError("root_type must be 'node' or 'edge'") + + timeout = max(10, min(int(timeout), 3600)) + episode_limit = max(1, min(int(episode_limit), 1_000_000)) + beam_size = max(1, min(int(beam_size), 100)) + max_coeff_num = max(0, min(int(max_coeff_num), 20)) + data = self._prepare_data(self.context.data) + y = (y or self.context.target).strip() + if y not in data: + raise ValueError(f"Target {y!r} is missing from the ND2 data.") + + node_count = data["A"].shape[0] + edge_count = data["G"].shape[0] + excluded = {"A", "G", y} + if vars_node is None: + vars_node = [ + name for name, value in data.items() + if name not in excluded and np.shape(value)[-1:] == (node_count,) + ] + if vars_edge is None: + vars_edge = [ + name for name, value in data.items() + if name not in excluded and np.shape(value)[-1:] == (edge_count,) + and name not in vars_node + ] + missing = [name for name in [*vars_node, *vars_edge] if name not in data] + if missing: + raise ValueError(f"ND2 variables are missing from data: {missing}") + expected_width = node_count if root_type == "node" else edge_count + if np.asarray(data[y]).ndim != 2 or np.asarray(data[y]).shape[1] != expected_width: + raise ValueError( + f"ND2 {root_type} target must have shape (time, {expected_width})." + ) + + search = self._run_nd2( + root=Path(status["root"]), + checkpoint=checkpoint, + data=data, + y=y, + vars_node=vars_node, + vars_edge=vars_edge, + root_type=root_type, + binary_operators=binary_operators or self.DEFAULT_BINARY, + unary_operators=unary_operators or self.DEFAULT_UNARY, + timeout=timeout, + episode_limit=episode_limit, + beam_size=beam_size, + max_coeff_num=max_coeff_num, + ) + split_results = {"train": {"metrics": search["train_metrics"]}} + if search.get("validation_metrics") is not None: + split_results["validation"] = { + "metrics": search["validation_metrics"], + } + return { + "formula": search["formula"], + "target_expression": y, + "is_candidate": bool(np.isfinite(search["train_metrics"]["mse"])), + "candidate_ineligibility_reasons": [], + "data_split_results": split_results, + "method": "ND2-NDformer-MCTS", + "prefix": search["prefix"], + "backend": status, + "config": { + "vars_node": vars_node, + "vars_edge": vars_edge, + "root_type": root_type, + "timeout": timeout, + "episode_limit": episode_limit, + "beam_size": beam_size, + "max_coeff_num": max_coeff_num, + }, + } + + def _run_nd2( + self, + *, + root: Path, + checkpoint: Path, + data: Dict[str, np.ndarray], + y: str, + vars_node: List[str], + vars_edge: List[str], + root_type: str, + binary_operators: List[str], + unary_operators: List[str], + timeout: int, + episode_limit: int, + beam_size: int, + max_coeff_num: int, + ) -> Dict[str, Any]: + root_text = str(root) + if root_text not in sys.path: + sys.path.insert(0, root_text) + try: + import torch + from ND2.GDExpr import GDExpr + from ND2.model import NDformer + from ND2.search import MCTS + from ND2.search.reward_solver import RewardSolver + except ImportError as exc: + raise RuntimeError( + "ND2 dependencies are unavailable in this Python environment." + ) from exc + + device = os.environ.get( + "ND2_DEVICE", + "cuda" if torch.cuda.is_available() else "cpu", + ) + rewarder = self._make_rewarder( + RewardSolver, data, y, vars_node, vars_edge + ) + model = NDformer(device=device) + model.load(checkpoint, weights_only=False) + model.eval() + model.set_data( + Xv={name: data[name] for name in vars_node}, + Xe={name: data[name] for name in vars_edge}, + A=data["A"], + G=data["G"], + Y=data[y], + root_type=root_type, + cache_data_emb=True, + ) + estimator = MCTS( + rewarder=rewarder, + ndformer=model, + vars_node=vars_node, + vars_edge=vars_edge, + binary=binary_operators, + unary=unary_operators, + log_per_episode=100, + log_per_second=10, + beam_size=beam_size, + max_coeff_num=max_coeff_num, + use_random_simulate=False, + ) + estimator.fit( + [root_type], + episode_limit=episode_limit, + time_limit=timeout, + ) + if not estimator.best_model: + raise RuntimeError("ND2 completed without producing a formula.") + + validation_metrics = None + if validation_data := self.context.validation_split.data: + validation_data = self._prepare_data(validation_data) + validator = self._make_rewarder( + RewardSolver, validation_data, y, vars_node, vars_edge + ) + validation_metrics = self._normalize_metrics( + validator.evaluate(estimator.best_model) + ) + return { + "formula": GDExpr.prefix2str(estimator.best_model), + "prefix": [ + value.tolist() if isinstance(value, np.ndarray) else value + for value in estimator.best_model + ], + "train_metrics": self._normalize_metrics(estimator.best_metric), + "validation_metrics": validation_metrics, + } + + @staticmethod + def _make_rewarder(rewarder_cls, data, y, vars_node, vars_edge): + return rewarder_cls( + Xv={name: data[name] for name in vars_node}, + Xe={name: data[name] for name in vars_edge}, + A=data["A"], + G=data["G"], + Y=data[y], + mask=None, + ) + + @staticmethod + def _prepare_data(data: Dict[str, Any]) -> Dict[str, np.ndarray]: + arrays = {name: np.asarray(value) for name, value in data.items()} + if "A" not in arrays and "G" not in arrays: + raise ValueError("ND2 requires adjacency A or edge list G.") + if "G" not in arrays: + arrays["G"] = np.stack(np.nonzero(arrays["A"]), axis=-1) + arrays["G"] = arrays["G"].astype(int, copy=False) + if "A" not in arrays: + node_count = int(arrays["G"].max()) + 1 + arrays["A"] = np.zeros((node_count, node_count), dtype=int) + arrays["A"][arrays["G"][:, 0], arrays["G"][:, 1]] = 1 + arrays["A"] = arrays["A"].astype(int, copy=False) + return arrays + + @staticmethod + def _normalize_metrics(metrics: Dict[str, Any]) -> Dict[str, float]: + names = { + "RMSE": "rmse", + "MAE": "mae", + "MAPE": "mape", + "R2": "r2", + "ACC2": "acc2", + "ACC3": "acc3", + "ACC4": "acc4", + "complexity": "complexity", + } + result = { + output: float(metrics[input_name]) + for input_name, output in names.items() + if input_name in metrics + } + result["mse"] = result["rmse"] ** 2 + return result + + @classmethod + def backend_status(cls) -> Dict[str, Any]: + """Run the ``backend status`` operation. + + Returns: + Dict[str, Any]: The operation result. + """ + configured = os.environ.get("ND2_HOME") + local_root = Path.cwd() / "third-party" / "ND2" + root = ( + Path(configured).expanduser().resolve() + if configured + else local_root.resolve() if (local_root / "search.py").is_file() + else None + ) + marker = "search.py" + checkpoint = ( + Path(os.environ.get("ND2_CHECKPOINT", root / "weights" / "checkpoint.pth")) + if root else None + ) + return { + "backend": "nd2", + "repository": cls.REPOSITORY, + "environment_variable": "ND2_HOME", + "root": str(root) if root else None, + "installed": bool(root and (root / marker).is_file()), + "checkpoint": str(checkpoint) if checkpoint else None, + "checkpoint_available": bool(checkpoint and checkpoint.is_file()), + "marker": marker, + } + + @classmethod + def format_result_dict(cls, result: Dict[str, Any]) -> str: + """Format a tool result for the language model. + + Args: + result: Result mapping to format or update. + + Returns: + str: The operation result. + """ + split_results = result["data_split_results"] + train = split_results["train"]["metrics"] + validation = split_results.get("validation", {}).get("metrics") + lines = [ + f"ND2 discovered: {result['target_expression']} = {result['formula']}", + f"Train RMSE={train['rmse']:.6g}, R2={train['r2']:.6g}, " + f"complexity={train['complexity']:.0f}", + ] + if validation: + lines.append( + f"Validation RMSE={validation['rmse']:.6g}, " + f"R2={validation['r2']:.6g}" + ) + return "\n".join(lines) + + @classmethod + def get_doc(cls) -> dict[str, str]: + """Return documentation exposed as a runtime skill. + + Returns: + dict[str, str]: The operation result. + """ + return { + "name": "nd2-network-dynamics", + "description": ( + "Use ND2 neural symbolic regression for graph and network-dynamics discovery." + ), + "content": ( + "ND2 expects adjacency `A` or edge list `G`, node inputs shaped `(time, node)`, " + "optional edge inputs shaped `(time, edge)`, and a node- or edge-level target. " + "Call `nd2` to run the actual NDformer-guided MCTS; the returned graph-dynamics " + "formula and train/validation metrics enter SRAgent's candidate set. Configure " + "`ND2_HOME` and `ND2_CHECKPOINT` before use. Use ordinary SRAgent tools for " + "non-network tabular regression.\n\n" + f"Source: {cls.REPOSITORY}" + ), + } + + +""" +Real invocation captured with the official checkpoint and Kuramoto demo data: + +>>> ND2Tool.backend_status() +{'backend': 'nd2', 'repository': 'https://github.com/tsinghua-fib-lab/ND2', + 'environment_variable': 'ND2_HOME', 'root': '.../third-party/ND2', + 'installed': True, 'checkpoint': '.../third-party/ND2/weights/checkpoint.pth', + 'checkpoint_available': True, 'marker': 'search.py'} + +>>> result = tool.execute( +... vars_node=["x", "omega"], vars_edge=[], y="dx", +... binary_operators=["add", "sub", "mul"], +... unary_operators=["sin", "aggr", "sour", "targ"], +... timeout=10, episode_limit=1, beam_size=2, max_coeff_num=2, +... ) +>>> print(ND2Tool.format_result_dict(result)) +ND2 discovered: dx = ((omega+(0.9960*x))-x) +Train RMSE=1.11731, R2=0.839655, complexity=7 +""" diff --git a/src/sr_harness/tools/polynomial_fit.py b/src/sr_harness/tools/polynomial_fit.py new file mode 100644 index 0000000000000000000000000000000000000000..a705f92f91850c92a716c5ee71e92e61772fb292 --- /dev/null +++ b/src/sr_harness/tools/polynomial_fit.py @@ -0,0 +1,385 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""多项式拟合工具。提供对输入变量或表达式的多项式拟合功能,支持自定义最高阶次数、交叉项控制等。""" + +import numpy as np +import sr_harness_engine as engine +from itertools import combinations, product +from functools import reduce +from typing import Dict, Any, List, Optional, Tuple, Set +from .base_tool import BaseTool, ToolMetadata, is_numeric_array + + +@BaseTool.register('polynomial_fit') +class PolynomialFitTool(BaseTool): + """Implementation of the polynomial fit tool.""" + metadata = ToolMetadata(name="polynomial_fit") + + def execute( + self, + x: List[str] = None, + y: str = None, + max_degree: int = 2, + include_interactions: bool = True, + interaction_blacklist: List[Tuple[str, str]] = None, + interaction_whitelist: List[Tuple[str, str]] = None, + include_bias: bool = True, + simplify: bool = True, + show_diagnostics: bool = True, + ) -> Dict[str, Any]: + """Execute polynomial fit. + + This tool can return candidate formulas for submission when `y` is the target variable and `x` does not depend on the target variable. + + Args: + x: List of input feature names, e.g., ["x1", "x2"]. Use all features other than y by default. + Expressions are also supported, e.g., ["sin(x1)", "(x1-x2)**2"]. + y: Target variable name. Use target variable by default. + Expressions are also supported, e.g., "log(y)", "y - x1" + max_degree: Maximum polynomial degree. + include_interactions: Whether to include interaction terms. + interaction_blacklist: List of variable pairs that should not interact. + E.g., [("x1", "x2")] means no interaction between x1 and x2. + interaction_whitelist: Only allow specified variable pairs to interact. + By default, all pairs are allowed (unless in blacklist). + If specified, only interactions in the whitelist are generated. + include_bias: Whether to include bias/intercept term. + simplify: Whether to conservatively remove monomials whose fitted + contributions are negligible on the training samples, then refit + the remaining coefficients. Enabled by default. + show_diagnostics: Whether final metrics should include compact residual diagnostics. + """ + data = self.context.data + y = y or self.context.target + y = y.strip().strip('"').strip("'") + x = x or [var for var in data if var != y and is_numeric_array(data[var])] + exceptions = [] + + try: + eq_y = self.parse_formula(y) + data_y = eq_y.eval(data).flatten() + except Exception as e: + raise ValueError( + f"Failed to compute target '{y}': {str(e)}" + + "\nOther exceptions: " + "; ".join(exceptions) + ) + + eq_x_list = [] + for xi in x: + try: + eq_x = self.parse_formula(xi) + data_x = eq_x.eval(data).flatten() + if not is_numeric_array(data_x): + exceptions.append(f"Feature '{xi}' did not produce numeric values.") + continue + eq_x_list.append(eq_x) + assert data_x.shape == data_y.shape, f"Feature '{xi}' shape {data_x.shape} does not match target shape {data_y.shape}." + except Exception as e: + exceptions.append(f"Failed to compute feature '{xi}': {str(e)}") + if len(eq_x_list) == 0: + raise ValueError( + "No valid input variables available for fitting.\n" + + "Other exceptions: " + "; ".join(exceptions) + ) + + # 生成交叉项限制 + allowed_interactions = self._get_allowed_interactions( + eq_x_list, include_interactions, interaction_blacklist, interaction_whitelist + ) + + # 构建总次数不超过 max_degree 的符号项,并统一计算设计矩阵 + terms = self.generate_terms(eq_x_list, max_degree, allowed_interactions, include_bias) + design_matrix = self._build_design_matrix(data, terms, len(data_y)) + + # 检查设计矩阵的秩 + matrix_rank = np.linalg.matrix_rank(design_matrix) + n_params = design_matrix.shape[1] + + if matrix_rank < n_params: + exceptions.append( + f"设计矩阵秩 deficient: 秩={matrix_rank}, 参数={n_params}。" + "可能存在多重共线性,结果可能不稳定。" + ) + + # 使用最小二乘法拟合 + p = n_params + n = len(data_y) + + try: + # 使用 QR 分解提高数值稳定性 + Q, R = np.linalg.qr(design_matrix) + coefficients = np.linalg.solve(R, Q.T @ data_y) + + # 计算残差 + y_pred = design_matrix @ coefficients + residuals = data_y - y_pred + + # 计算系数标准误差 + if n > p: + mse = np.sum(residuals ** 2) / (n - p) + # 系数的协方差矩阵 + try: + cov_matrix = mse * np.linalg.inv(R.T @ R) + std_errors = np.sqrt(np.diag(cov_matrix)) + except np.linalg.LinAlgError: + # 如果矩阵奇异,使用伪逆 + cov_matrix = mse * np.linalg.pinv(R.T @ R) + std_errors = np.sqrt(np.diag(cov_matrix)) + exceptions.append("使用伪逆计算标准误差,结果可能不够精确。") + else: + std_errors = np.full(n_params, np.nan) + exceptions.append("样本数不足以计算标准误差。") + + # 计算 t 统计量和 p 值 + with np.errstate(divide='ignore', invalid='ignore'): + t_stats = coefficients / std_errors + # 使用 t 分布计算双尾 p 值 + from scipy import stats + dof = max(n - p, 1) + p_values = 2 * (1 - stats.t.cdf(np.abs(t_stats), dof)) + + except Exception as e: + # 降级到普通最小二乘 + exceptions.append(f"QR 分解失败,使用普通最小二乘法:{str(e)}") + coefficients, residuals, rank, s = np.linalg.lstsq( + design_matrix, data_y, rcond=None + ) + y_pred = design_matrix @ coefficients + std_errors = np.full(n_params, np.nan) + t_stats = np.full(n_params, np.nan) + p_values = np.full(n_params, np.nan) + + original_coefficients = np.asarray(coefficients, dtype=float) + simplification = { + "enabled": bool(simplify), + "original_term_count": len(terms), + "retained_term_count": len(terms), + "removed_terms": [], + } + if simplify: + terms, coefficients, removed_terms = self._simplify_terms( + design_matrix=design_matrix, + target=data_y, + terms=terms, + coefficients=original_coefficients, + ) + simplification.update({ + "retained_term_count": len(terms), + "removed_terms": removed_terms, + }) + + # 构建多项式 + polynomial_parts = [] + for coef, term in zip(coefficients, terms): + if coef == 0: + continue + if term.to_str() == "1": + polynomial_parts.append(engine.Number(float(coef))) + else: + polynomial_parts.append(float(coef) * term) + polynomial = reduce(lambda a, b: a + b, polynomial_parts) if polynomial_parts else engine.parse("0") + + evaluation = self.evaluate( + f=polynomial, + y=eq_y, + show_diagnostics=show_diagnostics, + ) + + return { + **evaluation, + "fit_configuration": { + "input_features": [feature.to_str() for feature in eq_x_list], + "maximum_degree": max_degree, + "interactions_included": include_interactions, + "bias_included": include_bias, + "simplification_enabled": bool(simplify), + }, + "simplification": simplification, + "exceptions": exceptions + } + + @classmethod + def format_result_dict(cls, result: Dict[str, Any]) -> str: + """Format a tool result for the language model. + + Args: + result: Result mapping to format or update. + + Returns: + str: The operation result. + """ + text = cls.format_evaluation_result(result, title="Best fitted polynomial") + if result["exceptions"]: + text += "\nFit warnings: " + "; ".join(result["exceptions"]) + return text + + @staticmethod + def _simplify_terms( + design_matrix: np.ndarray, + target: np.ndarray, + terms: List[engine.Expression], + coefficients: np.ndarray, + ) -> Tuple[List[engine.Expression], np.ndarray, List[Dict[str, Any]]]: + """Remove negligible fitted contributions and refit the retained terms. + + Raw coefficient magnitudes are not comparable when monomials have + different scales. We therefore threshold each fitted contribution + ``coefficient * monomial(samples)`` using both its RMS and maximum + absolute value. A proposed removal is accepted only when refitting the + retained terms changes training RMSE by no more than a small fraction of + the target RMS. Repeating this step mirrors conservative sequentially + thresholded least squares while guarding against material fit loss. + """ + active = np.arange(design_matrix.shape[1]) + coefficients = np.asarray(coefficients, dtype=float) + target = np.asarray(target, dtype=float).flatten() + target_rms = float(np.sqrt(np.mean(np.square(target)))) + scale = max(target_rms, np.finfo(float).eps) + accepted_rmse_increase = 1e-6 * scale + removed: List[Dict[str, Any]] = [] + + for _ in range(design_matrix.shape[1]): + active_matrix = design_matrix[:, active] + contributions = active_matrix * coefficients + contribution_rms = np.sqrt(np.mean(np.square(contributions), axis=0)) + contribution_max = np.max(np.abs(contributions), axis=0) + negligible = (contribution_rms <= 1e-6 * scale) & (contribution_max <= 1e-5 * scale) + if not np.any(negligible): + break + + keep = ~negligible + if not np.any(keep): + keep[int(np.argmax(contribution_rms))] = True + negligible = ~keep + if not np.any(negligible): + break + + old_prediction = active_matrix @ coefficients + old_rmse = float(np.sqrt(np.mean(np.square(target - old_prediction)))) + proposed_active = active[keep] + proposed_coefficients = np.linalg.lstsq( + design_matrix[:, proposed_active], target, rcond=None + )[0] + new_prediction = design_matrix[:, proposed_active] @ proposed_coefficients + new_rmse = float(np.sqrt(np.mean(np.square(target - new_prediction)))) + if new_rmse > old_rmse + accepted_rmse_increase: + break + + for local_index in np.flatnonzero(negligible): + removed.append({ + "term": terms[int(active[local_index])].to_str(), + "coefficient": float(coefficients[local_index]), + "contribution_rms": float(contribution_rms[local_index]), + "maximum_absolute_contribution": float(contribution_max[local_index]), + }) + active = proposed_active + coefficients = proposed_coefficients + + return [terms[int(index)] for index in active], coefficients, removed + + def _get_allowed_interactions( + self, + features: List[engine.Expression], + include_interactions: bool, + blacklist: Optional[List[Tuple[str, str]]], + whitelist: Optional[List[Tuple[str, str]]], + ) -> Set[Tuple[str, str]]: + """Get allowed interaction term combinations. + + Args: + features: List of symbolic features. + include_interactions: Whether to include interaction terms. + blacklist: List of variable pairs to exclude from interactions. + whitelist: List of variable pairs to allow for interactions. + + Returns: + Set of allowed variable pair combinations. + """ + if not include_interactions: + return set() + + # 生成所有可能的变量对 + all_pairs = set(combinations(sorted([f.to_str() for f in features]), 2)) + + if whitelist is not None: + # 白名单模式:只允许白名单中的组合 + whitelist_normalized = set( + tuple(sorted(pair)) for pair in whitelist + ) + allowed = all_pairs & whitelist_normalized + else: + # 默认允许所有组合,除非在黑名单中 + allowed = all_pairs + + if blacklist is not None: + blacklist_normalized = set( + tuple(sorted(pair)) for pair in blacklist + ) + allowed -= blacklist_normalized + + return allowed + + def generate_terms( + self, + features: List[engine.Expression], + max_degree: int, + allowed_interactions: Set[Tuple[str, str]], + include_bias: bool, + ) -> List[engine.Expression]: + """Generate symbolic terms up to a total degree. + + Args: + features: Input feature expressions. + max_degree: Maximum total polynomial degree. + allowed_interactions: Optional interaction combinations to retain. + include_bias: Whether to include the constant term. + + Returns: + Generated polynomial terms.""" + n_vars = len(features) + terms = [] + for powers in sorted(product(range(max_degree + 1), repeat=n_vars), key=lambda p: (sum(p), p)): + total_degree = sum(powers) + if total_degree == 0: + if not include_bias: + continue + terms.append(engine.parse("1")) + continue + if total_degree > max_degree: + continue + + non_zero_indices = [i for i, power in enumerate(powers) if power > 0] + if not allowed_interactions and len(non_zero_indices) > 1: + continue + if allowed_interactions: + allowed = True + for i, j in combinations(non_zero_indices, 2): + pair = tuple(sorted((features[i].to_str(), features[j].to_str()))) + if pair not in allowed_interactions: + allowed = False + break + if not allowed: + continue + + factors = [] + for feature, power in zip(features, powers): + if power > 0: + factors.append(feature if power == 1 else feature ** power) + terms.append(reduce(lambda a, b: a * b, factors)) + return terms + + def _build_design_matrix( + self, + data: Dict[str, np.ndarray], + terms: List[engine.Expression], + n_samples: int, + ) -> np.ndarray: + """Evaluate symbolic terms to build the design matrix.""" + columns = [] + for term in terms: + values = np.asarray(term.eval(data)) + if values.ndim == 0: + values = np.full(n_samples, float(values)) + else: + values = values.flatten() + columns.append(values) + return np.column_stack(columns) if columns else np.zeros((n_samples, 0)) diff --git a/src/sr_harness/tools/power_law_fit.py b/src/sr_harness/tools/power_law_fit.py new file mode 100644 index 0000000000000000000000000000000000000000..b61fff7ec9897dc53cd67dab760cb250065cd24c --- /dev/null +++ b/src/sr_harness/tools/power_law_fit.py @@ -0,0 +1,320 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""乘法幂律拟合工具。""" +import numpy as np +from fractions import Fraction +from scipy.stats import t as student_t +from typing import Any, Dict, List +from .base_tool import BaseTool, ToolMetadata, is_numeric_array + + +@BaseTool.register("power_law_fit") +class PowerLawFitTool(BaseTool): + """Implementation of the power law fit tool.""" + metadata = ToolMetadata("power_law_fit") + + def execute( + self, + x: List[str] = None, + y: str = None, + include_scale: bool = True, + snap_exponents: bool = False, + max_denominator: int = 8, + snap_tolerance: float = 0.05, + max_snap_rmse_degradation: float = 0.01, + n_stability_folds: int = 5, + show_diagnostics: bool = True, + ) -> Dict[str, Any]: + """Fit a multiplicative power law y = c * product(x_i ** p_i) in log space. + + Args: + x: Strictly positive input variables or expressions on every training sample. Use all numeric non-target variables by default. + y: Strictly positive target variable or expression on every training sample. Use the formula-discovery target by default. + include_scale: Whether to fit the multiplicative scale c. + snap_exponents: Whether to try nearby simple rational exponents and refit c. + max_denominator: Largest denominator considered when snapping exponents (1-32). + snap_tolerance: Maximum distance from every fitted exponent to its snapped value. + max_snap_rmse_degradation: Maximum normalized RMSE degradation allowed after snapping. + n_stability_folds: Number of disjoint folds for leave-one-fold-out exponent confidence intervals (2-20). + show_diagnostics: Whether final metrics should include compact residual diagnostics. + """ + data = self.context.data + if y is not None and not isinstance(y, str): + return {"exceptions": [f"y must be a string expression, got {type(y).__name__}."]} + if x is not None and (not isinstance(x, list) or any(not isinstance(item, str) for item in x)): + return {"exceptions": ["x must be a list of string expressions."]} + target_name = (y or self.context.target).strip().strip('"').strip("'") + x = x or [name for name, value in data.items() if name != target_name and is_numeric_array(value)] + y_symbol = self.parse_formula(target_name) + target = np.asarray(y_symbol.eval(data), dtype=float).flatten() + if target.size == 0: + return {"exceptions": [f"{target_name}: no training values; power_law_fit requires positive samples."]} + + features = [] + for expression in x: + value = data[expression] if expression in data else self.parse_formula(expression).eval(data) + if not is_numeric_array(value): + raise ValueError(f"'{expression}' did not produce numeric values") + value = np.asarray(value, dtype=float).flatten() + if value.shape != target.shape: + raise ValueError(f"Feature '{expression}' shape does not match target shape.") + features.append((expression, value)) + if not features: + raise ValueError("No valid input variables available for fitting.") + + exceptions = [] + for name, values in [*features, (target_name, target)]: + finite = np.isfinite(values) + nonpositive = int(np.count_nonzero(finite & (values <= 0))) + nonfinite = int(np.count_nonzero(~finite)) + total = values.size + if nonpositive: + exceptions.append( + f"{name} has {nonpositive}/{total} " + f"({self._format_percentage(nonpositive, total)}) non-positive finite values" + ) + if nonfinite: + exceptions.append( + f"{name} has {nonfinite}/{total} " + f"({self._format_percentage(nonfinite, total)}) non-finite values" + ) + if exceptions: + return {"exceptions": exceptions, "domain_inapplicable": True} + if len(target) < 2: + return {"exceptions": ["At least two training samples are required for exponent confidence intervals."]} + + valid = np.ones(target.shape, dtype=bool) + + log_x = np.column_stack([np.log(values[valid]) for _, values in features]) + log_y = np.log(np.abs(target[valid])) + design = np.column_stack([np.ones(len(log_x)), log_x]) if include_scale else log_x + coefficients, _, rank, _ = np.linalg.lstsq(design, log_y, rcond=None) + if include_scale: + log_scale, raw_exponents = coefficients[0], coefficients[1:] + else: + log_scale, raw_exponents = 0.0, coefficients + raw_scale = float(np.exp(log_scale)) + + max_denominator = max(1, min(int(max_denominator), 32)) + snapped_fractions = [ + Fraction(float(value)).limit_denominator(max_denominator) + for value in raw_exponents + ] + snapped_exponents = np.asarray([float(value) for value in snapped_fractions]) + snapped_log_scale = ( + float(np.mean(log_y - log_x @ snapped_exponents)) if include_scale else 0.0 + ) + snapped_scale = float(np.exp(snapped_log_scale)) + + raw_prediction = self._predict(features, valid, raw_exponents, raw_scale) + snapped_prediction = self._predict(features, valid, snapped_exponents, snapped_scale) + raw_rmse = float(np.sqrt(np.mean((raw_prediction - target[valid]) ** 2))) + snapped_rmse = float(np.sqrt(np.mean((snapped_prediction - target[valid]) ** 2))) + target_rms = max(float(np.sqrt(np.mean(target[valid] ** 2))), np.finfo(float).eps) + degradation = (snapped_rmse - raw_rmse) / target_rms + distances = np.abs(raw_exponents - snapped_exponents) + snap_accepted = bool( + snap_exponents + and np.all(distances <= max(float(snap_tolerance), 0.0)) + and degradation <= max(float(max_snap_rmse_degradation), 0.0) + ) + + exponents = snapped_exponents if snap_accepted else raw_exponents + scale = snapped_scale if snap_accepted else raw_scale + prediction = snapped_prediction if snap_accepted else raw_prediction + factors = [] + for index, ((name, _), power) in enumerate(zip(features, exponents)): + if power == 0: + continue + if snap_accepted: + fraction = snapped_fractions[index] + exponent = ( + f"Number({fraction.numerator}) / Number({fraction.denominator})" + if fraction.denominator != 1 else str(fraction.numerator) + ) + else: + exponent = f"{float(power):.12g}" + base = name if name.isidentifier() else f"({name})" + exponent = f"({exponent})" if "/" in exponent else exponent + factors.append(f"{base} ** {exponent}") + formula = f"{scale:.12g}" + (" * " + " * ".join(factors) if factors else "") + evaluation = self.evaluate( + f=self.parse_formula(formula), y=y_symbol, + show_diagnostics=show_diagnostics, + ) + evaluation["data_split_results"]["train"]["metrics"].update({ + "log_rmse": float(np.sqrt(np.mean((np.log(np.abs(prediction)) - log_y) ** 2))), + "valid_sample_ratio": float(np.mean(valid)), + }) + + n_stability_folds = min(max(int(n_stability_folds), 2), 20, len(log_y)) + folds = np.array_split(np.random.default_rng(0).permutation(len(log_y)), n_stability_folds) + leave_fold_out_exponents = [] + for held_out in range(n_stability_folds): + fit_indices = np.concatenate([fold for i, fold in enumerate(folds) if i != held_out]) + subset_coef = np.linalg.lstsq(design[fit_indices], log_y[fit_indices], rcond=None)[0] + leave_fold_out_exponents.append(subset_coef[1:] if include_scale else subset_coef) + leave_fold_out_exponents = np.asarray(leave_fold_out_exponents) + pseudo_values = ( + n_stability_folds * raw_exponents + - (n_stability_folds - 1) * leave_fold_out_exponents + ) + standard_errors = np.std(pseudo_values, axis=0, ddof=1) / np.sqrt(n_stability_folds) + margin = student_t.ppf(0.975, df=n_stability_folds - 1) * standard_errors + + result = evaluation | { + "exponents": {name: float(value) for (name, _), value in zip(features, exponents)}, + "exponent_confidence_intervals": { + name: [float(value - width), float(value + width)] + for (name, _), value, width in zip(features, raw_exponents, margin) + }, + "exponent_stability_folds": { + "number_of_folds": n_stability_folds, + "training_samples": len(log_y), + "method": "delete-one-fold jackknife t interval", + "degrees_of_freedom": n_stability_folds - 1, + }, + "exceptions": [] if rank == design.shape[1] else ["Log-space design matrix is rank deficient."], + } + if snap_exponents: + raw_validation_r2 = self._validation_r2(features, y_symbol, raw_exponents, raw_scale) + snapped_validation_r2 = self._validation_r2( + features, y_symbol, snapped_exponents, snapped_scale + ) + result["simple_exponent_check"] = { + "rounding_applied": snap_accepted, + "raw_exponents": {name: float(value) for (name, _), value in zip(features, raw_exponents)}, + "snapped_exponents": {name: float(value) for (name, _), value in zip(features, snapped_exponents)}, + "snapped_exponent_expressions": { + name: str(value) for (name, _), value in zip(features, snapped_fractions) + }, + "rmse_increase_as_fraction_of_target_rms": float(degradation), + "training_samples": len(log_y), + "raw_validation_r2": raw_validation_r2, + "snapped_validation_r2": snapped_validation_r2, + } + excluded = { + name: [float(np.min(values[~valid & np.isfinite(values)])), float(np.max(values[~valid & np.isfinite(values)]))] + for name, values in features if np.any(~valid & np.isfinite(values)) + } + if excluded: + result["excluded_finite_ranges"] = excluded + return result + + @staticmethod + def _predict(features, valid, exponents, scale): + return scale * np.prod(np.column_stack([ + values[valid] ** exponent + for (_, values), exponent in zip(features, exponents) + ]), axis=1) + + @staticmethod + def _format_percentage(count: int, total: int) -> str: + value = 100 * count / total + display = f"{value:.3g}" + if "." not in display and "e" not in display: + display += ".0" + return f"{display}%" + + def _validation_r2(self, features, y_symbol, exponents, scale): + """Score an exponent candidate on the same complete, positive validation rows.""" + data = self.context.validation_split.data + if not data: + return None + try: + target = np.asarray(y_symbol.eval(data), dtype=float).flatten() + validation_features = [] + for expression, _ in features: + values = data[expression] if expression in data else self.parse_formula(expression).eval(data) + values = np.asarray(values, dtype=float).flatten() + if values.shape != target.shape or not np.all(np.isfinite(values) & (values > 0)): + return None + validation_features.append((expression, values)) + if not np.all(np.isfinite(target) & (target > 0)): + return None + with np.errstate(over="ignore", invalid="ignore", divide="ignore"): + prediction = self._predict( + validation_features, np.ones(target.shape, dtype=bool), exponents, scale + ) + if not np.all(np.isfinite(prediction)): + return None + total = float(np.sum((target - np.mean(target)) ** 2)) + return float(1 - np.sum((prediction - target) ** 2) / total) if total > 0 else None + except (ArithmeticError, TypeError, ValueError, KeyError): + return None + + @staticmethod + def _format_ci_endpoints(lower: float, upper: float) -> tuple[str, str]: + """Show at least three significant digits, up to six if needed to separate endpoints.""" + for precision in range(3, 7): + left = format(lower, f"#.{precision}g").removesuffix(".") + right = format(upper, f"#.{precision}g").removesuffix(".") + if left != right or precision == 6: + return left, right + + @classmethod + def format_result_dict(cls, result: Dict[str, Any]) -> str: + """Format a tool result for the language model. + + Args: + result: Result mapping to format or update. + + Returns: + str: The operation result. + """ + if "data_split_results" not in result: + if result.get("domain_inapplicable"): + issues = "\n".join(f" {issue}" for issue in result["exceptions"]) + return ( + f"Power-law fitting not applicable:\n{issues}\n" + "power_law_fit requires every x and y value to be finite and strictly positive." + ) + return "Power-law fitting not applicable: " + "; ".join(result.get("exceptions", [])) + lines = [cls.format_evaluation_result(result, title="Best fitted power-law formula")] + refits = result["exponent_stability_folds"] + n_folds = refits["number_of_folds"] + lines.append( + f"Exponent stability (Divide the {refits['training_samples']} training samples into " + f"{n_folds} folds, use {n_folds - 1} of the folds to fit the exponents, " + f"and repeat the process {n_folds} times):" + ) + for name, (lower, upper) in result["exponent_confidence_intervals"].items(): + left, right = cls._format_ci_endpoints(lower, upper) + lines.append(f" {name}: 95% CI=[{left}, {right}];") + if check := result.get("simple_exponent_check"): + lines.append("Simplified exponent check:") + snapped_display = check.get("snapped_exponent_expressions", check["snapped_exponents"]) + raw_r2 = check["raw_validation_r2"] + snapped_r2 = check["snapped_validation_r2"] + if raw_r2 is None or snapped_r2 is None: + effect = ( + f"replacing them with {snapped_display} cannot be compared " + "on a validation set" + ) + else: + change = snapped_r2 - raw_r2 + magnitude = f"{abs(change):#.3g}".removesuffix(".") + if change > 0: + verb = "increased" if check["rounding_applied"] else "would increase" + effect = f"replacing them with {snapped_display} {verb} validation-set R2 by {magnitude}" + elif change < 0: + verb = "decreased" if check["rounding_applied"] else "would decrease" + effect = f"replacing them with {snapped_display} {verb} validation-set R2 by {magnitude}" + else: + verb = "did not change" if check["rounding_applied"] else "would not change" + effect = f"replacing them with {snapped_display} {verb} validation-set R2" + ending = ( + "; the simplified exponents were thus used as the best fitted power-law formula." + if check["rounding_applied"] else "." + ) + lines.append( + f" Direct fitting on {check['training_samples']} samples yields exponents: " + f"{check['raw_exponents']}; {effect}{ending}" + ) + if "excluded_finite_ranges" in result: + lines.append( + "Domain warning: these finite input ranges were excluded because at least one power-law " + f"domain requirement failed: {result['excluded_finite_ranges']}." + ) + if result["exceptions"]: + lines.append("Exceptions: " + "; ".join(result["exceptions"])) + return "\n".join(lines) diff --git a/src/sr_harness/tools/predict_property.py b/src/sr_harness/tools/predict_property.py new file mode 100644 index 0000000000000000000000000000000000000000..0ba126597bb8da7fb90309b72b08dbbc6c7ab47d --- /dev/null +++ b/src/sr_harness/tools/predict_property.py @@ -0,0 +1,398 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""数据性质预测工具。 + +使用预训练的 Transformer 模型从数据样本中预测公式的数学性质 +(单调性、凹凸性、周期性、乘法可分性),并自动分析变量组合的性质, +为符号回归搜索提供先验知识指导。 + +可通过下述指令将模型上传到 Github Release(需要设置 GITHUB_TOKEN 环境变量) + python scripts/upload_models.py --checkpoint path/to/model.pth --name property-scratch-v5 --release-tag sr-agent-models-v5 +可通过下述指令从 Github Release 下载模型到本地(或者在首次调用时自动下载) + python scripts/download_models.py --checkpoint path/to/save/model.pth --name property-scratch-v5 --release-tag sr-agent-models-v5 +""" +from __future__ import annotations + +import logging +import os +import numpy as np +from pathlib import Path +from typing import Dict, Any, List, Literal +from ..utils import download_model, get_default, tag2ansi +from .base_tool import BaseTool, ToolMetadata, ToolRunAbort, is_numeric_array + +_logger = logging.getLogger(f"sr_harness.{__name__}") +_PROJECT_ROOT = Path(__file__).resolve().parents[3] +_MODEL_CACHE_DIR = _PROJECT_ROOT / ".cache" / "nn_tools" +_MONO_LABELS = {0: "non-monotonic", 1: "increasing", 2: "decreasing", 3: "constant"} +_CONV_LABELS = {0: "non-convex/concave", 1: "convex", 2: "concave", 3: "affine"} +_PERIOD_LABELS = {0: "non-periodic", 1: "periodic"} +_SEP_LABELS = {0: "not multiplicatively separable", 1: "multiplicatively separable"} +_COMBO_OPS = { + "*": lambda a, b: a * b, + "+": lambda a, b: a + b, + "-": lambda a, b: a - b, + "/": lambda a, b: np.where(np.abs(b) > 1e-12, a / b, np.nan), +} +_cached_model = {} + + +def _load_model(checkpoint_path: str, device: str = "cpu"): + """Load model from checkpoint with caching to avoid repeated I/O.""" + import torch + + cache_key = (checkpoint_path, device) + if cache_key in _cached_model: + return _cached_model[cache_key] + + import sys + exp_path = str(_PROJECT_ROOT / "src" / "experimental") + if exp_path not in sys.path: + sys.path.insert(0, exp_path) + + import argparse + from nn_tools.models import FloatEmbedder, DataEmbedder, PropertyPredictionModel + + ckpt = torch.load(checkpoint_path, map_location=device, weights_only=False) + saved_args = ckpt["args"] + if isinstance(saved_args, dict): + saved_args = argparse.Namespace(**saved_args) + + float_emb = FloatEmbedder(d_model=saved_args.d_model).to(device) + data_emb = DataEmbedder( + d_model=saved_args.d_model, + pooling=saved_args.data_pooling, + float_embedder=float_emb, + ).to(device) + model = PropertyPredictionModel(saved_args).to(device) + + model.load_state_dict(ckpt["model"]) + float_emb.load_state_dict(ckpt["float_embedder"]) + data_emb.load_state_dict(ckpt["data_embedder"]) + + model.eval() + float_emb.eval() + data_emb.eval() + + result = (model, float_emb, data_emb, saved_args) + _cached_model[cache_key] = result + _logger.info(f"Loaded property prediction model from {checkpoint_path}") + return result + + +def _predict(model, float_emb, data_emb, data_arr: np.ndarray, device: str) -> dict: + """Run model inference on a single (sample_num, max_var+1) data array. + + Returns raw logits dict with keys: monotonicity, convexity, periodicity, + multiplicative_separable. + """ + import torch + data_tensor = torch.from_numpy(data_arr).unsqueeze(0) + with torch.no_grad(): + B, S = data_tensor.shape[:2] + val_emb = float_emb(data_tensor.to(device)).flatten(0, 1) + d_emb = data_emb.pool(val_emb).reshape(B, S, -1) + out = model(d_emb) + return {k: v[0].cpu().numpy() for k, v in out.items()} + + +def _decode_per_var(logits: np.ndarray, label_map: dict, n_vars: int) -> list: + """Decode per-variable logits into list of (pred_label, confidence).""" + probs = _softmax(logits) + preds = logits.argmax(axis=-1) + results = [] + for i in range(n_vars): + pred = int(preds[i]) + conf = float(probs[i, pred]) + results.append((label_map[pred], round(conf, 3))) + return results + + +# 此工具尚未处于 Ready 状态 +# @BaseTool.register("predict_property") +class PropertyPredictorTool(BaseTool): + """Implementation of the property predictor tool.""" + metadata = ToolMetadata(name="predict_property") + + MODEL_TYPE: Literal[ + "property-scratch", + "property-finetune", + "property-scratch-v5", + ] = "property-scratch-v5" + MODEL_RELEASE_TAG: str = "sr-agent-models-v5" + DEVICE: str = "cpu" + AUTO_DOWNLOAD: bool = True + + def execute(self) -> Dict[str, Any]: + """Predict mathematical properties of the data using a neural network. + This tool analyzes the relationship between input variables and the target to detect: + - **Monotonicity**: Whether y is monotonically increasing, decreasing, or constant w.r.t. each variable. + - **Convexity**: Whether y is convex, concave, or affine w.r.t. each variable. + - **Periodicity**: A heuristic per-variable periodicity prediction. A negative + prediction does not rule out a periodic term modulated by another variable + (for example x * sin(omega * t)). + - **Multiplicative Separability**: Whether y = f(x1) * g(x2) * ... + Additionally, this tool automatically tests variable COMBINATIONS (xi*xj, xi+xj, xi-xj, xi/xj) + to detect properties that only emerge in combinations (e.g., sin(x1*x2) is periodic in x1*x2 + but neither x1 nor x2 alone appears periodic). + No arguments needed — the tool automatically uses the data provided to the agent. + """ + data = self.context.data + target_name = self.context.target + exceptions = [] + + ## 加载模型 checkpoint + default_ckpt_path = _MODEL_CACHE_DIR / f"{self.MODEL_TYPE}.pth" + ckpt_path = Path(os.getenv("SR_AGENT_PROPERTY_MODEL_CHECKPOINT") or default_ckpt_path).expanduser() + repo = get_default("repo") + release_url = f"https://github.com/{repo}/releases/tag/{self.MODEL_RELEASE_TAG}" + if not ckpt_path.exists() and self.AUTO_DOWNLOAD: + _logger.info( + f"Model checkpoint {ckpt_path} not found, attempting to download from GitHub..." + f"You can also download it manually if it takes too long or fails. To do so, visit the GitHub Release page\n" + f" [blue bold]{release_url}[reset]\n" + f"and download the asset named\n" + f" [blue bold]{self.MODEL_TYPE!r}[reset]\n" + f"Then save it as\n" + f" [blue bold]{ckpt_path}[reset]\n" + ) + download_model(name=self.MODEL_TYPE, checkpoint=ckpt_path, release_tag=self.MODEL_RELEASE_TAG) + if not ckpt_path.exists(): + raise ToolRunAbort(tag2ansi( + f"Model checkpoint not found: {ckpt_path}.\n" + f"Automatic download was not available. To use predict_property, please visit the GitHub Release page\n" + f" [blue bold]{release_url}[reset]\n" + f"and download the asset named\n" + f" [blue bold]{self.MODEL_TYPE!r}[reset]\n" + f"Then save it as\n" + f" [blue bold]{ckpt_path}[reset]\n" + "Alternatively, you can ban this predict_property tool to avoid this error." + )) + + model, float_emb, data_emb, saved_args = _load_model(ckpt_path, self.DEVICE) + max_var_num = saved_args.max_var_num + + input_vars = [v for v in data if v != target_name and is_numeric_array(data[v])] + if len(input_vars) > max_var_num: + input_vars = input_vars[:max_var_num] + exceptions.append(f"Too many variables ({len(data) - 1}), only the first {max_var_num} are analyzed: {input_vars}") + + n_vars = len(input_vars) + if not is_numeric_array(data[target_name]): + raise ValueError(f"Target variable '{target_name}' did not produce numeric values.") + y_arr = np.asarray(data[target_name], dtype=np.float32).flatten() + n_samples = len(y_arr) + + sample_num = min(n_samples, 200) + rng = np.random.default_rng(42) + idx = rng.choice(n_samples, sample_num, replace=False) if n_samples > sample_num else np.arange(n_samples) + + var_arrays = {} + for var in input_vars: + var_arrays[var] = np.asarray(data[var], dtype=np.float32).flatten()[idx] + + # --- Per-variable prediction --- + data_arr = np.zeros((sample_num, max_var_num + 1), dtype=np.float32) + for i, var in enumerate(input_vars): + data_arr[:, i] = var_arrays[var] + data_arr[:, -1] = y_arr[idx] + + out = _predict(model, float_emb, data_emb, data_arr, self.DEVICE) + + mono_decoded = _decode_per_var(out["monotonicity"], _MONO_LABELS, n_vars) + conv_decoded = _decode_per_var(out["convexity"], _CONV_LABELS, n_vars) + period_decoded = _decode_per_var(out["periodicity"], _PERIOD_LABELS, n_vars) + + sep_logits = out["multiplicative_separable"] + sep_probs = _softmax(sep_logits) + sep_pred = int(sep_logits.argmax()) + sep_conf = float(sep_probs[sep_pred]) + + monotonicity = {} + convexity = {} + periodicity = {} + for i, var in enumerate(input_vars): + monotonicity[var] = {"prediction": mono_decoded[i][0], "confidence": mono_decoded[i][1]} + convexity[var] = {"prediction": conv_decoded[i][0], "confidence": conv_decoded[i][1]} + periodicity[var] = {"prediction": period_decoded[i][0], "confidence": period_decoded[i][1]} + + separability = { + "prediction": _SEP_LABELS[sep_pred], + "confidence": round(sep_conf, 3), + } + + # --- Variable combination prediction --- + combo_results = {} + if n_vars >= 2: + for i in range(n_vars): + for j in range(i + 1, n_vars): + vi, vj = input_vars[i], input_vars[j] + xi, xj = var_arrays[vi], var_arrays[vj] + for op_name, op_fn in _COMBO_OPS.items(): + combo_name = f"{vi}{op_name}{vj}" + combo_val = op_fn(xi, xj).astype(np.float32) + if not np.all(np.isfinite(combo_val)): + valid = np.isfinite(combo_val) + if valid.sum() < 20: + continue + combo_val = combo_val[valid] + y_combo = y_arr[idx][valid] + combo_s = len(combo_val) + else: + y_combo = y_arr[idx] + combo_s = sample_num + + remaining_vars = [input_vars[k] for k in range(n_vars) if k != i and k != j] + n_combo_vars = 1 + len(remaining_vars) + + combo_arr = np.zeros((combo_s, max_var_num + 1), dtype=np.float32) + combo_arr[:, 0] = combo_val[:combo_s] + for ri, rv in enumerate(remaining_vars): + if not np.all(np.isfinite(combo_val)): + combo_arr[:, 1 + ri] = var_arrays[rv][valid][:combo_s] + else: + combo_arr[:, 1 + ri] = var_arrays[rv][:combo_s] + combo_arr[:, -1] = y_combo[:combo_s] + + combo_out = _predict(model, float_emb, data_emb, combo_arr, self.DEVICE) + + combo_mono = _decode_per_var(combo_out["monotonicity"], _MONO_LABELS, 1) + combo_conv = _decode_per_var(combo_out["convexity"], _CONV_LABELS, 1) + combo_period = _decode_per_var(combo_out["periodicity"], _PERIOD_LABELS, 1) + + combo_results[combo_name] = { + "monotonicity": {"prediction": combo_mono[0][0], "confidence": combo_mono[0][1]}, + "convexity": {"prediction": combo_conv[0][0], "confidence": combo_conv[0][1]}, + "periodicity": {"prediction": combo_period[0][0], "confidence": combo_period[0][1]}, + } + + result = { + "target": target_name, + "monotonicity": monotonicity, + "convexity": convexity, + "periodicity": periodicity, + "multiplicative_separable": separability, + "n_variables_analyzed": n_vars, + "n_samples_used": sample_num, + "exceptions": exceptions, + } + if combo_results: + result["variable_combinations"] = combo_results + + return result + + @classmethod + def format_result_dict(cls, result: Dict[str, Any]) -> str: + """Format a tool result for the language model. + + Args: + result: Result mapping to format or update. + + Returns: + str: The operation result. + """ + if "error" in result: + return f"Error: {result['error']}" + + lines = [ + f"Heuristic neural-network property predictions for target {result['target']!r} " + f"(analyzed {result['n_variables_analyzed']} variables using {result['n_samples_used']} sampled rows):", + "Model scores below are uncalibrated confidence-like scores, not statistical proof. Treat low-score predictions as uncertain.", + "", + "=== Per-Variable Properties ===", + "", + "Monotonicity (whether y is monotonic w.r.t. each variable):", + ] + for var, info in result["monotonicity"].items(): + label = info['prediction'] if info['confidence'] >= 0.6 else f"uncertain; top label is {info['prediction']}" + lines.append(f" {var}: {label} (model score: {info['confidence']:.1%})") + + lines.append("") + lines.append("Convexity (whether y is convex/concave w.r.t. each variable):") + for var, info in result["convexity"].items(): + label = info['prediction'] if info['confidence'] >= 0.6 else f"uncertain; top label is {info['prediction']}" + lines.append(f" {var}: {label} (model score: {info['confidence']:.1%})") + + lines.append("") + lines.append("Periodicity (whether y is periodic w.r.t. each variable):") + for var, info in result["periodicity"].items(): + label = info['prediction'] if info['confidence'] >= 0.6 else f"uncertain; top label is {info['prediction']}" + lines.append(f" {var}: {label} (model score: {info['confidence']:.1%})") + lines.append( + "Caution: a 'non-periodic' label cannot exclude modulated oscillations such as " + "x * sin(omega * t); test such interactions against data when scientifically plausible." + ) + + sep = result["multiplicative_separable"] + lines.append("") + sep_label = sep['prediction'] if sep['confidence'] >= 0.6 else f"uncertain; top label is {sep['prediction']}" + lines.append(f"Multiplicative Separability: {sep_label} (model score: {sep['confidence']:.1%})") + + # Per-variable hints + if any(info["prediction"] == "periodic" and info["confidence"] >= 0.6 for info in result["periodicity"].values()): + lines.append("") + lines.append("Hint: Periodic variables suggest the formula likely contains trigonometric functions " + "(sin, cos) of those variables.") + + if (result["multiplicative_separable"]["prediction"] == "multiplicatively separable" + and result["multiplicative_separable"]["confidence"] >= 0.6): + lines.append("") + lines.append("Hint: The formula may be expressible as a product of functions of individual variables, " + "e.g., y = f(x1) * g(x2). Try decomposing the problem.") + + # Variable combination results + combo = result.get("variable_combinations", {}) + if combo: + lines.append("") + lines.append("=== Variable Combination Properties ===") + lines.append("(Analyzing xi*xj, xi+xj, xi-xj, xi/xj to detect combination-level properties)") + lines.append("") + + interesting = [] + for cname, cinfo in combo.items(): + flags = [] + if cinfo["periodicity"]["prediction"] == "periodic" and cinfo["periodicity"]["confidence"] >= 0.6: + flags.append(f"periodic ({cinfo['periodicity']['confidence']:.1%})") + if (cinfo["monotonicity"]["prediction"] in ("increasing", "decreasing") + and cinfo["monotonicity"]["confidence"] >= 0.6): + flags.append(f"{cinfo['monotonicity']['prediction']} ({cinfo['monotonicity']['confidence']:.1%})") + if (cinfo["convexity"]["prediction"] in ("convex", "concave") + and cinfo["convexity"]["confidence"] >= 0.6): + flags.append(f"{cinfo['convexity']['prediction']} ({cinfo['convexity']['confidence']:.1%})") + if flags: + interesting.append((cname, flags, cinfo)) + + if interesting: + for cname, flags, cinfo in interesting: + lines.append(f" {cname}: {', '.join(flags)}") + lines.append("") + lines.append("Hint: Variable combinations with detected properties suggest the formula may contain " + "functions of those combinations. For example:") + for cname, flags, cinfo in interesting: + if (cinfo["periodicity"]["prediction"] == "periodic" + and cinfo["periodicity"]["confidence"] >= 0.6): + lines.append(f" - {cname} is periodic → consider sin({cname}), cos({cname})") + if (cinfo["monotonicity"]["prediction"] in ("increasing", "decreasing") + and cinfo["monotonicity"]["confidence"] >= 0.6): + lines.append(f" - {cname} is {cinfo['monotonicity']['prediction']} → y may depend on {cname} directly or via a monotonic function") + if (cinfo["convexity"]["prediction"] in ("convex", "concave") + and cinfo["convexity"]["confidence"] >= 0.6): + lines.append(f" - {cname} is {cinfo['convexity']['prediction']} → consider {cname}², sqrt({cname}), exp({cname}), etc.") + else: + lines.append(" No notable properties detected in variable combinations.") + lines.append("") + lines.append("Note: Even though no combination properties were detected, complex variable " + "combinations (e.g., sin(xi-xj), cos(xi*xj)) should still be explored " + "as the model may not capture all patterns.") + + if result["exceptions"]: + lines.append("") + lines.append("Exceptions / Warnings:") + for ex in result["exceptions"]: + lines.append(f" - {ex}") + + return "\n".join(lines) + + +def _softmax(logits: np.ndarray) -> np.ndarray: + e = np.exp(logits - logits.max(axis=-1, keepdims=True)) + return e / e.sum(axis=-1, keepdims=True) diff --git a/src/sr_harness/tools/rational_fit.py b/src/sr_harness/tools/rational_fit.py new file mode 100644 index 0000000000000000000000000000000000000000..38cc40f2ae7e5d1c471a3f06b28bc9617b1b09e5 --- /dev/null +++ b/src/sr_harness/tools/rational_fit.py @@ -0,0 +1,301 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""有理式拟合工具。""" +import numpy as np +from typing import Any, Dict, List +from .polynomial_fit import PolynomialFitTool +from .base_tool import BaseTool, ToolMetadata, is_numeric_array + + +@BaseTool.register("rational_fit") +class RationalFitTool(BaseTool): + """Implementation of the rational fit tool.""" + metadata = ToolMetadata("rational_fit") + + def execute( + self, + x: List[str] = None, + y: str = None, + numerator_degree: int = 2, + denominator_degree: int = 1, + include_interactions: bool = True, + numerator_degrees: List[int] = None, + denominator_degrees: List[int] = None, + validation_fraction: float = 0.2, + top_k: int = 5, + complexity_penalty: float = 1e-12, + show_diagnostics: bool = True, + ) -> Dict[str, Any]: + """Fit a rational expression P(x) / Q(x) by linearized least squares with Q's constant fixed to one. + + Args: + x: Input variables or expressions. Use all numeric non-target variables by default. + y: Target variable or expression. Use the formula-discovery target by default. + numerator_degree: Maximum total degree of numerator P (0-8). + denominator_degree: Maximum total degree of denominator Q excluding its fixed constant (0-8). + include_interactions: Whether polynomial terms may contain multiple input features. + numerator_degrees: Optional numerator degree grid; overrides numerator_degree when provided. + denominator_degrees: Optional denominator degree grid; overrides denominator_degree when provided. + validation_fraction: Deterministic holdout fraction used to rank degree combinations (0.05-0.5). + top_k: Number of degree-grid candidates to return (1-20). + complexity_penalty: Penalty per fitted coefficient added to validation RMSE after target-scale normalization. + show_diagnostics: Whether final metrics should include compact residual diagnostics. + """ + data = self.context.data + target_name = (y or self.context.target).strip().strip('"').strip("'") + x = x or [name for name, value in data.items() if name != target_name and is_numeric_array(value)] + p_degrees = sorted(set( + max(0, min(int(value), 8)) + for value in (numerator_degrees if numerator_degrees is not None else [numerator_degree]) + )) + q_degrees = sorted(set( + max(0, min(int(value), 8)) + for value in (denominator_degrees if denominator_degrees is not None else [denominator_degree]) + )) + validation_fraction = min(max(float(validation_fraction), 0.05), 0.5) + top_k = min(max(int(top_k), 1), 20) + complexity_penalty = max(float(complexity_penalty), 0.0) + eq_y = self.parse_formula(target_name) + target = np.asarray(eq_y.eval(data), dtype=float).flatten() + symbols, valid_x, exceptions = [], [], [] + for expression in x: + try: + symbol = self.parse_formula(expression) + value = np.asarray(symbol.eval(data), dtype=float).flatten() + if value.shape != target.shape: + raise ValueError("shape mismatch") + symbols.append(symbol) + valid_x.append(expression) + except Exception as exc: + exceptions.append(f"Failed to compute '{expression}': {exc}") + if not symbols: + raise ValueError("No valid input variables available for fitting.") + helper = PolynomialFitTool(context=self.context) + allowed = helper._get_allowed_interactions(symbols, include_interactions, None, None) + finite_target = np.isfinite(target) + finite_indices = np.flatnonzero(finite_target) + order = np.random.default_rng(0).permutation(finite_indices) + n_validation = max(2, int(round(len(order) * validation_fraction))) + validation_indices, train_indices = order[:n_validation], order[n_validation:] + candidates = [] + for p_degree in p_degrees: + for q_degree in q_degrees: + try: + model = self._fit_model(helper, symbols, allowed, data, target, train_indices, p_degree, q_degree) + candidate = self._score_model( + model, target, eq_y, train_indices, validation_indices, + show_diagnostics=False, + ) + candidate["numerator_degree"] = p_degree + candidate["denominator_degree"] = q_degree + candidates.append(candidate) + except Exception as exc: + exceptions.append(f"Degree ({p_degree}, {q_degree}) failed: {exc}") + if not candidates: + raise ValueError("No rational degree combination could be fitted.") + target_scale = float(np.sqrt(np.mean(target[finite_target] ** 2))) + for candidate in candidates: + candidate["selection_score"] = ( + candidate["validation_rmse"] / max(target_scale, np.finfo(float).eps) + + complexity_penalty * candidate["complexity"] + ) + for candidate in candidates: + candidate["pareto_optimal"] = not any( + other["complexity"] <= candidate["complexity"] + and other["validation_rmse"] <= candidate["validation_rmse"] + and (other["complexity"] < candidate["complexity"] or other["validation_rmse"] < candidate["validation_rmse"]) + for other in candidates + ) + candidates.sort(key=lambda item: (item["selection_score"], item["complexity"])) + selected = candidates[0] + selected_model = self._fit_model( + helper, symbols, allowed, data, target, finite_indices, + selected["numerator_degree"], selected["denominator_degree"], + ) + final = self._score_model( + selected_model, target, eq_y, finite_indices, finite_indices, + show_diagnostics=show_diagnostics, + ) + diagnostics = final["evaluation"]["data_split_results"]["train"].get("diagnostics") + if diagnostics: + for expression, symbol in zip(valid_x, symbols): + values = np.asarray(symbol.eval(data), dtype=float).flatten() + for sample in diagnostics["worst_samples"]: + sample["row"][expression] = float(values[sample["index"]]) + alternatives = [] + for candidate in candidates: + if ( + candidate is selected + or not candidate["pareto_optimal"] + or candidate["validation_rmse"] > selected["validation_rmse"] + 0.05 * target_scale + ): + continue + alternatives.append({ + "formula": candidate["formula"], + "numerator_degree": candidate["numerator_degree"], + "denominator_degree": candidate["denominator_degree"], + "validation_rmse": candidate["validation_rmse"], + "formula_complexity": candidate["complexity"], + }) + if len(alternatives) >= top_k: + break + return final["evaluation"] | { + "analyzed_input_expressions": valid_x, + "data_split_results": final["evaluation"]["data_split_results"] | { + "train": final["evaluation"]["data_split_results"]["train"] | { + "metrics": final["evaluation"]["data_split_results"]["train"]["metrics"] | { + "valid_sample_ratio": final["valid_sample_ratio"], + }, + }, + }, + "selected_polynomial_degrees": { + "numerator_degree": selected["numerator_degree"], + "denominator_degree": selected["denominator_degree"], + }, + "alternatives": alternatives, + "denominator_safety_on_observed_samples": final["denominator_diagnostics"], + "linearized_design_matrix": { + "rows": final["matrix_rows"], + "columns": final["complexity"], + "rank": final["matrix_rank"], + "column_labels": final["matrix_column_labels"], + }, + "exceptions": exceptions, + } + + def _fit_model(self, helper, symbols, allowed, data, target, fit_indices, p_degree, q_degree): + p_terms = helper.generate_terms(symbols, p_degree, allowed, True) + q_terms = [term for term in helper.generate_terms(symbols, q_degree, allowed, True) if term.to_str() != "1"] + p_matrix = helper._build_design_matrix(data, p_terms, len(target)) + q_matrix = helper._build_design_matrix(data, q_terms, len(target)) if q_terms else np.empty((len(target), 0)) + design = np.column_stack([p_matrix, -target[:, None] * q_matrix]) + fit_indices = np.asarray(fit_indices, dtype=int) + usable = fit_indices[np.all(np.isfinite(design[fit_indices]), axis=1) & np.isfinite(target[fit_indices])] + if len(usable) < design.shape[1]: + raise ValueError(f"need at least {design.shape[1]} finite fitting samples, got {len(usable)}") + coefficients, _, rank, _ = np.linalg.lstsq(design[usable], target[usable], rcond=None) + return { + "p_terms": p_terms, "q_terms": q_terms, "p_matrix": p_matrix, "q_matrix": q_matrix, + "p_coef": coefficients[:len(p_terms)], "q_coef": coefficients[len(p_terms):], + "rank": int(rank), + "rows": int(len(usable)), + "complexity": int(design.shape[1]), + } + + def _score_model( + self, model, target, y_symbol, train_indices, validation_indices, + show_diagnostics: bool = False, + ): + denominator = 1 + model["q_matrix"] @ model["q_coef"] + prediction = np.full_like(target, np.nan, dtype=float) + safe = np.isfinite(denominator) & (np.abs(denominator) > 1e-12) + prediction[safe] = (model["p_matrix"][safe] @ model["p_coef"]) / denominator[safe] + train = np.asarray(train_indices, dtype=int) + validation = np.asarray(validation_indices, dtype=int) + train = train[np.isfinite(prediction[train]) & np.isfinite(target[train])] + validation = validation[np.isfinite(prediction[validation]) & np.isfinite(target[validation])] + if not len(train) or not len(validation): + raise ValueError("model has no finite train or validation predictions") + numerator_parts = [ + f"({float(coef):.12g}) * ({term.to_str()})" + for coef, term in zip(model["p_coef"], model["p_terms"]) if coef != 0 + ] + numerator = " + ".join(numerator_parts) if numerator_parts else "0" + denominator_formula = "1" + "".join( + f" + ({float(coef):.12g}) * ({term.to_str()})" + for coef, term in zip(model["q_coef"], model["q_terms"]) if coef != 0 + ) + denominator_expression = self.parse_formula(denominator_formula).to_str() + target_label = y_symbol.to_str() + + def factor_label(expression: str) -> str: + return expression if expression.isidentifier() else f"({expression})" + + matrix_column_labels = [term.to_str() for term in model["p_terms"]] + [ + f"-{factor_label(target_label)}*{factor_label(term.to_str())}" + for term in model["q_terms"] + ] + formula = f"({numerator}) / ({denominator_formula})" + formula_symbol = self.parse_formula(formula) + finite_denominator = denominator[np.isfinite(denominator)] + abs_den = np.abs(finite_denominator) + denominator_min = float(np.min(finite_denominator)) if finite_denominator.size else float("nan") + denominator_max = float(np.max(finite_denominator)) if finite_denominator.size else float("nan") + thresholds = (1e-8, 1e-6, 1e-4, 1e-2) + validation_metrics = self.calculate_metrics( + formula_symbol, target[validation], prediction[validation] + ) + validation_evaluation = self.evaluate( + f=formula_symbol, y=y_symbol, + show_diagnostics=show_diagnostics, + ) + return { + "formula": formula, + "validation_rmse": validation_metrics["rmse"], + "evaluation": validation_evaluation, + "complexity": model["complexity"], "matrix_rank": model["rank"], + "matrix_rows": model["rows"], + "matrix_column_labels": matrix_column_labels, + "valid_sample_ratio": float(np.mean(np.isfinite(prediction))), + "denominator_diagnostics": { + "formula": denominator_expression, + "minimum": denominator_min, + "maximum": denominator_max, + "crosses_zero": bool(denominator_min <= 0 <= denominator_max), + "finite_samples": int(finite_denominator.size), + "total_samples": int(denominator.size), + "near_zero_counts": { + threshold: int(np.count_nonzero(abs_den < threshold)) + for threshold in thresholds + }, + }, + } + + @classmethod + def format_result_dict(cls, result: Dict[str, Any]) -> str: + """Format a tool result for the language model. + + Args: + result: Result mapping to format or update. + + Returns: + str: The operation result. + """ + lines = [cls.format_evaluation_result(result, title="Best fitted rational formula")] + if result["alternatives"]: + lines.append("Simpler non-dominated alternatives (validation error versus complexity):") + for alternative in result["alternatives"]: + lines.append( + f" - {alternative['formula']} | validation RMSE=" + f"{alternative['validation_rmse']:.6g}, formula complexity=" + f"{alternative['formula_complexity']}." + ) + exception_lines = [] + matrix = result["linearized_design_matrix"] + if matrix["rank"] < matrix["columns"]: + labels = ", ".join(matrix["column_labels"]) + exception_lines.extend([ + (1, "Linearized design matrix is rank deficient."), + (2, f"Rank[{labels}] = {matrix['rank']} < {matrix['columns']}."), + ]) + denominator = result["denominator_safety_on_observed_samples"] + if denominator["crosses_zero"]: + minimum = f"{denominator['minimum']:#.3g}".removesuffix(".") + maximum = f"{denominator['maximum']:#.3g}".removesuffix(".") + exception_lines.append( + (1, f"Denominator ({denominator['formula']}) crosses or reaches zero " + f"on training samples: range=[{minimum}, {maximum}].") + ) + n_finite = denominator["finite_samples"] + for threshold, count in denominator["near_zero_counts"].items(): + fraction = count / n_finite if n_finite else float("nan") + displayed_percent = f"{100 * fraction:#.3g}".removesuffix(".") + threshold_label = f"1e-{int(round(-np.log10(threshold)))}" + exception_lines.append( + (2, f"fraction(|denominator| < {threshold_label})=" + f"{count}/{n_finite} ({displayed_percent}%).") + ) + exception_lines.extend((1, message) for message in result["exceptions"]) + if exception_lines: + lines.append("Exception:") + lines.extend(f"{' ' * depth}{message}" for depth, message in exception_lines) + return "\n".join(lines) diff --git a/src/sr_harness/tools/read_pdf.py b/src/sr_harness/tools/read_pdf.py new file mode 100644 index 0000000000000000000000000000000000000000..172f194e15de6a14afc5ab6c475ced5505bce36d --- /dev/null +++ b/src/sr_harness/tools/read_pdf.py @@ -0,0 +1,108 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""Bounded PDF text extraction from workspace files or public URLs.""" + +from __future__ import annotations + +import ipaddress +import socket +from io import BytesIO +from typing import Any, Dict +from urllib.parse import urlparse + +import requests + +from .base_tool import BaseTool, ToolMetadata + +MAX_DOWNLOAD_BYTES = 25 * 1024 * 1024 + + +def _validate_public_url(url: str) -> None: + parsed = urlparse(url) + if parsed.scheme not in {"http", "https"} or not parsed.hostname: + raise ValueError("Only absolute http(s) URLs are supported.") + for info in socket.getaddrinfo( + parsed.hostname, + parsed.port or 443, + type=socket.SOCK_STREAM, + ): + if not ipaddress.ip_address(info[4][0]).is_global: + raise ValueError("Refusing to access a non-public network address.") + + +@BaseTool.register("read_pdf") +class PDFReadTool(BaseTool): + """Implementation of the p d f read tool.""" + + metadata = ToolMetadata(name="read_pdf") + + def execute(self, source: str, start_page: int = 1, max_pages: int = 10) -> Dict[str, Any]: + """Extract text from selected pages of a local or public PDF. + + Args: + source: Local PDF path or an absolute public http(s) URL. + start_page: First page to read, one-indexed. + max_pages: Maximum pages to extract, between 1 and 50. + """ + start_page = max(1, int(start_page)) + max_pages = max(1, min(int(max_pages), 50)) + raw = self._load(source) + try: + from pypdf import PdfReader + except ImportError as exc: + raise RuntimeError("PDF support requires: pip install -e '.[tools]'") from exc + reader = PdfReader(BytesIO(raw)) + begin = start_page - 1 + end = min(len(reader.pages), begin + max_pages) + if begin >= len(reader.pages): + raise ValueError(f"start_page exceeds PDF page count ({len(reader.pages)}).") + pages = [ + {"page": i + 1, "text": reader.pages[i].extract_text() or ""} for i in range(begin, end) + ] + return {"source": source, "page_count": len(reader.pages), "pages": pages} + + def _load(self, source: str) -> bytes: + if source.startswith(("http://", "https://")): + _validate_public_url(source) + response = requests.get( + source, + timeout=30, + stream=True, + headers={"User-Agent": "SRAgent/1.0"}, + ) + response.raise_for_status() + data = bytearray() + for chunk in response.iter_content(64 * 1024): + data.extend(chunk) + if len(data) > MAX_DOWNLOAD_BYTES: + raise ValueError("PDF exceeds the 25 MiB download limit.") + return bytes(data) + with self.context.workspace.safe_open(source, "rb") as stream: + raw = stream.read(MAX_DOWNLOAD_BYTES + 1) + if len(raw) > MAX_DOWNLOAD_BYTES: + raise ValueError("PDF exceeds the 25 MiB read limit.") + return raw + + @classmethod + def format_result_dict(cls, result: Dict[str, Any]) -> str: + """Format a tool result for the language model. + + Args: + result: Result mapping to format or update. + + Returns: + str: The operation result. + """ + return "\n\n".join(f"## Page {page['page']}\n{page['text']}" for page in result["pages"]) + + +""" +Real invocation and selected output captured from the public EIC paper: + +>>> PDFReadTool().execute( +... "https://arxiv.org/pdf/2509.21780", start_page=1, max_pages=1 +... ) +{'source': 'https://arxiv.org/pdf/2509.21780', 'page_count': 29, + 'pages': [{'page': 1, + 'text': 'BEYOND ACCURACY AND COMPLEXITY: THE EFFECTIVE ' + 'INFORMATION CRITERION FOR STRUCTURALLY STABLE ...'}]} +""" diff --git a/src/sr_harness/tools/read_skill.py b/src/sr_harness/tools/read_skill.py new file mode 100644 index 0000000000000000000000000000000000000000..2a7e7601bbe43d45192174ab7b1f38458e287652 --- /dev/null +++ b/src/sr_harness/tools/read_skill.py @@ -0,0 +1,119 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +from typing import Any, Dict +from dataclasses import replace +from xml.sax.saxutils import escape +from ..skills import Skill, SkillManager +from ..core import AgentContext +from .base_tool import BaseTool, ToolMetadata + + +def _format_description(skills: Dict[str, Skill]) -> str: + skill_blocks = [] + for skill in skills.values(): + skill_blocks.append( + f" \n" + f" {escape(skill.name)}\n" + f" \n" + f" {escape(skill.description)}\n" + f" \n" + f" " + ) + return ( + "Read the content of a skill by its name.\n\n" + "Skills are reusable human-written instructions. Use this tool when the " + "current task matches one of the skill descriptions below.\n\n" + "Available skills:\n\n" + "\n" + "\n\n".join(skill_blocks) + "\n" + ) + + +@BaseTool.register("read_skill") +class ReadSkill(BaseTool): + """Implementation of the read skill.""" + + default_skill_manager = SkillManager() + metadata = ToolMetadata( + name="read_skill", + description=_format_description(default_skill_manager.load_skills()), + ) + + def __init__(self, context: AgentContext | None = None) -> None: + super().__init__(context=context) + if hasattr(self.context.args, "skill_manager"): + self.skill_manager = self.context.args.skill_manager + if not isinstance(self.skill_manager, SkillManager): + raise TypeError("context.args.skill_manager must be a SkillManager") + else: + self.skill_manager = self.default_skill_manager + enabled = getattr(self.context.args, "enabled_skills", None) + skills = self.skill_manager.load_skills() + self.enabled_skills = set(enabled) if enabled is not None else set(skills) + description = _format_description({ + name: skill for name, skill in skills.items() if name in self.enabled_skills + }) + self.metadata = replace(type(self).metadata, description=description) + + def execute( + self, + name: str = "", + file_path: str = "", + show_tree: bool = False, + query: str = "", + ) -> Dict[str, Any]: + """Inspect a skill's instructions, directory structure, or a file. + + Args: + name: The exact skill name to inspect. Leave empty to search by query. + file_path: Optional path relative to the skill directory, such as + ``tool.py`` or ``references/example.md``. Empty reads SKILL.md. + show_tree: Whether to include all files and subdirectories in the skill. + query: Task description used to recommend skills when name is empty. + """ + if not name.strip(): + if not query.strip(): + raise ValueError("Provide either an exact skill name or a search query.") + matches = [ + skill for skill in self.skill_manager.search_skills(query) + if skill.name in self.enabled_skills + ][:5] + return { + "content": "Recommended skills:\n" + "\n".join( + f"- {skill.name}: {skill.description}" for skill in matches + ), + "matches": [skill.name for skill in matches], + } + if name not in self.skill_manager.load_skills(): + self.skill_manager.get_skill(name) + if name not in self.enabled_skills: + raise ValueError(f"Skill '{name}' is not enabled for this Agent.") + skill = self.skill_manager.get_skill(name) + result: dict[str, Any] = {} + if file_path.strip(): + relative_path = file_path.strip() + file_content = self.skill_manager.read_skill(name, relative_path) + result.update(file_path=relative_path, file_content=file_content) + result["content"] = ( + f'\n' + f"{file_content}\n" + ) + else: + content = self.skill_manager.read_skill(name) + result["content"] = f'\n{content}\n' + if show_tree: + result["tree"] = self.skill_manager.get_skill_tree(name) + return result + + @classmethod + def format_result_dict(cls, result: Dict[str, Any]) -> str: + """Format a tool result for the language model. + + Args: + result: Result mapping to format or update. + + Returns: + str: The operation result. + """ + text = [result["content"]] + if "tree" in result: + text.extend(["", "Skill directory tree:", *[f"- {path}" for path in result["tree"]]]) + return "\n".join(text) diff --git a/src/sr_harness/tools/read_source.py b/src/sr_harness/tools/read_source.py new file mode 100644 index 0000000000000000000000000000000000000000..100eb771036bac8d8455c5349becb7d2b801df25 --- /dev/null +++ b/src/sr_harness/tools/read_source.py @@ -0,0 +1,209 @@ +"""Read files, definitions, and references from installed SRHarness source.""" +from __future__ import annotations + +import ast +from pathlib import Path +from typing import Any + +from .base_tool import BaseTool +from ..core import ToolMetadata + +_SOURCE_ROOT = Path(__file__).resolve().parents[2] +_ALLOWED_SUFFIXES = {".py", ".md", ".html", ".json", ".toml", ".yaml", ".yml"} +_MAX_SOURCE_SIZE = 200_000 +_MAX_SYMBOL_RESULTS = 200 + + +def _resolve(path: str | None) -> Path: + path = path or "." + if path == "src": + path = "." + elif path.startswith("src/"): + path = path[4:] + target = (_SOURCE_ROOT / path).resolve() + if target != _SOURCE_ROOT and _SOURCE_ROOT not in target.parents: + raise ValueError("path must remain inside the installed SRHarness source tree") + return target + + +def _python_files(target: Path) -> list[Path]: + if target.is_file(): + if target.suffix != ".py": + raise ValueError("symbol queries require a Python file or directory") + return [target] + return [item for item in sorted(target.rglob("*.py")) if "__pycache__" not in item.parts] + + +def _matches_symbol(candidate: str, query: str) -> bool: + return candidate == query or candidate.endswith("." + query) + + +def _attribute_name(node: ast.AST) -> str | None: + parts = [] + while isinstance(node, ast.Attribute): + parts.append(node.attr) + node = node.value + if isinstance(node, ast.Name): + parts.append(node.id) + return ".".join(reversed(parts)) + return None + + +def _symbol_results(path: Path, source: str, symbol: str, *, implementation: bool, references: bool) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + try: + tree = ast.parse(source) + except SyntaxError: + return [], [] + lines = source.splitlines() + relative = str(path.relative_to(_SOURCE_ROOT)) + definitions: list[dict[str, Any]] = [] + usages: list[dict[str, Any]] = [] + + class Visitor(ast.NodeVisitor): + def __init__(self): + self.scope: list[str] = [] + + def _definition(self, node): + qualified = ".".join([*self.scope, node.name]) + if implementation and _matches_symbol(qualified, symbol): + definitions.append({ + "path": relative, "line": node.lineno, "qualified_name": qualified, + "source": "\n".join(lines[node.lineno - 1:node.end_lineno]), + }) + self.scope.append(node.name) + self.generic_visit(node) + self.scope.pop() + + visit_ClassDef = _definition + visit_FunctionDef = _definition + visit_AsyncFunctionDef = _definition + + def visit_Attribute(self, node): + name = _attribute_name(node) + if references and name and _matches_symbol(name, symbol): + usages.append({ + "path": relative, "line": node.lineno, "column": node.col_offset, + "reference": name, "source": lines[node.lineno - 1].strip(), + }) + self.generic_visit(node) + + def visit_Name(self, node): + if references and "." not in symbol and node.id == symbol: + usages.append({ + "path": relative, "line": node.lineno, "column": node.col_offset, + "reference": node.id, "source": lines[node.lineno - 1].strip(), + }) + + def visit_ImportFrom(self, node): + if references: + for alias in node.names: + imported = f"{node.module}.{alias.name}" if node.module else alias.name + if _matches_symbol(imported, symbol) or _matches_symbol(alias.name, symbol): + usages.append({ + "path": relative, "line": node.lineno, "column": node.col_offset, + "reference": imported, "source": lines[node.lineno - 1].strip(), + }) + self.generic_visit(node) + + Visitor().visit(tree) + unique = {(item["path"], item["line"], item["column"], item["reference"]): item for item in usages} + return definitions, list(unique.values()) + + +@BaseTool.register("read_source") +class ReadSourceTool(BaseTool): + """Inspect installed source files and locate symbol definitions or references.""" + + metadata = ToolMetadata( + name="read_source", + description=( + "List a directory, read a source file, or query a Python symbol's implementation " + "and references. Paths are relative to src; omit path to search all SRHarness source." + ), + parameters={ + "type": "object", + "properties": { + "path": {"type": "string", "description": "Optional path relative to src."}, + "symbol": {"type": "string", "description": "Optional symbol such as DefaultEvaluator.evaluate."}, + "include_implementation": {"type": "boolean", "description": "Return matching definitions; defaults to true."}, + "include_references": {"type": "boolean", "description": "Return matching usages; defaults to false."}, + }, + "additionalProperties": False, + }, + ) + + def execute(self, path: str | None = None, symbol: str | None = None, include_implementation: bool = True, include_references: bool = False) -> dict[str, Any]: + """Read a source path or locate a Python symbol. + + Args: + path: File or directory relative to the installed ``src`` tree. + symbol: Qualified or unqualified Python symbol to locate. + include_implementation: Whether symbol queries return definitions. + include_references: Whether symbol queries return references. + + Returns: + A directory listing, file source, or symbol-query result. + """ + target = _resolve(path) + if not target.exists(): + raise ValueError(f"Source path does not exist: {path}") + if symbol: + if not include_implementation and not include_references: + raise ValueError("a symbol query must request implementation, references, or both") + definitions, references = [], [] + for item in _python_files(target): + source = item.read_text(encoding="utf-8") + if len(source) > _MAX_SOURCE_SIZE: + continue + found_definitions, found_references = _symbol_results( + item, source, symbol, + implementation=include_implementation, + references=include_references, + ) + definitions.extend(found_definitions) + references.extend(found_references) + if len(definitions) + len(references) >= _MAX_SYMBOL_RESULTS: + break + result = { + "path": str(target.relative_to(_SOURCE_ROOT)), "type": "symbol", "symbol": symbol, + "definitions": definitions[:_MAX_SYMBOL_RESULTS], + "references": references[:max(0, _MAX_SYMBOL_RESULTS - len(definitions))], + } + if len(result["definitions"]) == 1: + result["source"] = result["definitions"][0]["source"] + return result + if target.is_dir(): + entries = [ + str(item.relative_to(_SOURCE_ROOT)) for item in sorted(target.rglob("*")) + if item.is_file() and item.suffix in _ALLOWED_SUFFIXES and "__pycache__" not in item.parts + ] + return {"path": str(target.relative_to(_SOURCE_ROOT)), "type": "directory", "entries": entries} + if target.suffix not in _ALLOWED_SUFFIXES: + raise ValueError(f"Unsupported source-file type: {target.suffix}") + source = target.read_text(encoding="utf-8") + if len(source) > _MAX_SOURCE_SIZE: + raise ValueError(f"Source file exceeds {_MAX_SOURCE_SIZE} characters") + return {"path": str(target.relative_to(_SOURCE_ROOT)), "type": "file", "source": source} + + @classmethod + def format_result_dict(cls, result: dict[str, Any]) -> str: + """Format a source inspection result for a language model. + + Args: + result: Structured result returned by :meth:`execute`. + + Returns: + Human-readable source text or query matches. + """ + if result["type"] == "directory": + return "Source tree: " + result["path"] + "\n" + "\n".join(result["entries"]) + if result["type"] == "file": + return f"Source: {result['path']}\n```\n{result['source']}\n```" + lines = [f"Symbol: {result['symbol']} (scope: {result['path'] or 'src'})"] + for item in result["definitions"]: + lines.append(f"Implementation: {item['path']}:{item['line']} · {item['qualified_name']}\n```python\n{item['source']}\n```") + for item in result["references"]: + lines.append(f"Reference: {item['path']}:{item['line']} · `{item['source']}`") + if len(lines) == 1: + lines.append("No matching implementation or reference found.") + return "\n".join(lines) diff --git a/src/sr_harness/tools/relationship_analysis.py b/src/sr_harness/tools/relationship_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fe935e0660f0b05311000cc285e5e33331e0d5 --- /dev/null +++ b/src/sr_harness/tools/relationship_analysis.py @@ -0,0 +1,329 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""变量关系、条件分布和一维 collapse 分析工具。""" +import numpy as np +from scipy import stats +from scipy.interpolate import UnivariateSpline +from typing import Any, Dict, List +from .base_tool import BaseTool, ToolMetadata, is_numeric_array + + +@BaseTool.register("relationship_analysis") +class RelationshipAnalysisTool(BaseTool): + """Implementation of the relationship analysis tool.""" + metadata = ToolMetadata("relationship_analysis") + + def execute( + self, + variables: List[str] = None, + y: str = None, + n_bins: int = 5, + pairwise: bool = False, + binning: str = "quantile", + n_folds: int = 5, + collapse_model: str = "bins", + ) -> Dict[str, Any]: + """Analyze feature-target relationships, conditional distributions, and one-dimensional collapse. + + Args: + variables: Variables or expressions to analyze. Use all numeric non-target variables by default. + y: Target variable or expression. Use the formula-discovery target by default. + n_bins: Number of bins for each feature's conditional target summary (2-100). + pairwise: Whether to also return full pairwise Pearson and Spearman matrices. + binning: Binning strategy: "quantile" or "equal_width". + n_folds: Number of disjoint cross-validation folds (2-20). Default: 5. + collapse_model: One-dimensional predictor fitted on each training fold: "bins", "spline", or "isotonic". + """ + data = self.context.data + target_name = (y or self.context.target).strip().strip('"').strip("'") + n_bins = max(2, min(int(n_bins), 100)) + n_folds = max(2, min(int(n_folds), 20)) + if binning not in {"quantile", "equal_width"}: + raise ValueError("binning must be 'quantile' or 'equal_width'") + if collapse_model not in {"bins", "spline", "isotonic"}: + raise ValueError("collapse_model must be 'bins', 'spline', or 'isotonic'") + + target_value = data[target_name] if target_name in data else self.parse_formula(target_name).eval(data) + if not is_numeric_array(target_value): + raise ValueError(f"Target '{target_name}' did not produce numeric values.") + target = np.asarray(target_value, dtype=float).flatten() + variables = variables or [ + name for name, value in data.items() + if name != target_name and is_numeric_array(value) + ] + + arrays = {} + exceptions = [] + for expression in variables: + try: + value = data[expression] if expression in data else self.parse_formula(expression).eval(data) + if not is_numeric_array(value): + raise ValueError("expression did not produce numeric values") + value = np.asarray(value, dtype=float).flatten() + if value.shape != target.shape: + raise ValueError(f"shape {value.shape} does not match target shape {target.shape}") + arrays[expression] = value + except Exception as exc: + exceptions.append(f"Failed to compute '{expression}': {exc}") + + relationships = {} + for name, values in arrays.items(): + try: + relationship, residual = self._analyze_relationship( + values, target, n_bins, binning, n_folds, collapse_model, + ) + + # Compute correlations of other variables with the cross-fitted residual. + if np.any(np.isfinite(residual)): + remaining = [] + for other, other_values in arrays.items(): + if other == name: + continue + pearson, spearman = self.correlation_coefficients(other_values, residual) + strength = max(abs(pearson), abs(spearman)) + if np.isfinite(strength): + remaining.append({ + "variable": other, + "pearson": pearson, + "spearman": spearman, + "strength": strength, + }) + if remaining: + relationship["strongest_residual_association_after_one_variable_fit"] = max( + remaining, key=lambda item: item["strength"] + ) + relationships[name] = relationship + except Exception as exc: + exceptions.append(f"Failed to analyze '{name}': {exc}") + + result = { + "target": target_name, + "relationships": relationships, + "exceptions": exceptions, + "analysis_settings": { + "n_bins": n_bins, + "binning": binning, + "n_folds": n_folds, + "collapse_model": collapse_model, + }, + } + if pairwise: + pairwise_arrays = {name: arrays[name] for name in relationships} + if target_name not in pairwise_arrays: + pairwise_arrays[target_name] = target + names = list(pairwise_arrays) + pearson_matrix, spearman_matrix = [], [] + for left in names: + pearson_row, spearman_row = [], [] + for right in names: + pearson, spearman = self.correlation_coefficients( + pairwise_arrays[left], pairwise_arrays[right] + ) + pearson_row.append(pearson) + spearman_row.append(spearman) + pearson_matrix.append(pearson_row) + spearman_matrix.append(spearman_row) + result["pairwise_correlations"] = { + "variables": names, + "pearson": pearson_matrix, + "spearman": spearman_matrix, + } + return result + + @classmethod + def _analyze_relationship( + cls, x, y, n_bins, binning, n_folds, collapse_model, + ): + finite = np.isfinite(x) & np.isfinite(y) + total_count = len(x) + x, y = x[finite], y[finite] + if not len(x): + raise ValueError("no jointly finite samples") + + if np.min(x) == np.max(x): + edges = np.array([x[0], x[0]]) + bin_ids = np.zeros(len(x), dtype=int) + else: + edges = ( + np.unique(np.quantile(x, np.linspace(0, 1, n_bins + 1))) + if binning == "quantile" + else np.linspace(np.min(x), np.max(x), n_bins + 1) + ) + bin_ids = np.clip(np.digitize(x, edges[1:-1]), 0, len(edges) - 2) + + conditional_bins = [] + for index in range(max(1, len(edges) - 1)): + mask = bin_ids == index + if not np.any(mask): + continue + xb, yb = x[mask], y[mask] + y_mean = float(np.mean(yb)) + conditional_bins.append({ + "bin_interval": [float(edges[index]), float(edges[index + 1])], + "upper_inclusive": index == len(edges) - 2, + "x_range": [float(np.min(xb)), float(np.max(xb))], + "sample_count": int(len(yb)), + "y_mean": y_mean, + "y_std": float(np.std(yb)), + "y_range": [float(np.min(yb)), float(np.max(yb))], + }) + + fold_scores = [] + prediction = np.full(len(x), np.nan, dtype=float) + if len(x) >= n_folds and np.var(y) > 0: + folds = np.array_split(np.random.default_rng(0).permutation(len(x)), n_folds) + for test in folds: + train_mask = np.ones(len(x), dtype=bool) + train_mask[test] = False + train = np.flatnonzero(train_mask) + if len(train) < 4 or len(test) < 2: + continue + try: + predicted = cls._fit_predict_1d( + x[train], y[train], x[test], n_bins, binning, collapse_model + ) + baseline = float(np.sum((y[test] - np.mean(y[train])) ** 2)) + if baseline > 0 and np.all(np.isfinite(predicted)): + prediction[test] = predicted + fold_scores.append(float( + 1 - np.sum((y[test] - predicted) ** 2) / baseline + )) + except Exception: + continue + + pearson, spearman = cls.correlation_coefficients(x, y) + residual = np.full(total_count, np.nan, dtype=float) + residual[finite] = y - prediction + return { + "pearson": pearson, + "spearman": spearman, + "jointly_finite_sample_count": len(x), + "total_sample_count": total_count, + "observed_variable_range": [float(np.min(x)), float(np.max(x))], + "observed_target_range": [float(np.min(y)), float(np.max(y))], + "one_variable_test_r2_mean": float(np.mean(fold_scores)) if fold_scores else float("nan"), + "one_variable_test_r2_std": float(np.std(fold_scores)) if fold_scores else float("nan"), + "one_variable_test_success_folds": len(fold_scores), + "conditional_bins": conditional_bins, + }, residual + + @staticmethod + def _fit_predict_1d(train_x, train_y, test_x, n_bins, binning, model): + order = np.argsort(train_x) + x, y = train_x[order], train_y[order] + if model == "isotonic": + from sklearn.isotonic import IsotonicRegression + increasing = bool(stats.spearmanr(x, y).statistic >= 0) + return IsotonicRegression(increasing=increasing, out_of_bounds="clip").fit(x, y).predict(test_x) + if model == "spline": + unique_x, inverse = np.unique(x, return_inverse=True) + means = np.bincount(inverse, weights=y) / np.bincount(inverse) + if len(unique_x) >= 4: + smoothing = max(len(unique_x) * float(np.var(means)) * 1e-3, 0.0) + return np.asarray(UnivariateSpline( + unique_x, means, k=min(3, len(unique_x) - 1), s=smoothing, ext=3 + )(test_x), dtype=float) + if np.min(x) == np.max(x): + return np.full_like(test_x, np.mean(y), dtype=float) + edges = ( + np.unique(np.quantile(x, np.linspace(0, 1, n_bins + 1))) + if binning == "quantile" + else np.linspace(np.min(x), np.max(x), n_bins + 1) + ) + ids = np.clip(np.digitize(x, edges[1:-1]), 0, len(edges) - 2) + global_mean = float(np.mean(y)) + means = np.asarray([ + np.mean(y[ids == index]) if np.any(ids == index) else global_mean + for index in range(len(edges) - 1) + ]) + test_ids = np.clip(np.digitize(test_x, edges[1:-1]), 0, len(means) - 1) + return means[test_ids] + + @classmethod + def format_result_dict(cls, result: Dict[str, Any]) -> str: + """Format a tool result for the language model. + + Args: + result: Result mapping to format or update. + + Returns: + str: The operation result. + """ + def number(value): + if value == 0: + return "0" + return f"{value:#.3g}".removesuffix(".") + + def interval(values): + return f"[{number(values[0])}, {number(values[1])}]" + + lines = [] + settings = result["analysis_settings"] + predictor = { + "bins": ( + f"Randomly split data into n_folds={settings['n_folds']} parts, " + f"use {settings['n_folds'] - 1} parts for binning, and predict each " + "held-out value using the bin mean" + ), + "spline": ( + f"Randomly split data into n_folds={settings['n_folds']} parts, " + f"use {settings['n_folds'] - 1} parts to fit a univariate smoothing " + "spline, and predict the remaining part" + ), + "isotonic": ( + f"Randomly split data into n_folds={settings['n_folds']} parts, " + f"use {settings['n_folds'] - 1} parts to fit isotonic regression, " + "and predict the remaining part" + ), + }[settings["collapse_model"]] + duplicate_note = "; duplicate quantile cut points removed" if settings["binning"] == "quantile" else "" + for name, relationship in result["relationships"].items(): + lines.extend([ + f"{name} vs {result['target']} (Only jointly finite feature/target samples are used, " + f"{relationship['jointly_finite_sample_count']}/{relationship['total_sample_count']} finite samples):", + f" Pearson linear correlation={number(relationship['pearson'])};", + f" Spearman rank correlation={number(relationship['spearman'])};", + f" {name} range={interval(relationship['observed_variable_range'])};", + f" {result['target']} range={interval(relationship['observed_target_range'])};", + f" Binning analysis (n_bins={settings['n_bins']}, " + f"method={settings['binning']}{duplicate_note}):", + f" (Range of {name} | samples | {result['target']} mean | " + f"{result['target']} std | {result['target']} range)", + ]) + for item in relationship["conditional_bins"]: + lower, upper = item["bin_interval"] + if lower == upper: + condition = f"{name} = {number(lower)}" + else: + sign = "<=" if item["upper_inclusive"] else "<" + condition = f"{number(lower)} <= {name} {sign} {number(upper)}" + lines.extend([ + f" {condition} | {item['sample_count']} | " + f"{number(item['y_mean'])} | {number(item['y_std'])} | " + f"{interval(item['y_range'])}", + ]) + lines.extend([ + f" One-variable held-out experiment ({predictor}):", + f" R2 (mean)={number(relationship['one_variable_test_r2_mean'])}", + f" R2 (std)={number(relationship['one_variable_test_r2_std'])}", + f" Success folds={relationship['one_variable_test_success_folds']}/{settings['n_folds']}", + ]) + if strongest := relationship.get("strongest_residual_association_after_one_variable_fit"): + lines.extend([ + " Largest residual correlation among other analyzed variables " + "(criterion=max(|Pearson|, |Spearman|)):", + f" variable={strongest['variable']}", + f" Pearson={number(strongest['pearson'])}", + f" Spearman={number(strongest['spearman'])}", + ]) + if matrix := result.get("pairwise_correlations"): + lines.append("Pairwise correlations (Pearson linear; Spearman rank; pairwise finite samples):") + for left in range(len(matrix["variables"])): + for right in range(left + 1, len(matrix["variables"])): + lines.append( + f" {matrix['variables'][left]} ↔ {matrix['variables'][right]}: " + f"Pearson={number(matrix['pearson'][left][right])}, " + f"Spearman={number(matrix['spearman'][left][right])}." + ) + if result["exceptions"]: + lines.append("Exceptions:\n" + "\n".join(result["exceptions"])) + return "\n".join(lines) diff --git a/src/sr_harness/tools/sandboxed_custom_tool.py b/src/sr_harness/tools/sandboxed_custom_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..77d87f4952deabf937e945c0536921ef9776a0f3 --- /dev/null +++ b/src/sr_harness/tools/sandboxed_custom_tool.py @@ -0,0 +1,163 @@ +"""Sandbox-backed proxies for user-authored ``BaseTool`` implementations.""" + +from __future__ import annotations + +import time +from functools import lru_cache +from pathlib import Path +from typing import Any + +from ..core import AgentContext, ToolCallResult, ToolMetadata +from ..runtime.sandbox import ( + SandboxExecutionError, + _context_array_snapshot, + _run_sandbox_protocol, +) +from ..runtime.sandbox_context import sandbox_arguments +from .base_tool import BaseTool + + +def _context_payload(context: AgentContext) -> dict[str, Any]: + """Serialize only data-independent context metadata for a sandbox worker.""" + evaluator = context.evaluator + custom = getattr(type(evaluator), "CUSTOM_EVALUATOR", None) + evaluator_payload = ( + { + "kind": "custom", + "source": custom["source"], + "filename": Path(custom.get("file") or "custom_evaluator.py").name, + } + if isinstance(custom, dict) and isinstance(custom.get("source"), str) + else { + "kind": "graph" if type(evaluator).__name__ == "GraphEvaluator" else "default" + } + ) + return { + "args": sandbox_arguments(context.args), + "target": context.target, + "variable_descriptions": context.variable_descriptions, + "variable_axes": {name: list(axes) for name, axes in context.variable_axes.items()}, + "variable_structures": context.variable_structures, + "relation_names": sorted(context.relation_names), + "num_nodes": context.num_nodes, + "evaluator": evaluator_payload, + } + + +@lru_cache(maxsize=256) +def _inspect_source(source: str, filename: str) -> dict[str, Any]: + """Inspect immutable tool source inside the OS sandbox.""" + result = _run_sandbox_protocol( + operation="custom-tool", + request={"action": "inspect", "source": source, "filename": filename}, + timeout_seconds=30, + memory_limit_mb=2048, + output_limit_bytes=64 * 1024, + ) + return dict(result.payload) + + +class SandboxedCustomTool(BaseTool): + """Proxy a user-authored tool into a fresh confined worker per invocation.""" + + metadata = ToolMetadata( + name="_sandboxed_custom_tool_proxy", + description="Internal sandbox proxy for a user-authored tool.", + parameters={}, + ) + + SANDBOX_SOURCE: str + SANDBOX_FILENAME: str + source_path: Path + + def _sandbox_call(self, params: dict[str, Any]) -> dict[str, Any]: + result = _run_sandbox_protocol( + operation="custom-tool", + request={ + "action": "execute", + "source": self.SANDBOX_SOURCE, + "filename": self.SANDBOX_FILENAME, + "params": params, + "context": _context_payload(self.context), + }, + array_snapshot=_context_array_snapshot(self.context), + timeout_seconds=120, + memory_limit_mb=4096, + output_limit_bytes=self.MAX_RESULT_STR_LENGTH, + interruption_event=getattr(self, "cancel_event", None), + ) + return dict(result.payload) + + def execute(self, **kwargs: Any) -> dict[str, Any]: + """Execute the custom tool in the OS sandbox.""" + return dict(self._sandbox_call(kwargs)["result"]) + + def __call__(self, *args: Any, **kwargs: Any) -> ToolCallResult: + """Execute and format the tool without importing its code in this process.""" + if args: + raise TypeError("Sandboxed custom tools accept keyword arguments only") + started = time.time() + try: + payload = self._sandbox_call(kwargs) + result = payload["result"] + if not isinstance(result, dict): + raise TypeError("Custom tool execute() must return a dictionary") + result_str = self.truncate_result_str(str(payload["result_str"])) + return ToolCallResult( + ok=True, + result=result, + result_str=result_str, + meta_data={ + "timestamp": started, + "execution_time": time.time() - started, + "tool": self.metadata.name, + }, + ) + except Exception as exc: + error = self.truncate_result_str( + f"Error executing {self.metadata.name}:\n {type(exc).__name__}: {exc}" + ) + return ToolCallResult( + ok=False, + result={"error": error}, + result_str=error, + meta_data={ + "timestamp": started, + "execution_time": time.time() - started, + "tool": self.metadata.name, + }, + ) + + +def create_sandboxed_custom_tool(source: str, file: Path) -> type[BaseTool]: + """Validate custom tool source and return a metadata-only proxy class.""" + try: + metadata = _inspect_source(source, file.name) + except SandboxExecutionError as exc: + message = str(exc) + if any( + marker in message + for marker in ( + "Custom tool must define exactly one", + "Custom tools must not use @BaseTool.register", + "Custom tool metadata.", + ) + ): + raise ValueError(message.split("\nTraceback", 1)[0]) from None + raise + tool_metadata = ToolMetadata( + name=str(metadata["tool_name"]), + description=str(metadata["description"]), + parameters=dict(metadata["parameters"]), + ) + return type( + str(metadata["class_name"]), + (SandboxedCustomTool,), + { + "__module__": __name__, + "metadata": tool_metadata, + "source_path": file.resolve(), + "SANDBOX_SOURCE": source, + "SANDBOX_FILENAME": file.name, + }, + ) diff --git a/src/sr_harness/tools/sr4mdl.py b/src/sr_harness/tools/sr4mdl.py new file mode 100644 index 0000000000000000000000000000000000000000..78a547c7a2111c58135db643cea577fa883d38dc --- /dev/null +++ b/src/sr_harness/tools/sr4mdl.py @@ -0,0 +1,346 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""SR4MDL/MDLformer-guided symbolic-regression search tool.""" +from __future__ import annotations + +import os +import re +import sys +import time +from pathlib import Path +from types import SimpleNamespace +from typing import Any, Dict, List + +import numpy as np + +from .base_tool import BaseTool, ToolMetadata, is_numeric_array + + +@BaseTool.register("sr4mdl") +class SR4MDLTool(BaseTool): + """Implementation of the s r4 m d l tool.""" + metadata = ToolMetadata(name="sr4mdl") + REPOSITORY = "https://github.com/tsinghua-fib-lab/SR4MDL" + BINARY_OPERATORS = { + "+": "Add", + "-": "Sub", + "*": "Mul", + "/": "Div", + } + UNARY_OPERATORS = { + "sqrt": "Sqrt", + "sin": "Sin", + "cos": "Cos", + "neg": "Neg", + "inv": "Inv", + "log": "Log", + "exp": "Exp", + "square": "Pow2", + "cube": "Pow3", + } + + def execute( + self, + binary_operators: List[str], + unary_operators: List[str], + x: List[str] = None, + y: str = None, + timeout: int = 60, + maxsize: int = 30, + max_samples: int = 500, + n_iter: int = 100, + show_diagnostics: bool = True, + ) -> Dict[str, Any]: + """Run MDLformer-guided Monte Carlo tree search on the current data. + + Like `call_pysr`, this tool constructs a regression dataset from agent-visible + expressions and returns an evaluated candidate formula. SR4MDL must be cloned into an + isolated directory, `SR4MDL_HOME` must point to it, and `SR4MDL_CHECKPOINT` must point + to its trained checkpoint (default: `$SR4MDL_HOME/weights/checkpoint.pth`). + + Args: + binary_operators: Binary search operators chosen from "+", "-", "*", "/". + unary_operators: Unary operators chosen from "sqrt", "sin", "cos", "neg", + "inv", "log", "exp", "square", "cube". + x: Input feature names or expressions. Defaults to numeric non-target columns. + y: Target name or expression. Defaults to the configured target. + timeout: Soft wall-time budget in seconds, checked whenever a new best tree appears. + maxsize: Maximum expression-tree length, between 5 and 100. + max_samples: Maximum fitting samples, between 20 and 5000. + n_iter: Maximum MCTS iterations, between 1 and 10000. + show_diagnostics: Whether final metrics include compact residual diagnostics. + """ + status = self.backend_status() + if not status["installed"]: + raise RuntimeError( + "SR4MDL is not configured: clone the repository and set SR4MDL_HOME." + ) + checkpoint = Path( + os.environ.get( + "SR4MDL_CHECKPOINT", + Path(status["root"]) / "weights" / "checkpoint.pth", + ) + ).expanduser().resolve() + if not checkpoint.is_file(): + raise RuntimeError( + "SR4MDL checkpoint not found. Set SR4MDL_CHECKPOINT to checkpoint.pth." + ) + + unary_operators = ["log" if name == "ln" else name for name in unary_operators] + unknown_binary = sorted(set(binary_operators) - self.BINARY_OPERATORS.keys()) + unknown_unary = sorted(set(unary_operators) - self.UNARY_OPERATORS.keys()) + if unknown_binary or unknown_unary: + raise ValueError( + f"Unsupported operators: binary={unknown_binary}, unary={unknown_unary}" + ) + timeout = max(10, min(int(timeout), 600)) + maxsize = max(5, min(int(maxsize), 100)) + max_samples = max(20, min(int(max_samples), 5000)) + n_iter = max(1, min(int(n_iter), 10000)) + + data = self.context.data + y = (y or self.context.target).strip().strip('"').strip("'") + x = x or [ + name for name, values in data.items() + if name != y and is_numeric_array(values) + ] + target_formula = self.parse_formula(y) + target_values = np.asarray(target_formula.eval(data)).flatten() + if not is_numeric_array(target_values): + raise ValueError(f"Target {y!r} did not produce numeric values.") + + internal_data = {} + original_expressions = [] + for index, expression in enumerate(x, start=1): + values = np.asarray(self.parse_formula(expression).eval(data)).flatten() + if not is_numeric_array(values): + raise ValueError(f"Feature {expression!r} did not produce numeric values.") + if values.shape != target_values.shape: + raise ValueError( + f"Feature {expression!r} shape {values.shape} does not match " + f"target shape {target_values.shape}." + ) + internal_data[f"x{index}"] = values + original_expressions.append(expression) + if not internal_data: + raise ValueError("No valid input variables available for fitting.") + + if len(target_values) > max_samples: + rng = np.random.default_rng(42) + indices = rng.choice(len(target_values), size=max_samples, replace=False) + internal_data = { + name: values[indices] for name, values in internal_data.items() + } + target_values = target_values[indices] + + formula = self._run_sr4mdl( + root=Path(status["root"]), + checkpoint=checkpoint, + X=internal_data, + y=target_values, + binary_operators=binary_operators, + unary_operators=unary_operators, + timeout=timeout, + maxsize=maxsize, + n_iter=n_iter, + ) + formula = self._restore_feature_names(formula, original_expressions) + evaluation = self.evaluate( + f=self.parse_formula(formula), + y=target_formula, + show_diagnostics=show_diagnostics, + ) + return { + **evaluation, + "method": "SR4MDL-MCTS", + "backend": status, + "config": { + "timeout": timeout, + "maxsize": maxsize, + "max_samples": max_samples, + "n_iter": n_iter, + "binary_operators": binary_operators, + "unary_operators": unary_operators, + }, + } + + def _run_sr4mdl( + self, + *, + root: Path, + checkpoint: Path, + X: Dict[str, np.ndarray], + y: np.ndarray, + binary_operators: List[str], + unary_operators: List[str], + timeout: int, + maxsize: int, + n_iter: int, + ) -> str: + root_text = str(root) + bundled_engine = str(root / "nd2py_package") + if (root / "nd2py_package" / "nd2py").is_dir() and bundled_engine not in sys.path: + sys.path.insert(0, bundled_engine) + if root_text not in sys.path: + sys.path.insert(0, root_text) + try: + import torch + from sr4mdl.env import Tokenizer + from sr4mdl.model import MDLformer + from sr4mdl.search import MCTS4MDL + except ImportError as exc: + raise RuntimeError( + "SR4MDL dependencies are unavailable in this Python environment." + ) from exc + + device = os.environ.get( + "SR4MDL_DEVICE", + "cuda" if torch.cuda.is_available() else "cpu", + ) + state = torch.load(checkpoint, map_location=device, weights_only=False) + args = SimpleNamespace( + dropout=0.0, + d_model=512, + d_input=64, + d_output=512, + n_TE_layers=8, + max_len=maxsize, + max_param=5, + max_var=10, + uniform_sample_number=len(y), + device=device, + use_SENet=True, + use_old_model=False, + ) + tokenizer = Tokenizer(-100, 100, 4, args.max_var) + model = MDLformer(args, state["xy_token_list"]) + model.load(state["xy_encoder"], state["xy_token_list"], strict=True) + model.eval() + estimator = MCTS4MDL( + tokenizer=tokenizer, + model=model, + n_iter=n_iter, + max_len=maxsize, + sample_num=len(y), + binary=[self.BINARY_OPERATORS[name] for name in binary_operators], + unary=[self.UNARY_OPERATORS[name] for name in unary_operators], + leaf=[1.0, 2.0, float(np.pi)], + keep_vars=True, + normalize_y=False, + normalize_all=False, + remove_abnormal=True, + train_eval_split=0.25, + random_state=42, + ) + started = time.monotonic() + + def early_stop(r2, complexity, equation): + del complexity, equation + return r2 > 0.99999 or time.monotonic() - started >= timeout + + estimator.fit(X, y, use_tqdm=False, early_stop=early_stop) + if estimator.eqtree is None: + raise RuntimeError("SR4MDL completed without producing a formula.") + return estimator.eqtree.to_str() + + @staticmethod + def _restore_feature_names( + formula: str, + original_expressions: List[str], + ) -> str: + for index in range(len(original_expressions), 0, -1): + formula = re.sub( + rf"\bx{index}\b", + f"({original_expressions[index - 1]})", + formula, + ) + return formula + + @classmethod + def backend_status(cls) -> Dict[str, Any]: + """Run the ``backend status`` operation. + + Returns: + Dict[str, Any]: The operation result. + """ + configured = os.environ.get("SR4MDL_HOME") + local_root = Path.cwd() / "third-party" / "SR4MDL" + root = ( + Path(configured).expanduser().resolve() + if configured + else local_root.resolve() if (local_root / "regressor.py").is_file() + else None + ) + marker = "regressor.py" + checkpoint = ( + Path(os.environ.get( + "SR4MDL_CHECKPOINT", + root / "weights" / "checkpoint.pth", + )) + if root else None + ) + return { + "backend": "sr4mdl", + "repository": cls.REPOSITORY, + "environment_variable": "SR4MDL_HOME", + "root": str(root) if root else None, + "installed": bool(root and (root / marker).is_file()), + "checkpoint": str(checkpoint) if checkpoint else None, + "checkpoint_available": bool(checkpoint and checkpoint.is_file()), + "marker": marker, + } + + @classmethod + def format_result_dict(cls, result: Dict[str, Any]) -> str: + """Format a tool result for the language model. + + Args: + result: Result mapping to format or update. + + Returns: + str: The operation result. + """ + return BaseTool.format_result_dict(result) + + @classmethod + def get_doc(cls) -> dict[str, str]: + """Return documentation exposed as a runtime skill. + + Returns: + dict[str, str]: The operation result. + """ + return { + "name": "sr4mdl-search", + "description": ( + "Use SR4MDL/MDLformer-guided search when description length should guide " + "symbolic model selection." + ), + "content": ( + "Call `sr4mdl` with hypothesized binary/unary operators, input expressions, " + "and a target expression, just as for `call_pysr`. SR4MDL runs an actual " + "MDLformer-guided MCTS over the current data; it is not a data-export command. " + "Set `SR4MDL_HOME` and `SR4MDL_CHECKPOINT` before use. Compare returned " + "validation metrics and formula complexity with other search tools.\n\n" + f"Source: {cls.REPOSITORY}" + ), + } + + +""" +Real invocation captured with the official checkpoint and 100 samples of ``y = a + b``: + +>>> SR4MDLTool.backend_status() +{'backend': 'sr4mdl', + 'repository': 'https://github.com/tsinghua-fib-lab/SR4MDL', + 'environment_variable': 'SR4MDL_HOME', 'root': '.../third-party/SR4MDL', + 'installed': True, 'checkpoint': '.../third-party/SR4MDL/weights/checkpoint.pth', + 'checkpoint_available': True, 'marker': 'regressor.py'} + +>>> result = tool.execute( +... binary_operators=["+"], unary_operators=[], x=["a", "b"], y="y", +... timeout=10, maxsize=10, max_samples=100, n_iter=1, +... ) +>>> result["formula"], result["data_split_results"]["train"]["metrics"] +('a + b', {'mse': 0.0, 'rmse': 0.0, 'mae': 0.0, 'mape': 0.0, + 'r2': 1.0, 'aic': -inf, 'bic': -inf, 'pearson_r': 1.0, + 'spearman_r': 1.0, 'complexity': 3}) +""" diff --git a/src/sr_harness/tools/statistics_analysis.py b/src/sr_harness/tools/statistics_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..72680df5a579eed7fd198b938ac7ad06dd51eb76 --- /dev/null +++ b/src/sr_harness/tools/statistics_analysis.py @@ -0,0 +1,205 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""数据统计分析工具。计算变量或表达式的基本统计量,包括最小值、最大值、均值、方差等。""" +import numpy as np +import sr_harness_engine as engine +from typing import Dict, Any, List +from .base_tool import BaseTool, ToolMetadata, is_numeric_array + + +@BaseTool.register('statistics_analysis') +class StatisticsTool(BaseTool): + """Implementation of the statistics tool.""" + metadata = ToolMetadata('statistics_analysis') + + def execute( + self, + variables: List[str] = None, + n_bins: int = 10, + near_zero_threshold: float = 1e-8, + ) -> Dict[str, Any]: + """Execute statistical analysis. + + Args: + variables: List of variable names to analyze, e.g., ["x1", "x2", "y"]. + Use all variables (including the target variable) by default. + Expressions are also supported, e.g., ["sin(x1)", "(x1-x2)**2", "sin(y+x1)"]. + n_bins: Number of equal-width histogram bins used to summarize each distribution (1-100). + near_zero_threshold: First absolute-value threshold used to count near-zero samples. + The output also reports thresholds 1e-6 and 1e-4. + """ + data = self.context.data # {str: np.ndarray}, 包括 input variables & target variable + if variables is None: + variables = [key for key in data if is_numeric_array(data[key])] + get_stats_args = dict( + n_bins=max(1, min(int(n_bins), 100)), + near_zero_threshold=max(0.0, float(near_zero_threshold)), + ) + statistics = {} + exceptions = [] + for item in variables: + if item in data: + x = data[item] + else: + try: + f = self.parse_formula(item) + x = f.eval(data) + except Exception as e: + exceptions.append(f"Failed to compute '{item}': {str(e)}") + continue + if not is_numeric_array(x): + exceptions.append(f"Feature '{item}' did not produce numeric values.") + continue + try: + statistics[item] = self.get_stats(x, **get_stats_args) + except Exception as e: + exceptions.append(f"Failed to analyze '{item}': {str(e)}") + return { + 'statistics': statistics, + 'config': get_stats_args, + 'exceptions': exceptions + } + + @classmethod + def format_result_dict(cls, result: Dict[str, Any]) -> str: + """Format a tool result for the language model. + + Args: + result: Result mapping to format or update. + + Returns: + str: The operation result. + """ + def number(value): + if value == 0: + return "0" + return f"{value:#.3g}".removesuffix(".") + + def percent(value): + return f"{number(100 * value)}%" + + def threshold_number(value): + return "0" if value == 0 else f"{value:.2e}" + + def interval(left, right, last=False): + return f"[{number(left)}, {number(right)}{']' if last else ')'}" + + sections = [] + for var, stat in result['statistics'].items(): + total = stat['n_samples'] + lines = [ + f"{var} (finite samples={stat['n_finite']}/{stat['n_samples']}; " + f"finite ratio={percent(stat['finite_ratio'])}):", + " Fractions:", + f" Inf={stat['n_pos_inf']}/{total} ({percent(stat['n_pos_inf'] / total)})", + f" Negative inf={stat['n_neg_inf']}/{total} ({percent(stat['n_neg_inf'] / total)})", + f" NaN={stat['n_nan']}/{total} ({percent(stat['n_nan'] / total)})", + f" Negative={stat['n_negative']}/{total} ({percent(stat['n_negative'] / total)});", + f" Zero={stat['n_zero']}/{total} ({percent(stat['n_zero'] / total)});", + f" Positive={stat['n_positive']}/{total} ({percent(stat['n_positive'] / total)});", + f" Statistics (computed on {stat['n_finite']} finite values):", + f" Range=[{number(stat['min'])}, {number(stat['max'])}];", + f" Mean={number(stat['mean'])};", + f" Median={number(stat['median'])};", + f" Variance={number(stat['variance'])};", + f" Std={number(stat['std'])} (ddof=0);", + f" Q1 (25%)={number(stat['q1'])};", + f" Q3 (75%)={number(stat['q3'])};", + f" Near-zero fraction (computed on {stat['n_finite']} finite values):", + ] + for item in stat['near_zero_fractions']: + lines.append( + f" fraction(|{var}| <= {threshold_number(item['threshold'])})=" + f"{item['count']}/{stat['n_finite']} ({percent(item['ratio'])});" + ) + distribution = stat['distribution'] + bins = distribution['bins'] + collapse_note = "; near-constant values combined" if distribution.get("near_constant_collapsed") else "" + lines.append( + f" Equal-width histogram (n_bins={distribution['n_bins']}; finite values only; " + f"last bin includes its right endpoint{collapse_note}):" + ) + lines.append(" (Range | samples | fraction of finite samples)") + for index, item in enumerate(bins): + ratio = item['count'] / stat['n_finite'] + lines.append( + f" {interval(item['left'], item['right'], index == len(bins) - 1)} " + f"| {item['count']} | {percent(ratio)}" + ) + sections.append("\n".join(lines)) + if result['exceptions']: + sections.append("Exceptions:\n" + "\n".join(result['exceptions'])) + return "\n\n".join(sections) + ("\n" if sections else "") + + def get_stats( + self, + arr: np.ndarray, + n_bins: int = 10, + near_zero_threshold: float = 1e-8, + ) -> Dict[str, Any]: + """Compute statistics for a single array. + + Args: + arr: Input array. + + Returns: + Dictionary of statistics. + """ + arr = np.asarray(arr).flatten() + if arr.size == 0: + raise ValueError("zero-size array cannot be analyzed") + finite = np.isfinite(arr) + values = arr[finite] + if values.size == 0: + raise ValueError("array contains no finite values") + minimum, maximum = float(np.min(values)), float(np.max(values)) + near_constant = (maximum - minimum <= 32 * np.finfo(float).eps + * max(abs(minimum), abs(maximum), 1.0)) + if near_constant: + counts = np.array([len(values)]) + edges = np.array([minimum, maximum]) + else: + counts, edges = np.histogram(values, bins=n_bins) + near_zero_thresholds = list(dict.fromkeys((float(near_zero_threshold), 1e-6, 1e-4))) + near_zero_fractions = [] + for threshold in near_zero_thresholds: + count = int(np.count_nonzero(np.abs(values) <= threshold)) + near_zero_fractions.append({ + "threshold": threshold, + "count": count, + "ratio": count / len(values), + }) + bins = [] + for i in range(len(counts)): + bins.append({ + "left": float(edges[i]), + "right": float(edges[i + 1]), + "count": int(counts[i]) + }) + return { + "n_samples": len(arr), + "n_finite": int(values.size), + "n_pos_inf": int(np.count_nonzero(np.isposinf(arr))), + "n_neg_inf": int(np.count_nonzero(np.isneginf(arr))), + "n_nan": int(np.count_nonzero(np.isnan(arr))), + "min": float(np.min(values)), + "max": float(np.max(values)), + "mean": float(np.mean(values)), + "variance": float(np.var(values)), + "std": float(np.std(values)), + "median": float(np.median(values)), + "q1": float(np.percentile(values, 25)), + "q3": float(np.percentile(values, 75)), + "negative_ratio": float(np.mean(values < 0)), + "zero_ratio": float(np.mean(values == 0)), + "positive_ratio": float(np.mean(values > 0)), + "near_zero_ratio": float(np.mean(np.abs(values) <= near_zero_threshold)), + "n_negative": int(np.count_nonzero(values < 0)), + "n_zero": int(np.count_nonzero(values == 0)), + "n_positive": int(np.count_nonzero(values > 0)), + "n_near_zero": int(np.count_nonzero(np.abs(values) <= near_zero_threshold)), + "near_zero_fractions": near_zero_fractions, + "near_zero_threshold": float(near_zero_threshold), + "finite_ratio": float(np.mean(finite)), + "distribution": {"n_bins": len(bins), "bins": bins, + "near_constant_collapsed": bool(near_constant)}, + } diff --git a/src/sr_harness/tools/subagent.py b/src/sr_harness/tools/subagent.py new file mode 100644 index 0000000000000000000000000000000000000000..43b9b1b14acc6f38d709646b3d2b6aa89c2ce8fd --- /dev/null +++ b/src/sr_harness/tools/subagent.py @@ -0,0 +1,195 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""Context-isolated symbolic-regression hypothesis and critique agent.""" +from __future__ import annotations + +from typing import Any, Dict, List + +import numpy as np + +from .base_tool import BaseTool, ToolMetadata + + +@BaseTool.register("delegate_subagent") +class SubagentTool(BaseTool): + """Implementation of the subagent tool.""" + metadata = ToolMetadata(name="delegate_subagent") + MODES = { + "hypothesis_generation": ( + "Generate 2-4 structurally distinct, testable formula families. For each, state " + "the invariant/transformation that would support it and the cheapest main-agent " + "tool call that can falsify it. Avoid guessing constants without evidence." + ), + "candidate_critique": ( + "Audit the supplied candidate formulas independently. Check identifiability, domain, " + "units when available, extrapolation, numerical stability, redundant subtrees, and " + "whether simpler algebraically equivalent forms exist. Rank concrete follow-up tests." + ), + "residual_diagnosis": ( + "Use the supplied residual evidence to identify missing variables, factors, poles, " + "symmetries, transforms, or numerical artifacts. Propose a bounded next experiment." + ), + "search_recovery": ( + "Assume the main search is stagnating. Challenge its current assumptions, identify " + "an unexplored formula family, and give a short recovery branch with stop criteria." + ), + } + + def execute( + self, + objective: str, + mode: str = "hypothesis_generation", + candidate_formulas: List[str] = None, + evidence: str = "", + ) -> Dict[str, Any]: + """Run a bounded independent SR analysis with a specific scientific role. + + Use this only when diversity or an independent audit is valuable: generating competing + hypotheses before committing search budget, critiquing near-tied candidates, diagnosing + structured residuals, or recovering a stagnated search. The subagent cannot execute tools + or mutate the main search state; it must return falsifiable recommendations. + + Args: + objective: Precise scientific question or search decision to resolve. + mode: hypothesis_generation, candidate_critique, residual_diagnosis, or search_recovery. + candidate_formulas: Candidate expressions to compare when relevant. + evidence: Compact metrics, residual summaries, units, or search history from main tools. + """ + if not objective.strip(): + raise ValueError("objective must not be empty") + if mode not in self.MODES: + raise ValueError(f"mode must be one of: {', '.join(self.MODES)}") + messages = self._messages(objective, mode, candidate_formulas or [], evidence) + callback = getattr(self.context.args, "subagent_callback", None) + if callback is not None: + response = callback(messages) + return { + "mode": mode, + "objective": objective, + "content": str(response), + "usage": {}, + } + + from ..api import BaseAPI + + provider = getattr(self.context.args, "subagent_llm_provider", None) + if provider is None: + provider = getattr(self.context.args, "llm_provider", None) + model = getattr(self.context.args, "subagent_llm_model", None) + if model is None: + model = getattr(self.context.args, "llm_model", None) + if not isinstance(provider, str) or not provider: + raise ValueError("A non-empty subagent or primary LLM provider is required") + if not isinstance(model, str) or not model: + raise ValueError("A non-empty subagent or primary LLM model is required") + api = BaseAPI.create( + provider, + model=model, + ) + result = api(messages, n=1, max_tokens=getattr(self.context.args, "llm_max_tokens", 4096)) + content = "" + for response in result: + content = response.content or "" + return { + "mode": mode, + "objective": objective, + "content": content, + "usage": {"token": result.token_usage, "price": result.money_usage}, + } + + def _messages( + self, + objective: str, + mode: str, + candidate_formulas: List[str], + evidence: str, + ) -> list[dict[str, str]]: + tool_catalog = getattr(self.context.args, "tool_catalog", None) + if tool_catalog is None: + tool_catalog = BaseTool.load_tool_classes() + tool_names = ", ".join( + sorted( + tool.metadata.name + for tool in tool_catalog + if tool.metadata.name != self.metadata.name + ) + ) + candidates = "\n".join(f"- {formula}" for formula in candidate_formulas) or "(none)" + return [ + { + "role": "system", + "content": ( + "You are an independent symbolic-regression research critic, not a generic " + "chat assistant. Do not repeat the main agent's conclusion by default. Return " + "falsifiable hypotheses or objections and a bounded experiment plan. Never " + "claim to have run a tool or inspected raw rows not included in the prompt." + ), + }, + { + "role": "user", + "content": ( + f"Mode: {mode}\nMode mandate: {self.MODES[mode]}\n\n" + f"Objective:\n{objective}\n\n" + f"Automatic data summary:\n{self._data_summary()}\n\n" + f"Candidate formulas:\n{candidates}\n\n" + f"Main-agent evidence:\n{evidence.strip() or '(none supplied)'}\n\n" + f"Available main-agent tools (recommend only these):\n{tool_names}" + ), + }, + ] + + def _data_summary(self) -> str: + data = self.context.data + target = self.context.target + target_values = self._finite_vector(data.get(target)) if target in data else None + lines = [] + for name, values in data.items(): + vector = self._finite_vector(values) + if vector is None or vector.size == 0: + lines.append(f"- {name}: shape={np.shape(values)}, no finite scalar summary") + continue + correlation = "" + if target_values is not None and name != target and len(vector) == len(target_values): + if np.std(vector) > 0 and np.std(target_values) > 0: + value = np.corrcoef(vector, target_values)[0, 1] + correlation = f", pearson_to_target={value:.4g}" + lines.append( + f"- {name}: n={vector.size}, min={np.min(vector):.4g}, " + f"median={np.median(vector):.4g}, max={np.max(vector):.4g}, " + f"mean={np.mean(vector):.4g}, std={np.std(vector):.4g}{correlation}" + ) + return "\n".join(lines) or "(data not provided)" + + @staticmethod + def _finite_vector(values): + if values is None: + return None + array = np.asarray(values) + if array.ndim != 1: + return None + return array[np.isfinite(array)].astype(float, copy=False) + + @classmethod + def format_result_dict(cls, result: Dict[str, Any]) -> str: + """Format a tool result for the language model. + + Args: + result: Result mapping to format or update. + + Returns: + str: The operation result. + """ + return f"Independent SR subagent ({result['mode']}):\n{result['content']}" + + +""" +Real callback-backed invocation and output: + +>>> tool = SubagentTool( +... data={"x": np.arange(3.0), "y": np.arange(3.0)}, +... target="y", +... subagent_callback=lambda messages: "Test x first; reject if residuals curve.", +... ) +>>> tool.execute("Audit y=x", mode="candidate_critique", candidate_formulas=["x"]) +{'mode': 'candidate_critique', 'objective': 'Audit y=x', + 'content': 'Test x first; reject if residuals curve.', 'usage': {}} +""" diff --git a/src/sr_harness/tools/validate_context_data.py b/src/sr_harness/tools/validate_context_data.py new file mode 100644 index 0000000000000000000000000000000000000000..0260496845dcb21ddfdd97133b860e8e30da1290 --- /dev/null +++ b/src/sr_harness/tools/validate_context_data.py @@ -0,0 +1,169 @@ +"""Validate a workspace ``context.data`` collection and explain repairs.""" + +from __future__ import annotations + +from typing import Any + +from ..core import inspect_context_data, load_context_data +from .base_tool import BaseTool, ToolMetadata + + +def _repair_hint(error: str) -> str: + """Translate one validation error into a concrete repair action.""" + rules = ( + ("directory does not exist", "Create the context.data directory before validating it."), + ("missing manifest.json", "Create context.data/manifest.json with non-empty variables and an axes object."), + ( + "cannot read manifest.json", + "Fix the JSON syntax, encoding, or duplicate keys in manifest.json.", + ), + ("manifest root must be", "Make the top level of manifest.json a JSON object."), + ( + "manifest.variables must be a non-empty object", + "Declare at least one variable under manifest.variables.", + ), + ( + "manifest.axes must be an object", + "Set manifest.axes to a JSON object, even when no axes are needed.", + ), + ("is missing fields", "Add every listed required field at the reported manifest location."), + ( + "contains unsupported fields", + "Remove the listed fields; store scientific meaning and units in description.", + ), + ( + "must contain exactly one of values, file, or size", + "Choose exactly one axis representation: inline values, .npy, or a positive size.", + ), + ("name must be non-empty", "Use a non-empty flat name without '/', '\\', '.' or '..'."), + ( + "file must be", + "Rename the NPY file and set file to the exact .npy value shown in the error.", + ), + ("missing array file", "Create the referenced NPY file in context.data using numpy.save."), + ( + "object dtype", + "Convert object arrays to a numeric, Boolean, or fixed-width Unicode NumPy dtype.", + ), + ( + "axes references missing axes", + "Declare every referenced axis under manifest.axes or correct the variable's axes list.", + ), + ( + "must be an array of non-empty axis names", + "Set axes to a JSON array of non-empty axis-name strings in dimension order.", + ), + ( + "dimensions but declares", + "Make the number of declared axes equal to the array rank, in dimension order.", + ), + ( + "axis length mismatch", + "Make each array dimension equal to the size of its corresponding declared axis.", + ), + ("unreferenced axes", "Remove unused axes or reference them from at least one variable."), + ( + "num_nodes and relation metadata", + "Provide num_nodes and mark each graph or hypergraph table with kind: relation, or omit both for ordinary data.", + ), + ( + "must reference a variable with kind 'relation'", + "Add kind: relation to the referenced edge-list or hyperedge-list variable.", + ), + ( + "must have shape (E, 2) or (H, 3)", + "Store graph edges as (E, 2) or hyperedges as (H, 3).", + ), + ( + "must end in a dimension", + "Make the structured variable's final dimension match the number of edges or hyperedges.", + ), + ( + "relation endpoints must use an integer dtype", + "Save relation endpoints with an integer NumPy dtype.", + ), + ( + "relation endpoints must be in", + "Correct relation indices or num_nodes so every endpoint lies in the reported range.", + ), + ( + "description must be a string", + "Set description to a JSON string explaining meaning and units.", + ), + ) + return next( + (hint for fragment, hint in rules if fragment in error), + "Correct the reported manifest field or NPY file, then run validate_context_data again.", + ) + + +@BaseTool.register("validate_context_data") +class ValidateContextDataTool(BaseTool): + """Validate context.data without mutating the live AgentContext.""" + + metadata = ToolMetadata(name="validate_context_data") + + def execute(self, path: str = "context.data") -> dict[str, Any]: + """Validate a manifest-backed context-data directory and explain every repair. + + This calls the production ``load_context_data`` loader, so a successful + result guarantees that InteractiveSession can load the same collection. + On failure it returns all detectable errors together with specific repair + suggestions instead of stopping at an opaque exception. + + Args: + path: Workspace-relative directory containing manifest.json and flat NPY files. + + Returns: + Validation status, complete diagnostics, array summaries, and repair actions. + """ + workspace = self.context.workspace + if workspace is None: + raise RuntimeError("Workspace not initialized.") + directory = workspace.path / path + + try: + load_context_data(directory, workspace=workspace) + except ValueError: + pass + report = inspect_context_data(directory, workspace=workspace) + errors = list(report.get("errors", [])) + report["repairs"] = [{"error": error, "action": _repair_hint(error)} for error in errors] + report["next_action"] = ( + "Fix every reported error and run validate_context_data again." + if errors else + "The collection is ready for InteractiveSession to load after this Agent turn." + ) + return report + + @classmethod + def format_result_dict(cls, result: dict[str, Any]) -> str: + """Format complete, actionable diagnostics for the data-preparation Agent.""" + if not result.get("valid"): + lines = [f"INVALID context.data: {result['path']}", "Required repairs:"] + for index, repair in enumerate(result.get("repairs", []), 1): + lines.extend(( + f"{index}. {repair['error']}", + f" Action: {repair['action']}", + )) + for warning in result.get("warnings", []): + lines.append(f"Warning: {warning}") + lines.append(result["next_action"]) + return "\n".join(lines) + lines = [f"VALID context.data: {result['path']}"] + for name, variable in result.get("variables", {}).items(): + lines.append( + f"- variable {name}: shape={variable['shape']}, dtype={variable['dtype']}, " + f"axes={variable['axes']}" + ) + for name, axis in result.get("axes", {}).items(): + lines.append( + f"- axis {name}: size={axis['size']}, dtype={axis['dtype']}, " + f"storage={axis['storage']}" + ) + if result.get("num_nodes") is not None: + lines.append(f"- num_nodes={result['num_nodes']}") + for warning in result.get("warnings", []): + lines.append(f"Warning: {warning}") + lines.append(result["next_action"]) + return "\n".join(lines) diff --git a/src/sr_harness/tools/validate_evaluator.py b/src/sr_harness/tools/validate_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..3746929a314a1617b6ef29ce679f29735ee38556 --- /dev/null +++ b/src/sr_harness/tools/validate_evaluator.py @@ -0,0 +1,81 @@ +"""Validate a workspace evaluator against the current dataset.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from ..core import AgentContext, ToolMetadata +from ..evaluator import load_custom_evaluator +from .base_tool import BaseTool +from .evaluate_formula import EvaluateTool + + +@BaseTool.register("validate_evaluator") +class ValidateEvaluatorTool(BaseTool): + """Load an evaluator file in isolation and use it to evaluate one formula.""" + + metadata = ToolMetadata(name="validate_evaluator") + + def execute( + self, + f: str, + evaluator_file: str | None = None, + y: str | None = None, + fit: bool = False, + show_diagnostics: bool = False, + ) -> dict[str, Any]: + """Validate a custom evaluator without changing the live context. + + Args: + evaluator_file: Optional workspace-relative Python file under context.evaluator/. When omitted, validate the evaluator already attached to the context. + f: Formula to evaluate. + y: Optional target expression; defaults to context.target. + fit: Whether to fit formula parameters first. + show_diagnostics: Whether to include residual diagnostics. + """ + relative = None + evaluator = self.context.evaluator + if evaluator_file is not None: + if self.context.workspace is None: + raise RuntimeError("Workspace not initialized.") + relative = Path(evaluator_file) + if relative.suffix != ".py": + raise ValueError("evaluator_file must identify a Python file") + path = self.context.workspace.path / relative + evaluator = load_custom_evaluator( + file=path, + workspace=self.context.workspace, + ) + test_context = AgentContext( + args=self.context.args, + data=self.context.data, + target=self.context.target, + variable_descriptions=self.context.variable_descriptions, + variable_axes=self.context.variable_axes, + variable_structures=self.context.variable_structures, + num_nodes=self.context.num_nodes, + evaluator=evaluator, + workspace=self.context.workspace, + ) + result = EvaluateTool(context=test_context).execute( + f=f, y=y, fit=fit, show_diagnostics=show_diagnostics, + ) + return { + "evaluator_file": str(relative) if relative is not None else None, + "evaluator": type(evaluator).__name__, + **result, + } + + @classmethod + def format_result_dict(cls, result: dict[str, Any]) -> str: + """Format evaluator identity and formula-evaluation details. + + Args: + result: Structured result returned by :meth:`execute`. + + Returns: + A model-readable evaluator validation report. + """ + reference = result["evaluator_file"] or result["evaluator"] + return f"Evaluator: {reference}\n" + EvaluateTool.format_result_dict(result) diff --git a/src/sr_harness/tools/web_research.py b/src/sr_harness/tools/web_research.py new file mode 100644 index 0000000000000000000000000000000000000000..32aaaffd9308db9d60e1d5793d71c67a6ea42da6 --- /dev/null +++ b/src/sr_harness/tools/web_research.py @@ -0,0 +1,202 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""Bounded public-web search.""" +from __future__ import annotations + +from html.parser import HTMLParser +from html import unescape +import ipaddress +import socket +from typing import Any, Dict +from urllib.parse import parse_qs, unquote, urlparse + +import requests + +from .base_tool import BaseTool, ToolMetadata + + +def _session_proxies(tool: BaseTool) -> dict[str, str] | None: + environment = getattr(tool.context.args, "api_environment", {}) + proxy = ( + environment.get("HTTPS_PROXY") or environment.get("https_proxy") + or environment.get("HTTP_PROXY") or environment.get("http_proxy") + ) + return {"http": proxy, "https": proxy} if proxy else None + + +class _DuckDuckGoParser(HTMLParser): + def __init__(self): + super().__init__() + self.results = [] + self._field = None + self._parts = [] + + def handle_starttag(self, tag, attrs): + attributes = dict(attrs) + classes = set(attributes.get("class", "").split()) + if tag == "a" and "result__a" in classes: + href = attributes.get("href", "") + parsed = urlparse(href) + href = unquote(parse_qs(parsed.query).get("uddg", [href])[0]) + self.results.append({"title": "", "url": href, "snippet": ""}) + self._field, self._parts = "title", [] + elif self.results and ("result__snippet" in classes): + self._field, self._parts = "snippet", [] + + def handle_data(self, data): + if self._field: + self._parts.append(data) + + def handle_endtag(self, tag): + if self._field and tag in {"a", "div"}: + self.results[-1][self._field] = unescape(" ".join("".join(self._parts).split())) + self._field, self._parts = None, [] + + +@BaseTool.register("web_search") +class WebSearchTool(BaseTool): + """Implementation of the web search tool.""" + metadata = ToolMetadata(name="web_search") + + def execute(self, query: str, max_results: int = 5) -> Dict[str, Any]: + """Search the public web for papers, documentation, and scientific context. + + Args: + query: Specific search query. + max_results: Maximum number of results, between 1 and 10. + """ + if not query.strip(): + raise ValueError("query must not be empty") + max_results = max(1, min(int(max_results), 10)) + callback = getattr(self.context.args, "web_search_callback", None) + if callback is not None: + results = callback(query, max_results) + return {"query": query, "results": list(results)[:max_results], "provider": "callback"} + response = requests.post( + "https://html.duckduckgo.com/html/", + data={"q": query}, + timeout=15, + headers={"User-Agent": "SRAgent/1.0 (research assistant)"}, + proxies=_session_proxies(self), + ) + response.raise_for_status() + parser = _DuckDuckGoParser() + parser.feed(response.text) + return { + "query": query, + "results": parser.results[:max_results], + "provider": "duckduckgo-html", + } + + +class _TextParser(HTMLParser): + def __init__(self): + super().__init__() + self.parts: list[str] = [] + self.ignored = 0 + + def handle_starttag(self, tag, attrs): + if tag in {"script", "style", "svg", "noscript"}: + self.ignored += 1 + + def handle_endtag(self, tag): + if tag in {"script", "style", "svg", "noscript"} and self.ignored: + self.ignored -= 1 + + def handle_data(self, data): + if not self.ignored and data.strip(): + self.parts.append(data.strip()) + + +@BaseTool.register("web_fetch") +class WebFetchTool(BaseTool): + """Implementation of the web fetch tool.""" + metadata = ToolMetadata(name="web_fetch") + + def execute(self, url: str, max_characters: int = 30000) -> Dict[str, Any]: + """Fetch readable text from a public HTTP or HTTPS page. + + Args: + url: Absolute public webpage URL returned by web_search. + max_characters: Maximum number of extracted text characters, between 1000 and 50000. + """ + parsed = urlparse(url) + if ( + parsed.scheme not in {"http", "https"} + or not parsed.hostname + or parsed.username is not None + or parsed.password is not None + ): + raise ValueError("url must be an absolute HTTP or HTTPS URL") + try: + literal_address = ipaddress.ip_address(parsed.hostname) + except ValueError: + literal_address = None + if literal_address is not None and not literal_address.is_global: + raise ValueError("url must resolve only to public network addresses") + addresses = { + item[4][0] + for item in socket.getaddrinfo( + parsed.hostname, + parsed.port or (443 if parsed.scheme == "https" else 80), + type=socket.SOCK_STREAM, + ) + } + public_addresses = { + address for address in addresses if ipaddress.ip_address(address).is_global + } + proxies = _session_proxies(self) + if not public_addresses or (public_addresses != addresses and not proxies): + raise ValueError("url must resolve only to public network addresses") + limit = max(1000, min(int(max_characters), 50000)) + response = requests.get( + url, + timeout=20, + headers={"User-Agent": "SRHarness/1.0"}, + allow_redirects=False, + stream=True, + proxies=proxies, + ) + if response.is_redirect: + raise ValueError("redirects are not followed; fetch the public destination URL directly") + if response.status_code in {401, 403, 429}: + status_code = response.status_code + response.close() + return { + "url": url, + "text": "", + "truncated": False, + "blocked": True, + "status_code": status_code, + "message": ( + "The site blocked automated access. Do not retry this URL repeatedly; " + "use web_search to find an accessible authoritative source for the same data." + ), + } + response.raise_for_status() + content_type = response.headers.get("content-type", "") + if "html" not in content_type and "text" not in content_type and "json" not in content_type: + raise ValueError(f"unsupported content type: {content_type}") + body = bytearray() + for chunk in response.iter_content(64 * 1024): + body.extend(chunk) + if len(body) >= 1_000_000: + break + parser = _TextParser() + parser.feed(bytes(body[:1_000_000]).decode(response.encoding or "utf-8", errors="replace")) + text = "\n".join(parser.parts) + return {"url": url, "text": text[:limit], "truncated": len(text) > limit} + + +""" +Real invocation and output captured from DuckDuckGo HTML search: + +>>> WebSearchTool().execute("EIC symbolic regression paper", max_results=2) +{'query': 'EIC symbolic regression paper', 'results': [ + {'title': '[2509.21780v1] Beyond Formula Complexity: Effective Information ...', + 'url': 'https://arxiv.org/abs/2509.21780v1', + 'snippet': 'Combining EIC with various search-based symbolic regression ...'}, + {'title': 'Beyond Accuracy and Complexity: The Effective Information Criterion for ...', + 'url': 'https://arxiv.org/html/2509.21780', + 'snippet': 'This paper presents the Effective Information Criterion (EIC) ...'}], + 'provider': 'duckduckgo-html'} +""" diff --git a/src/sr_harness/tools/workspace_code_executor.py b/src/sr_harness/tools/workspace_code_executor.py new file mode 100644 index 0000000000000000000000000000000000000000..59dd777963859297b6f10d6059a54cb64edcaa1d --- /dev/null +++ b/src/sr_harness/tools/workspace_code_executor.py @@ -0,0 +1,75 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""Execute Python with only the active conversation workspace mounted writable.""" + +from __future__ import annotations + +import json +from typing import Any, Dict + +from ..runtime import get_sandbox_runner +from .base_tool import BaseTool, ToolMetadata +from .code_executor import CodeExecutorTool + + +@BaseTool.register("workspace_code_executor") +class WorkspaceCodeExecutorTool(CodeExecutorTool): + """Implementation of the workspace code executor tool.""" + + metadata = ToolMetadata(name="workspace_code_executor") + + def execute( + self, + program: str, + timeout_seconds: int = CodeExecutorTool.DEFAULT_TIMEOUT_SECONDS, + memory_limit_mb: int = CodeExecutorTool.DEFAULT_MEMORY_LIMIT_MB, + output_limit_bytes: int = CodeExecutorTool.DEFAULT_OUTPUT_LIMIT_BYTES, + ) -> Dict[str, Any]: + """Execute Python code in the workspace directory with file access. + 1) Code runs with cwd set to the workspace directory. + 2) Use `open("filename")` or `pandas.read_csv("filename")` to read workspace files. + 3) Use `open("output.csv", "w")` to write results back to the workspace. + 4) All file paths must be within the workspace. Absolute paths outside + workspace are forbidden. + 5) Installed scientific Python libraries are available. Networking and + child-process creation are unavailable. + + Args: + program: Python code string to execute. + timeout_seconds: Wall-clock timeout in seconds. The effective value is capped. + memory_limit_mb: Address-space memory limit in MB. The effective value is capped. + output_limit_bytes: Limit on the amount of output (in bytes) that can be produced. + """ + timeout_seconds = self.bounded_int( + timeout_seconds, self.DEFAULT_TIMEOUT_SECONDS, 1, self.MAX_TIMEOUT_SECONDS + ) + memory_limit_mb = self.bounded_int( + memory_limit_mb, self.DEFAULT_MEMORY_LIMIT_MB, 64, self.MAX_MEMORY_LIMIT_MB + ) + output_limit_bytes = self.bounded_int( + output_limit_bytes, self.DEFAULT_OUTPUT_LIMIT_BYTES, 1024, self.MAX_OUTPUT_LIMIT_BYTES + ) + stdin_text = json.dumps(self.serialization(self.context.data), ensure_ascii=False) + workspace = self.context.workspace + if workspace is None: + raise RuntimeError("Workspace not initialized.") + result = get_sandbox_runner().run( + self.extract_code(program), + stdin=stdin_text, + workspace=workspace, + timeout_seconds=timeout_seconds, + memory_limit_mb=memory_limit_mb, + output_limit_bytes=output_limit_bytes, + interruption_event=getattr(self, "cancel_event", None), + ) + if result.exit_code != 0: + raise RuntimeError(result.stderr or f"Sandboxed program exited with {result.exit_code}") + return { + "stdout": result.stdout, + "stderr": result.stderr, + "duration": result.duration_seconds, + "cpu_seconds": result.cpu_seconds, + "peak_memory_bytes": result.peak_memory_bytes, + "timeout_seconds": timeout_seconds, + "memory_limit_mb": memory_limit_mb, + "output_limit_bytes": output_limit_bytes, + } diff --git a/src/sr_harness/tools/workspace_shell.py b/src/sr_harness/tools/workspace_shell.py new file mode 100644 index 0000000000000000000000000000000000000000..0583cc0563777aaf6eecb0b3463c7f5623a39de2 --- /dev/null +++ b/src/sr_harness/tools/workspace_shell.py @@ -0,0 +1,1029 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""工作区 Shell 工具。 + +提供一个隔离的工作区目录,允许 Agent 通过受限的 shell 风格命令操作 +文件。 +""" + +from __future__ import annotations + +import argparse +import gzip +import logging +import os +import re +import shlex +import shutil +import stat +from datetime import datetime +from pathlib import Path +from typing import Any, Callable, Dict, List, Never + +from ..runtime.workspace import Workspace +from .base_tool import BaseTool, ToolMetadata +from .code_executor import LimitedWriter +from ..utils import log_exception + +_logger = logging.getLogger(f"sr_harness.{__name__}") + +# WorkspaceShellTool 支持的命令白名单 +ALLOWED_COMMANDS = { + "ls", "cat", "head", "tail", "wc", "grep", + "sort", "cut", "cp", "mv", "rm", "mkdir", + "gunzip", "gzip", "unzip", "tar", +} + + +class CommandParseError(ValueError): + """Raised when the restricted command language cannot parse an invocation.""" + + +class CommandArgumentParser(argparse.ArgumentParser): + """An ``argparse`` parser that reports errors instead of exiting the process.""" + + def __init__(self, command: str): + super().__init__(prog=command, add_help=False, allow_abbrev=False, exit_on_error=False) + + def error(self, message: str) -> Never: + """Run the ``error`` operation. + + Args: + message: Message text or provider message payload. + + Returns: + Never: The operation result. + """ + raise CommandParseError(f"{self.prog}: {message}") + + def exit(self, status: int = 0, message: str | None = None) -> Never: + """Run the ``exit`` operation. + + Args: + status: Run completion status. + message: Message text or provider message payload. + + Returns: + Never: The operation result. + """ + raise CommandParseError(message or f"{self.prog}: invalid arguments") + + +@BaseTool.register("workspace_shell") +class WorkspaceShellTool(BaseTool): + """Implementation of the workspace shell tool.""" + + metadata = ToolMetadata(name="workspace_shell") + + DEFAULT_OUTPUT_LIMIT_BYTES = 64 * 1024 + MAX_OUTPUT_LIMIT_BYTES = 1024 * 1024 + + @classmethod + def get_doc(cls) -> dict[str, str]: + """Return documentation exposed as a runtime skill. + + Returns: + dict[str, str]: The operation result. + """ + return { + "name": "workspace-shell", + "description": ( + "Inspect and modify workspace files with a safe, restricted shell-like " + "command language." + ), + "content": ( + "# Workspace Shell\n\n" + "`workspace_shell` implements a small command language in Python. It does not " + "start a system shell or execute operating-system commands. Use it to inspect, " + "filter, copy, move, remove, and unpack files in the current workspace.\n\n" + "## Syntax\n\n" + "- Separate arguments with whitespace. Single quotes, double quotes, and " + "backslash escapes follow POSIX shell lexical rules.\n" + "- Join supported commands with `|`. A pipeline passes each command's text " + "output to the next command in memory; spaces around `|` are optional.\n" + "- Short flags may be combined or separated: `ls -la`, `ls -al`, " + "`ls -l -a`, and `ls -a -l` are equivalent. Options and operands may usually " + "be interspersed. Use `--` before a path beginning with `-`.\n" + "- Every path must resolve inside the workspace. Absolute paths and paths or " + "symbolic links that escape the workspace are rejected.\n" + "- Redirection and other shell operators (`>`, `<`, `;`, `&&`, `||`, `&`) are " + "not supported. There is no globbing, variable or tilde expansion, command " + "substitution, background execution, or invocation of unlisted commands.\n\n" + "## Supported commands\n\n" + "```text\n" + "ls [-a|--all] [-l] [PATH ...]\n" + "cat [-n|--number] [FILE ...]\n" + "head [-n N|--lines N|-N] [FILE]\n" + "tail [-n N|--lines N|-N] [FILE]\n" + "wc [-l] [-w] [-c] [-m] [FILE ...]\n" + "grep [-i|--ignore-case] [-v|--invert-match] [-n|--line-number]\n" + " [-c|--count] [-F|--fixed-strings] PATTERN [FILE]\n" + "sort [-r|--reverse] [-n|--numeric-sort] [-u|--unique] [FILE]\n" + "cut [-d DELIMITER|--delimiter DELIMITER] -f FIELDS [FILE]\n" + "cp [-r|-R|--recursive] [-f|--force] SOURCE DESTINATION\n" + "mv [-f|--force] SOURCE DESTINATION\n" + "rm [-r|-R|--recursive] [-f|--force] PATH ...\n" + "mkdir [-p|--parents] DIRECTORY ...\n" + "gzip [-k|--keep] [-f|--force] FILE\n" + "gunzip [-k|--keep] [-f|--force] FILE\n" + "unzip [-d DIRECTORY|--directory DIRECTORY] FILE\n" + "tar (-x|--extract) [-z|--gzip] (-f FILE|--file FILE)\n" + " [-C DIRECTORY|--directory DIRECTORY]\n" + "```\n\n" + "`grep` performs fixed-string matching; `-F` is accepted for familiar grep " + "syntax. `cut -f` accepts comma-separated, one-based field numbers. `tar` only " + "supports extraction and accepts grouped flags such as `-xf` and `-xzf`. When " + "a text-processing command has no file operand, it reads the previous pipeline " + "stage.\n\n" + "## Examples\n\n" + "```text\n" + "ls -la\n" + "cat 'experiment 1.csv' | head -5\n" + "cat data.csv|grep -i result|wc -l\n" + "cut data.csv -d, -f1,3 | sort -u\n" + "mkdir -p results/archive\n" + "cp -r results results-copy\n" + "tar -xzf results.tar.gz -C results/archive\n" + "cat -- -notes\n" + "```" + ), + } + + def execute( + self, + command: str, + output_limit_bytes: int = DEFAULT_OUTPUT_LIMIT_BYTES, + ) -> Dict[str, Any]: + """Execute a restricted shell command in the workspace directory. + Supported commands: ls, cat, head, tail, wc, grep, sort, cut, cp, mv, rm, mkdir, + gunzip, gzip, unzip, tar. + All file paths are relative to the workspace root. Absolute paths and path traversal + (e.g., ../) are forbidden. + + Args: + command: A shell command string. + Examples: "ls", "cat data.csv | head -5", "gunzip data.csv.gz". + output_limit_bytes: Maximum stdout size returned by each command segment. + """ + if self.context.workspace is None: + return self._error("Workspace not initialized.") + output_limit_bytes = self._bounded_output_limit(output_limit_bytes) + + try: + pipeline = self._parse_pipeline(command) + except CommandParseError as exc: + return self._error(f"Command parse error: {exc}") + + stdin_text = "" + for tokens in pipeline: + try: + result = self._execute_tokens(tokens, stdin_text) + if not result.get("success", False): + return result + stdin_text = self._limit_output(result.get("stdout", ""), output_limit_bytes) + except Exception as e: + rendered = shlex.join(tokens) + _logger.error(f"Error executing command segment '{rendered}': {log_exception(e)}") + return self._error( + f"Error executing command segment '{rendered}', ask human for help: " + f"{self._safe_exception_text(e)}" + ) + return self._ok(stdin_text) + + @classmethod + def format_result_dict(cls, result: Dict[str, Any]) -> str: + """Format a tool result for the language model. + + Args: + result: Result mapping to format or update. + + Returns: + str: The operation result. + """ + if not result.get("success", False): + detail = result.get("error") or result.get("stderr") or "No error detail was provided." + return f"Command failed: {detail}" + parts = [] + if result.get("stdout"): + parts.append(result["stdout"]) + if result.get("stderr"): + parts.append(f"Command stderr:\n{result['stderr']}") + return ( + "\n".join(parts) if parts else "Command completed successfully and produced no output." + ) + + def execute_single(self, command: str, stdin_text: str = "") -> Dict[str, Any]: + """Execute one command segment after pipeline parsing. + + Args: + command: Parsed command and arguments. + stdin_text: Text received from the previous pipeline segment. + + Returns: + Structured command output and status. + """ + if self.context.workspace is None: + return self._error("Workspace not initialized.") + try: + parts = shlex.split(command) + except ValueError as e: + return self._error(f"Command parse error: {e}") + return self._execute_tokens(parts, stdin_text) + + @staticmethod + def _parse_pipeline(command: str) -> list[list[str]]: + """Parse the deliberately small shell-like language into a pipeline AST. + + Quotes and backslash escapes follow POSIX shell lexical rules, but the only + executable operator is a single pipe. Shell evaluation, expansion, + redirection, conditionals, command substitution, and background jobs are + intentionally outside this language. + """ + try: + lexer = shlex.shlex(command, posix=True, punctuation_chars="|&;<>") + lexer.whitespace_split = True + lexer.commenters = "" + tokens = list(lexer) + except ValueError as exc: + raise CommandParseError(str(exc)) from exc + + pipeline: list[list[str]] = [[]] + for token in tokens: + if token == "|": + if not pipeline[-1]: + raise CommandParseError("empty command before pipe") + pipeline.append([]) + elif token and all(char in "|&;<>" for char in token): + raise CommandParseError(f"operator {token!r} is not supported") + else: + pipeline[-1].append(token) + if not pipeline[-1]: + message = "empty command" if len(pipeline) == 1 else "empty command after pipe" + raise CommandParseError(message) + return pipeline + + def _execute_tokens(self, parts: list[str], stdin_text: str) -> Dict[str, Any]: + if not parts: + return self._error("Empty command.") + + cmd_name = parts[0] + args = parts[1:] + + if cmd_name not in ALLOWED_COMMANDS: + return self._error( + f"Command '{cmd_name}' is not allowed. " + f"Allowed: {', '.join(sorted(ALLOWED_COMMANDS))}" + ) + + handler = getattr(self, f"_cmd_{cmd_name}", None) + if handler is None: + return self._error(f"Command '{cmd_name}' is not implemented.") + try: + return handler(args, stdin_text) + except CommandParseError as exc: + return self._error(str(exc)) + + @staticmethod + def _ok(stdout: str) -> Dict[str, Any]: + return {"success": True, "stdout": stdout, "stderr": "", "exit_code": 0} + + @staticmethod + def _error(msg: str) -> Dict[str, Any]: + return {"success": False, "stdout": "", "stderr": "", "error": msg, "exit_code": 1} + + @classmethod + def _bounded_output_limit(cls, value: Any) -> int: + try: + parsed = int(value) + except (TypeError, ValueError): + parsed = cls.DEFAULT_OUTPUT_LIMIT_BYTES + return max(1024, min(cls.MAX_OUTPUT_LIMIT_BYTES, parsed)) + + @staticmethod + def _limit_output(stdout: str, output_limit_bytes: int) -> str: + writer = LimitedWriter(output_limit_bytes) + writer.write(stdout) + return writer.getvalue() + + @staticmethod + def _parse_args( + command: str, + args: list[str], + configure: Callable[[CommandArgumentParser], None], + ) -> argparse.Namespace: + parser = CommandArgumentParser(command) + configure(parser) + try: + return parser.parse_intermixed_args(args) + except argparse.ArgumentError as exc: + raise CommandParseError(f"{command}: {exc}") from exc + + def _read_text(self, path: Path) -> str: + if not path.is_file(): + raise CommandParseError(f"Not a regular file: {path.name}") + try: + with self._workspace.safe_open( + path, "r", encoding="utf-8", errors="replace" + ) as f: + return f.read() + except OSError as exc: + raise CommandParseError( + f"Cannot read file: {self._safe_exception_text(exc)}" + ) from exc + + @property + def _workspace(self) -> Workspace: + workspace = self.context.workspace + if workspace is None: + raise RuntimeError("Workspace not initialized.") + return workspace + + def _safe_exception_text(self, error: BaseException) -> str: + """Remove host workspace and mount locations from a user-visible error.""" + message = str(error) + workspace = self.context.workspace + if workspace is None: + return message + replacements = [ + (workspace.path, "."), + *( + (source, os.fspath(logical.relative_to(workspace.path))) + for logical, source in workspace.mount_map.items() + ), + ] + for host_path, visible_path in sorted( + replacements, + key=lambda pair: len(os.fspath(pair[0])), + reverse=True, + ): + message = message.replace(os.fspath(host_path), visible_path) + return message + + def _copy_file(self, source: str | os.PathLike, destination: str) -> str: + """Copy one regular file while enforcing safe source and destination access.""" + ws = self._workspace + with ws.safe_open(source, "rb") as input_stream: + with ws.open_for_write(destination, "wb") as output_stream: + shutil.copyfileobj(input_stream, output_stream) + return os.fspath(destination) + + @staticmethod + def _reject_tree_symlinks(directory: str, names: list[str]) -> set[str]: + """Reject recursive copies containing symbolic links instead of following them.""" + symbolic_links = [name for name in names if (Path(directory) / name).is_symlink()] + if symbolic_links: + raise ValueError( + "recursive copies do not follow symbolic links: " + + ", ".join(symbolic_links) + ) + return set() + + @staticmethod + def _find_tree_symlink(root: Path) -> Path | None: + """Return the first symbolic link below a directory without following links.""" + for directory, directories, filenames in os.walk(root, followlinks=False): + parent = Path(directory) + for name in (*directories, *filenames): + candidate = parent / name + if candidate.is_symlink(): + return candidate + return None + + @staticmethod + def _nonnegative_int(value: str) -> int: + try: + parsed = int(value) + except ValueError as exc: + raise argparse.ArgumentTypeError("must be an integer") from exc + if parsed < 0: + raise argparse.ArgumentTypeError("must be non-negative") + return parsed + + def _cmd_ls(self, args: list, stdin: str) -> Dict[str, Any]: + ws = self._workspace + def configure(parser): + parser.add_argument("-a", "--all", action="store_true") + parser.add_argument("-l", action="store_true", dest="long") + parser.add_argument("paths", nargs="*") + + options = self._parse_args("ls", args, configure) + targets = options.paths or ["."] + sections = [] + for target in targets: + if (path := ws.resolve(target)) is None: + return self._error(f"Invalid path: {target}") + if not path.exists(): + return self._error(f"No such file or directory: {target}") + if path.is_dir(): + entries = sorted( + ( + entry + for entry in path.iterdir() + if options.all or not entry.name.startswith(".") + ), + key=lambda entry: entry.name, + ) + names = [ + entry.name + ("@" if entry.is_symlink() else "/" if entry.is_dir() else "") + for entry in entries + ] + if options.long: + rendered = [] + for name, entry in zip(names, entries): + info = entry.lstat() + modified = datetime.fromtimestamp(info.st_mtime).strftime("%Y-%m-%d %H:%M") + rendered.append( + f"{stat.filemode(info.st_mode)} {info.st_size:>10} {modified} {name}" + ) + output = "\n".join(rendered) + else: + output = "\n".join(names) + if len(targets) > 1: + sections.append(f"{target}:\n" + output) + else: + sections.append(output) + else: + if options.long: + info = path.stat() + modified = datetime.fromtimestamp(info.st_mtime).strftime("%Y-%m-%d %H:%M") + sections.append( + f"{stat.filemode(info.st_mode)} {info.st_size:>10} {modified} {path.name}" + ) + else: + sections.append(path.name) + return self._ok("\n\n".join(sections)) + + def _cmd_cat(self, args: list, stdin: str) -> Dict[str, Any]: + ws = self._workspace + def configure(parser): + parser.add_argument("-n", "--number", action="store_true") + parser.add_argument("files", nargs="*") + + options = self._parse_args("cat", args, configure) + if not options.files: + text = stdin + if options.number: + text = "\n".join( + f"{index:6}\t{line}" for index, line in enumerate(text.splitlines(), 1) + ) + return self._ok(text) + parts: List[str] = [] + for arg in options.files: + if (path := ws.resolve(arg)) is None: + return self._error(f"Invalid path: {arg}") + if not path.exists(): + return self._error(f"No such file: {arg}") + try: + parts.append(self._read_text(path)) + except Exception as e: + return self._error(f"Cannot read file: {self._safe_exception_text(e)}") + text = "".join(parts) + if options.number: + text = "\n".join( + f"{index:6}\t{line}" for index, line in enumerate(text.splitlines(), 1) + ) + return self._ok(text) + + def _cmd_head(self, args: list, stdin: str) -> Dict[str, Any]: + ws = self._workspace + normalized = [ + part + for arg in args + for part in (["-n", arg[1:]] if re.fullmatch(r"-\d+", arg) else [arg]) + ] + + def configure(parser): + parser.add_argument("-n", "--lines", type=self._nonnegative_int, default=10) + parser.add_argument("files", nargs="*") + + options = self._parse_args("head", normalized, configure) + if len(options.files) > 1: + return self._error("head: at most one file is supported") + if options.files: + path = ws.resolve(options.files[0]) + if path is None: + return self._error(f"Invalid path: {options.files[0]}") + if not path.exists(): + return self._error(f"No such file: {options.files[0]}") + text = self._read_text(path) + else: + text = stdin + lines = text.splitlines()[:options.lines] + return self._ok("\n".join(lines)) + + def _cmd_tail(self, args: list, stdin: str) -> Dict[str, Any]: + ws = self._workspace + normalized = [ + part + for arg in args + for part in (["-n", arg[1:]] if re.fullmatch(r"-\d+", arg) else [arg]) + ] + + def configure(parser): + parser.add_argument("-n", "--lines", type=self._nonnegative_int, default=10) + parser.add_argument("files", nargs="*") + + options = self._parse_args("tail", normalized, configure) + if len(options.files) > 1: + return self._error("tail: at most one file is supported") + if options.files: + path = ws.resolve(options.files[0]) + if path is None: + return self._error(f"Invalid path: {options.files[0]}") + if not path.exists(): + return self._error(f"No such file: {options.files[0]}") + text = self._read_text(path) + else: + text = stdin + lines = text.splitlines()[-options.lines:] if options.lines else [] + return self._ok("\n".join(lines)) + + def _cmd_wc(self, args: list, stdin: str) -> Dict[str, Any]: + ws = self._workspace + def configure(parser): + parser.add_argument("-l", "--lines", action="store_true") + parser.add_argument("-w", "--words", action="store_true") + parser.add_argument("-c", "--bytes", action="store_true") + parser.add_argument("-m", "--chars", action="store_true") + parser.add_argument("files", nargs="*") + + options = self._parse_args("wc", args, configure) + selected = [options.lines, options.words, options.bytes, options.chars] + enabled_counts = selected if any(selected) else [True, True, True, False] + sources: list[tuple[str, str]] = [] + if options.files: + for name in options.files: + path = ws.resolve(name) + if path is None: + return self._error(f"Invalid path: {name}") + if not path.exists(): + return self._error(f"No such file: {name}") + sources.append((name, self._read_text(path))) + else: + sources.append(("", stdin)) + + def counts(text: str) -> list[int]: + values = [ + len(text.splitlines()), + len(text.split()), + len(text.encode("utf-8")), + len(text), + ] + return [value for value, enabled in zip(values, enabled_counts) if enabled] + + output = [ + " ".join(map(str, counts(text))) + (f" {name}" if name else "") + for name, text in sources + ] + if len(sources) > 1: + totals = [sum(values) for values in zip(*(counts(text) for _, text in sources))] + output.append(" ".join(map(str, totals)) + " total") + return self._ok("\n".join(output)) + + def _cmd_grep(self, args: list, stdin: str) -> Dict[str, Any]: + ws = self._workspace + def configure(parser): + parser.add_argument("-i", "--ignore-case", action="store_true") + parser.add_argument("-v", "--invert-match", action="store_true") + parser.add_argument("-n", "--line-number", action="store_true") + parser.add_argument("-c", "--count", action="store_true") + parser.add_argument("-F", "--fixed-strings", action="store_true") + parser.add_argument("pattern") + parser.add_argument("files", nargs="*") + + options = self._parse_args("grep", args, configure) + if len(options.files) > 1: + return self._error("grep: at most one file is supported") + if options.files: + path = ws.resolve(options.files[0]) + if path is None: + return self._error(f"Invalid path: {options.files[0]}") + if not path.exists(): + return self._error(f"No such file: {options.files[0]}") + text = self._read_text(path) + else: + text = stdin + pattern = options.pattern.casefold() if options.ignore_case else options.pattern + matched = [] + for number, line in enumerate(text.splitlines(), 1): + searchable = line.casefold() if options.ignore_case else line + include = pattern in searchable + if include == options.invert_match: + continue + matched.append( + f"{number}:{line}" if options.line_number and not options.count else line + ) + return self._ok(str(len(matched)) if options.count else "\n".join(matched)) + + def _cmd_sort(self, args: list, stdin: str) -> Dict[str, Any]: + ws = self._workspace + def configure(parser): + parser.add_argument("-r", "--reverse", action="store_true") + parser.add_argument("-n", "--numeric-sort", action="store_true") + parser.add_argument("-u", "--unique", action="store_true") + parser.add_argument("files", nargs="*") + + options = self._parse_args("sort", args, configure) + if len(options.files) > 1: + return self._error("sort: at most one file is supported") + if options.files: + path = ws.resolve(options.files[0]) + if path is None: + return self._error(f"Invalid path: {options.files[0]}") + if not path.exists(): + return self._error(f"No such file: {options.files[0]}") + text = self._read_text(path) + else: + text = stdin + lines = text.splitlines() + if options.unique: + lines = list(dict.fromkeys(lines)) + if options.numeric_sort: + try: + lines.sort(key=lambda line: float(line.strip()), reverse=options.reverse) + except ValueError: + return self._error("sort: non-numeric input with -n") + else: + lines.sort(reverse=options.reverse) + return self._ok("\n".join(lines)) + + def _cmd_cut(self, args: list, stdin: str) -> Dict[str, Any]: + ws = self._workspace + def configure(parser): + parser.add_argument("-d", "--delimiter", default="\t") + parser.add_argument("-f", "--fields", required=True) + parser.add_argument("files", nargs="*") + + options = self._parse_args("cut", args, configure) + if len(options.delimiter) != 1: + return self._error("cut: delimiter must be a single character") + if len(options.files) > 1: + return self._error("cut: at most one file is supported") + if options.files: + path = ws.resolve(options.files[0]) + if path is None: + return self._error(f"Invalid path: {options.files[0]}") + if not path.exists(): + return self._error(f"No such file: {options.files[0]}") + text = self._read_text(path) + else: + text = stdin + # 解析字段索引(1-based) + try: + field_indices = [int(field) - 1 for field in options.fields.split(",")] + if any(index < 0 for index in field_indices): + raise ValueError + except ValueError: + return self._error(f"Invalid field specification: {options.fields}") + output_lines = [] + for line in text.splitlines(): + parts = line.split(options.delimiter) + selected = [parts[i] if i < len(parts) else "" for i in field_indices] + output_lines.append(options.delimiter.join(selected)) + return self._ok("\n".join(output_lines)) + + def _cmd_cp(self, args: list, stdin: str) -> Dict[str, Any]: + ws = self._workspace + def configure(parser): + parser.add_argument("-r", "-R", "--recursive", action="store_true") + parser.add_argument("-f", "--force", action="store_true") + parser.add_argument("paths", nargs="+") + + options = self._parse_args("cp", args, configure) + if len(options.paths) != 2: + return self._error("cp: exactly one source and one destination are supported") + source, destination = options.paths + src_path = ws.resolve(source) + dst_path = ws.resolve(destination) + if src_path is None: + return self._error(f"Invalid source path: {source}") + if dst_path is None: + return self._error(f"Invalid destination path: {destination}") + if not src_path.exists(): + return self._error(f"No such file: {source}") + if src_path.is_dir() and not options.recursive: + return self._error(f"cp: omitting directory {source!r}; use -r") + effective_destination = dst_path / src_path.name if dst_path.is_dir() else dst_path + destination_name = str( + Path(destination) / src_path.name if dst_path.is_dir() else Path(destination) + ) + dst_path = ws.resolve( + destination_name, + access="remove" if effective_destination.exists() else "create", + ) + if dst_path is None: + return self._error(f"Invalid destination path: {destination}") + if dst_path.exists() and os.path.samefile(src_path, dst_path): + return self._error("cp: source and destination identify the same file") + if src_path.is_dir(): + try: + dst_path.relative_to(src_path) + except ValueError: + pass + else: + return self._error("cp: cannot copy a directory into itself") + try: + if src_path.is_dir(): + if dst_path.exists() and not options.force: + return self._error(f"cp: destination already exists: {destination}") + ws.create_directory(destination_name, parents=True, exist_ok=options.force) + for directory, directories, filenames in os.walk(src_path, followlinks=False): + parent = Path(directory) + symbolic_links = [ + name for name in (*directories, *filenames) + if (parent / name).is_symlink() + ] + if symbolic_links: + raise ValueError( + "recursive copies do not follow symbolic links: " + + ", ".join(symbolic_links) + ) + relative = parent.relative_to(src_path) + for name in directories: + child = Path(destination_name) / relative / name + ws.create_directory(str(child), parents=True, exist_ok=options.force) + for name in filenames: + child = Path(destination_name) / relative / name + self._copy_file(parent / name, str(child)) + else: + self._copy_file(src_path, destination_name) + return self._ok("") + except Exception as e: + return self._error(f"cp failed: {self._safe_exception_text(e)}") + + def _cmd_mv(self, args: list, stdin: str) -> Dict[str, Any]: + ws = self._workspace + def configure(parser): + parser.add_argument("-f", "--force", action="store_true") + parser.add_argument("paths", nargs="+") + + options = self._parse_args("mv", args, configure) + if len(options.paths) != 2: + return self._error("mv: exactly one source and one destination are supported") + source, destination = options.paths + src_path = ws.resolve(source, access="remove") + destination_probe = ws.resolve(destination) + destination_name = str( + Path(destination) / src_path.name + if src_path is not None and destination_probe is not None and destination_probe.is_dir() + else Path(destination) + ) + effective_probe = ws.resolve(destination_name) + dst_path = ws.resolve( + destination_name, + access=( + "remove" if effective_probe is not None and effective_probe.exists() else "create" + ), + ) + if src_path is None: + return self._error(f"Invalid source path: {source}") + if dst_path is None: + return self._error(f"Invalid destination path: {destination}") + if not src_path.exists(): + return self._error(f"No such file: {source}") + if src_path == ws.path: + return self._error("mv: refusing to move the workspace root") + if dst_path.exists() and os.path.samefile(src_path, dst_path): + return self._error("mv: source and destination identify the same file") + if src_path.is_dir(): + try: + dst_path.relative_to(src_path) + except ValueError: + pass + else: + return self._error("mv: cannot move a directory into itself") + try: + ws.move(source, destination_name, overwrite=options.force) + return self._ok("") + except Exception as e: + return self._error(f"mv failed: {self._safe_exception_text(e)}") + + def _cmd_rm(self, args: list, stdin: str) -> Dict[str, Any]: + ws = self._workspace + def configure(parser): + parser.add_argument("-r", "-R", "--recursive", action="store_true") + parser.add_argument("-f", "--force", action="store_true") + parser.add_argument("paths", nargs="+") + + options = self._parse_args("rm", args, configure) + for name in options.paths: + path = ws.resolve(name, access="remove") + if path is None: + return self._error(f"Invalid path: {name}") + if path == ws.path: + return self._error("rm: refusing to remove the workspace root") + if not os.path.lexists(path): + if options.force: + continue + return self._error(f"No such file: {name}") + try: + ws.remove(name, recursive=options.recursive, missing_ok=options.force) + except IsADirectoryError: + return self._error(f"rm: cannot remove directory {name!r} without -r") + except Exception as e: + return self._error(f"rm failed: {self._safe_exception_text(e)}") + return self._ok("") + + def _cmd_mkdir(self, args: list, stdin: str) -> Dict[str, Any]: + ws = self._workspace + def configure(parser): + parser.add_argument("-p", "--parents", action="store_true") + parser.add_argument("directories", nargs="+") + + options = self._parse_args("mkdir", args, configure) + for name in options.directories: + try: + ws.create_directory(name, parents=options.parents, exist_ok=options.parents) + except Exception as e: + return self._error(f"mkdir failed: {self._safe_exception_text(e)}") + return self._ok("") + + def _cmd_gunzip(self, args: list, stdin: str) -> Dict[str, Any]: + ws = self._workspace + def configure(parser): + parser.add_argument("-k", "--keep", action="store_true") + parser.add_argument("-f", "--force", action="store_true") + parser.add_argument("file") + + options = self._parse_args("gunzip", args, configure) + path = ws.resolve(options.file) + if path is None: + return self._error(f"Invalid path: {options.file}") + if not path.exists(): + return self._error(f"No such file: {options.file}") + output_name = ( + str(Path(options.file).with_suffix("")) + if Path(options.file).suffix == ".gz" + else str(Path(options.file).parent / (Path(options.file).name + ".out")) + ) + output_probe = ws.resolve(output_name) + out_path = ws.resolve( + output_name, + access="remove" if output_probe is not None and output_probe.exists() else "create", + ) + remove_path = None if options.keep else ws.resolve(options.file, access="remove") + if out_path is None or (not options.keep and remove_path is None): + return self._error("gunzip: read-only workspace inputs cannot be modified") + if out_path.exists() and os.path.samefile(path, out_path): + return self._error("gunzip: input and output identify the same file") + if out_path.exists() and not options.force: + return self._error(f"gunzip: output already exists: {out_path.name}; use -f") + try: + with ws.safe_open(path, "rb") as f: + with gzip.GzipFile(fileobj=f, mode="rb") as f_in: + with ws.open_for_write(output_name, "wb") as f_out: + shutil.copyfileobj(f_in, f_out) + if remove_path is not None: + ws.remove(options.file) + return self._ok(f"Decompressed to {out_path.name}") + except Exception as e: + return self._error(f"gunzip failed: {self._safe_exception_text(e)}") + + def _cmd_gzip(self, args: list, stdin: str) -> Dict[str, Any]: + ws = self._workspace + def configure(parser): + parser.add_argument("-k", "--keep", action="store_true") + parser.add_argument("-f", "--force", action="store_true") + parser.add_argument("file") + + options = self._parse_args("gzip", args, configure) + path = ws.resolve(options.file) + if path is None: + return self._error(f"Invalid path: {options.file}") + if not path.exists(): + return self._error(f"No such file: {options.file}") + output_name = str(Path(options.file).parent / (Path(options.file).name + ".gz")) + output_probe = ws.resolve(output_name) + out_path = ws.resolve( + output_name, + access="remove" if output_probe is not None and output_probe.exists() else "create", + ) + remove_path = None if options.keep else ws.resolve(options.file, access="remove") + if out_path is None or (not options.keep and remove_path is None): + return self._error("gzip: read-only workspace inputs cannot be modified") + if out_path.exists() and os.path.samefile(path, out_path): + return self._error("gzip: input and output identify the same file") + if out_path.exists() and not options.force: + return self._error(f"gzip: output already exists: {out_path.name}; use -f") + try: + with ws.safe_open(path, "rb") as f_in: + with ws.open_for_write(output_name, "wb") as output_stream: + with gzip.GzipFile(fileobj=output_stream, mode="wb") as f_out: + shutil.copyfileobj(f_in, f_out) + if remove_path is not None: + ws.remove(options.file) + return self._ok(f"Compressed to {out_path.name}") + except Exception as e: + return self._error(f"gzip failed: {self._safe_exception_text(e)}") + + def _cmd_unzip(self, args: list, stdin: str) -> Dict[str, Any]: + ws = self._workspace + import zipfile + + def configure(parser): + parser.add_argument("-d", "--directory", default=".") + parser.add_argument("file") + + options = self._parse_args("unzip", args, configure) + path = ws.resolve(options.file) + destination = ws.resolve(options.directory) + if destination is not None and not destination.exists(): + destination = ws.resolve(options.directory, access="create") + if path is None: + return self._error(f"Invalid path: {options.file}") + if destination is None: + return self._error(f"Invalid destination path: {options.directory}") + if not path.exists(): + return self._error(f"No such file: {options.file}") + try: + with ws.safe_open(path, "rb") as f: + zf = zipfile.ZipFile(f, "r") + with zf: + ws.create_directory(options.directory, parents=True, exist_ok=True) + for member in zf.infolist(): + member_relative = Path(member.filename) + if member_relative.is_absolute() or ".." in member_relative.parts: + return self._error(f"Unsafe path in archive: {member.filename}") + logical_member = str(Path(options.directory) / member_relative) + if Path(logical_member) == Path(options.file): + return self._error( + f"Archive member would overwrite its source: {member.filename}" + ) + mode = member.external_attr >> 16 + if stat.S_ISLNK(mode): + return self._error( + f"Symbolic links are not allowed in archives: {member.filename}" + ) + file_type = stat.S_IFMT(mode) + if file_type and not (stat.S_ISREG(mode) or stat.S_ISDIR(mode)): + return self._error( + f"Special files are not allowed in archives: {member.filename}" + ) + if member.is_dir(): + ws.create_directory(logical_member, parents=True, exist_ok=True) + else: + parent = str(Path(logical_member).parent) + ws.create_directory(parent, parents=True, exist_ok=True) + with zf.open(member, "r") as input_stream: + with ws.open_for_write(logical_member, "wb") as output_stream: + shutil.copyfileobj(input_stream, output_stream) + return self._ok(f"Extracted to {options.directory}") + except Exception as e: + return self._error(f"unzip failed: {self._safe_exception_text(e)}") + + def _cmd_tar(self, args: list, stdin: str) -> Dict[str, Any]: + ws = self._workspace + import tarfile + + def configure(parser): + parser.add_argument("-x", "--extract", action="store_true") + parser.add_argument("-z", "--gzip", action="store_true") + parser.add_argument("-f", "--file", required=True) + parser.add_argument("-C", "--directory", default=".") + + options = self._parse_args("tar", args, configure) + path = ws.resolve(options.file) + destination = ws.resolve(options.directory) + if destination is not None and not destination.exists(): + destination = ws.resolve(options.directory, access="create") + if path is None: + return self._error(f"Invalid path: {options.file}") + if destination is None: + return self._error(f"Invalid destination path: {options.directory}") + if not path.exists(): + return self._error(f"No such file: {options.file}") + if not options.extract: + return self._error("Only tar extraction (-x) is supported.") + mode = "r:gz" if options.gzip else "r:*" + try: + ws.create_directory(options.directory, parents=True, exist_ok=True) + with ws.safe_open(path, "rb") as f: + tf = tarfile.open(fileobj=f, mode=mode) + with tf: + for member in tf.getmembers(): + if not (member.isfile() or member.isdir()): + return self._error( + f"Links and special files are not allowed in archives: " + f"{member.name}" + ) + member_relative = Path(member.name) + if member_relative.is_absolute() or ".." in member_relative.parts: + return self._error(f"Unsafe path in archive: {member.name}") + logical_member = str(Path(options.directory) / member_relative) + if Path(logical_member) == Path(options.file): + return self._error( + f"Archive member would overwrite its source: {member.name}" + ) + if member.isdir(): + ws.create_directory(logical_member, parents=True, exist_ok=True) + else: + parent = str(Path(logical_member).parent) + ws.create_directory(parent, parents=True, exist_ok=True) + input_stream = tf.extractfile(member) + if input_stream is None: + raise ValueError(f"Unable to read archive member: {member.name}") + with input_stream: + with ws.open_for_write(logical_member, "wb") as output_stream: + shutil.copyfileobj(input_stream, output_stream) + return self._ok(f"Extracted to {options.directory}") + except Exception as e: + return self._error(f"tar failed: {self._safe_exception_text(e)}") diff --git a/src/sr_harness/utils/__init__.py b/src/sr_harness/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..75295a485fee10a62102ede14b4f530b0d5b541d --- /dev/null +++ b/src/sr_harness/utils/__init__.py @@ -0,0 +1,34 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +from .attr_dict import * +from .logger import * +from .metrics import * +from .timing import * +from .utils import * +from .tag2ansi import tag2ansi +from .save_args import save_args +from .log_exception import log_exception +from .classproperty import classproperty +from .render_python import render_python +from .symbolic_acc import get_symbolic_acc +from .render_markdown import render_markdown +from .factory_mixin import FactoryMixin +from .fix_parser import add_minus_flags, add_negation_flags +from .lazy_loader import setup_lazy_imports, TYPE_CHECKING +from .df_to_3line import df_to_3line +from .sanitize_filename import sanitize_filename +from .format_confusion_matrix import format_confusion_matrix +from .parse_json_with_template import parse_json_with_template +from .model_store import get_default, download_model, upload_model +from .format_pareto_front import format_pareto_front +from .constant_optimizer import ConstantOptimizerConfig, fit_constants + +# 引入可选依赖的子模块 +if TYPE_CHECKING: + from . import plot + from .auto_gpu import AutoGPU + from . import nn +__getattr__, __dir__, __all__ = setup_lazy_imports(__name__, { + "plot": (".plot", "all"), + "AutoGPU": (".auto_gpu", "nn"), # 可选引入 .auto_gpu.AutoGPU, 但需要通过 pip install sr-harness[nn] 来安装可选依赖 + "nn": (".nn", "nn"), # 将 .nn package 映射到 nn,并标明需要通过 pip install sr-harness[nn] 来安装可选依赖 +}) diff --git a/src/sr_harness/utils/attr_dict.py b/src/sr_harness/utils/attr_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..a3bc49a935acfddfd79ce8bebdf3ddb2757cca0d --- /dev/null +++ b/src/sr_harness/utils/attr_dict.py @@ -0,0 +1,49 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +import os +import yaml + +__all__ = ["AttrDict"] + + +class AttrDict(dict): + def __init__(self, *args, **kwargs): + super(AttrDict, self).__init__(*args, **kwargs) + for key, value in self.items(): + if isinstance(value, dict): + self[key] = AttrDict(value) + if isinstance(value, list): + self[key] = [ + AttrDict(item) if isinstance(item, dict) else item for item in value + ] + self.__dict__ = self + + @classmethod + def load_yaml(cls, __filepath): + assert os.path.exists(__filepath), f"File {__filepath} not found!" + yaml_dict = yaml.load(open(__filepath, "r"), Loader=yaml.FullLoader) + return cls(yaml_dict) + + @classmethod + def load_yaml_str(cls, str): + yaml_dict = yaml.load(str, Loader=yaml.FullLoader) + return cls(yaml_dict) + + def __or__(self, __other): + return AttrDict({**self, **__other}) + + def __repr__(self) -> str: + return "AttrDict(" + super().__repr__() + ")" + + def __str__(self) -> str: + return ( + "{\n" + + "\n".join( + [f" {k}: " + str(v).replace("\n", "\n ") for k, v in self.items()] + ) + + "\n}" + ) + + def __getitem__(self, __key): + if isinstance(__key, int): + return list(self.values())[__key] + return super().__getitem__(__key) diff --git a/src/sr_harness/utils/auto_gpu.py b/src/sr_harness/utils/auto_gpu.py new file mode 100644 index 0000000000000000000000000000000000000000..1ddf23beada083f9b00dab1be618b2bed56d1da6 --- /dev/null +++ b/src/sr_harness/utils/auto_gpu.py @@ -0,0 +1,81 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +import os +import time +import torch +import logging +import subprocess + +__all__ = ["AutoGPU"] + +_logger = logging.getLogger(f"sr_harness.{__name__}") + + +class AutoGPU: + """Automatically choose a GPU with enough free memory""" + + def __init__(self): + visible_devices = os.getenv("CUDA_VISIBLE_DEVICES") + if visible_devices: + self.gpu_list = list(map(int, visible_devices.split(","))) + else: + self.gpu_list = [i for i in range(torch.cuda.device_count())] + self.free_memory = { + i: self.query_free_memory(j) for i, j in enumerate(self.gpu_list) + } # cuda:i -> memory of j-th GPU + + def update_free_memory(self): + for i, j in enumerate(self.gpu_list): + self.free_memory[i] = self.query_free_memory(j) + + def choice_gpu(self, memory_MB, interval=600, force=True): + """Choose a GPU with enough free memory + Arguments: + - memory_MB: int, the required memory in MB + - interval: int, the interval (in second) to check free memory + - force: bool, whether to wait until a GPU is available + """ + waiting = False + while True: + for i, free_memory in self.free_memory.items(): + if free_memory < memory_MB: + continue + try: + device = f"cuda:{i}" + free_memory1 = self.query_free_memory(self.gpu_list[i]) + fuck_cuda = torch.zeros( + int(memory_MB), 1024, 256, dtype=torch.float32, device=device + ) + free_memory2 = self.query_free_memory(self.gpu_list[i]) + if waiting: + _logger.note( + f"SubProcess[{os.getpid()}]: Choose GPU{self.gpu_list[i]} ({device}) with {memory_MB}MB ({free_memory1}MB -> {free_memory2}MB)" + ) + else: + _logger.info( + f"SubProcess[{os.getpid()}]: Choose GPU{self.gpu_list[i]} ({device}) with {memory_MB}MB ({free_memory1}MB -> {free_memory2}MB)" + ) + del fuck_cuda + return device + except Exception as e: + torch.cuda.empty_cache() + continue + else: + if force: + if not waiting: + _logger.warning(f"SubProcess[{os.getpid()}]: Waiting GPU...") + waiting = True + time.sleep(interval) + self.update_free_memory() + else: # not force + _logger.warning(f"SubProcess[{os.getpid()}]: No available GPU!") + return "cpu" + + def query_free_memory(self, gpu_id): + try: + cmd = f"nvidia-smi --query-gpu=memory.free --format=csv,noheader,nounits -i {gpu_id}" + return int( + subprocess.check_output(cmd, shell=True).decode().strip().split("\n")[0] + ) + except Exception as e: + _logger.warning(f"Query CUDA (GPU{gpu_id}) Memory Failed! {e}") + return 0 diff --git a/src/sr_harness/utils/classproperty.py b/src/sr_harness/utils/classproperty.py new file mode 100644 index 0000000000000000000000000000000000000000..b84236da2929e452afb3a8d75e991348b3669dba --- /dev/null +++ b/src/sr_harness/utils/classproperty.py @@ -0,0 +1,13 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +class classproperty(object): + """ + 自定义的类属性装饰器。 + 允许通过 ClassName.property_name 直接获取动态计算的类属性, + 同时也支持 instance.property_name。 + """ + def __init__(self, fget): + self.fget = fget + + def __get__(self, owner_instance, owner_class): + # 无论通过实例调用还是类调用,统一将当前的 class 传给底层函数 + return self.fget(owner_class) diff --git a/src/sr_harness/utils/constant_optimizer.py b/src/sr_harness/utils/constant_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..7c16a05d3f634abcc083c7c3337e62d94fd2598b --- /dev/null +++ b/src/sr_harness/utils/constant_optimizer.py @@ -0,0 +1,242 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""Numerical optimization for parameters and opted-in numeric literals.""" +from __future__ import annotations + +from dataclasses import dataclass, replace as dataclass_replace +from typing import Any, Dict +import warnings + +import numpy as np +import sr_harness_engine as engine +from scipy.optimize import differential_evolution, least_squares +from sr_harness_engine.evaluation import grouped_parameter_key +from sr_harness_engine.tree import children, with_children, transform + + +@dataclass(frozen=True) +class ConstantOptimizerConfig: + """Numerical budget and reproducibility controls for ``fit_constants``.""" + + random_state: int = 0 + n_restarts: int = 3 + max_nfev: int = 700 + differential_evolution_maxiter: int = 15 + differential_evolution_popsize: int = 5 + use_global_search: bool = True + snap_exponents: bool = True + use_eps: float = 1e-8 + + +@dataclass(frozen=True) +class _ParameterSpec: + name: str + label: Any | None + initial: float + lower: float + upper: float + literal: bool = False + + +def _parameterize_literals( + expression: engine.Expression, + data: Dict[str, np.ndarray], +) -> tuple[engine.Expression, list[_ParameterSpec]]: + specs: list[_ParameterSpec] = [] + named: dict[str, int] = {} + grouped: dict[str, engine.GroupedParameter] = {} + literal_index = 0 + + def visit( + node: engine.Expression, + parent: engine.Expression | None = None, + child_index: int | None = None, + ) -> engine.Expression: + nonlocal literal_index + if isinstance(node, engine.Number): + name = f"__literal_{literal_index}" + literal_index += 1 + value = float(node.value) + limit = max(100.0, 10.0 * abs(value) + 1.0) + lower, upper = -limit, limit + if isinstance(parent, engine.Binary) and parent.operator == "**" and child_index == 1: + lower, upper = -10.0, 10.0 + if ( + isinstance(parent, engine.Binary) + and parent.operator == "-" + and child_index == 1 + and isinstance(parent.left, engine.Symbol) + and parent.left.name in data + ): + feature = np.asarray(data[parent.left.name], dtype=float).reshape(-1) + feature = feature[np.isfinite(feature)] + if feature.size: + width = float(np.max(feature) - np.min(feature)) + margin = max(0.2 * width, 10.0) + lower = float(np.min(feature) - margin) + upper = float(np.max(feature) + margin) + specs.append(_ParameterSpec(name, None, value, lower, upper, literal=True)) + return engine.Parameter(name, value) + if isinstance(node, engine.Parameter): + if node.name not in named: + initial = 1.0 if node.value is None else float(node.value) + limit = max(100.0, 10.0 * abs(initial) + 1.0) + named[node.name] = len(specs) + specs.append(_ParameterSpec(node.name, None, initial, -limit, limit)) + return node + if isinstance(node, engine.GroupedParameter): + key = grouped_parameter_key(node) + grouped.setdefault(key, node) + return dataclass_replace(node, by=visit(node.by, node, 0)) + transformed_children = tuple( + visit(child, node, index) for index, child in enumerate(children(node)) + ) + return with_children(node, transformed_children) + + parameterized = visit(expression) + for key, node in grouped.items(): + labels = np.asarray(node.by.evaluate(data), dtype=object).reshape(-1) + unique = [] + for label in labels: + label = label.item() if isinstance(label, np.generic) else label + if label not in unique: + unique.append(label) + supplied = dict(node.value or {}) + for label in unique: + initial = float(supplied.get(label, node.default if node.default is not None else 1.0)) + limit = max(100.0, 10.0 * abs(initial) + 1.0) + specs.append(_ParameterSpec(key, label, initial, -limit, limit)) + return parameterized, specs + + +def _unpack(raw: np.ndarray, specs: list[_ParameterSpec]) -> dict[str, Any]: + result: dict[str, Any] = {} + for value, spec in zip(raw, specs): + if spec.label is None: + result[spec.name] = float(value) + else: + result.setdefault(spec.name, {})[spec.label] = float(value) + return result + + +def _bind( + expression: engine.Expression, + parameters: dict[str, Any], + literal_names: set[str], +) -> engine.Expression: + def bind(node: engine.Expression) -> engine.Expression: + if isinstance(node, engine.Parameter) and node.name in parameters: + value = float(parameters[node.name]) + if node.name in literal_names: + return engine.Number(value) + return engine.Parameter(node.name, value) + if isinstance(node, engine.GroupedParameter): + key = grouped_parameter_key(node) + if key in parameters: + return dataclass_replace(node, value=dict(parameters[key])) + return node + + return transform(expression, bind) + + +def fit_constants( + f: engine.Expression, + data: Dict[str, np.ndarray], + y: np.ndarray, + *, + config: ConstantOptimizerConfig | None = None, + num_nodes: int | None = None, +) -> engine.Expression: + """Return a fitted expression without modifying ``f``. + + This function is an explicit opt-in optimization operation, so numeric + literals are temporarily promoted to independent parameters. Outside this + function, literals remain fixed and only ``param(...)`` nodes are fitable. + """ + if not isinstance(f, engine.Expression): + raise TypeError("f must be an sr_harness_engine.Expression") + config = config or ConstantOptimizerConfig() + target = np.asarray(y, dtype=float).reshape(-1) + if target.size == 0 or not np.all(np.isfinite(target)): + raise ValueError("y must contain at least one finite-only sample") + arrays = {name: np.asarray(value) for name, value in data.items()} + if num_nodes is None and any( + np.asarray(value).reshape(-1).size != target.size + for value in arrays.values() + ): + raise ValueError("all data arrays must have the same number of samples as y") + + expression, specs = _parameterize_literals(f.copy(), arrays) + if not specs: + return expression.copy() + initial = np.asarray([spec.initial for spec in specs], dtype=float) + lower = np.asarray([spec.lower for spec in specs], dtype=float) + upper = np.asarray([spec.upper for spec in specs], dtype=float) + scale = max(float(np.std(target)), float(np.max(np.abs(target))) * 1e-12, 1e-12) + invalid = np.full(target.size, 1e6, dtype=float) + + def prediction(raw: np.ndarray) -> np.ndarray | None: + try: + with np.errstate(all="ignore"): + value = np.asarray( + expression.evaluate( + arrays, + parameters=_unpack(raw, specs), + num_nodes=num_nodes, + ), + dtype=float, + ).reshape(-1) + if value.size == 1 and target.size != 1: + value = np.full(target.size, float(value[0])) + if value.size != target.size or not np.all(np.isfinite(value)): + return None + return value + except (ArithmeticError, FloatingPointError, KeyError, TypeError, ValueError): + return None + + def residual(raw: np.ndarray) -> np.ndarray: + value = prediction(raw) + return invalid if value is None else (value - target) / scale + + def loss(raw: np.ndarray) -> float: + value = prediction(raw) + return 1e100 if value is None else float(np.mean(np.square(value - target))) + + starts = [np.clip(initial, lower, upper)] + rng = np.random.default_rng(config.random_state) + for _ in range(max(0, config.n_restarts - 1)): + starts.append(rng.uniform(lower, upper)) + if config.use_global_search and len(specs) <= 12: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + global_result = differential_evolution( + loss, + list(zip(lower, upper)), + seed=config.random_state, + maxiter=config.differential_evolution_maxiter, + popsize=config.differential_evolution_popsize, + polish=False, + updating="immediate", + ) + starts.append(global_result.x) + + best = starts[0] + best_loss = loss(best) + for start in starts: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + result = least_squares( + residual, + start, + bounds=(lower, upper), + max_nfev=config.max_nfev, + xtol=1e-13, + ftol=1e-13, + gtol=1e-13, + ) + current_loss = loss(result.x) + if current_loss < best_loss: + best, best_loss = result.x, current_loss + + parameters = _unpack(best, specs) + literal_names = {spec.name for spec in specs if spec.literal} + return _bind(expression, parameters, literal_names) diff --git a/src/sr_harness/utils/df_to_3line.py b/src/sr_harness/utils/df_to_3line.py new file mode 100644 index 0000000000000000000000000000000000000000..453710769702026ebe9766bb26cce37697eed37f --- /dev/null +++ b/src/sr_harness/utils/df_to_3line.py @@ -0,0 +1,48 @@ +import pandas as pd +from .tag2ansi import tag2ansi + +def df_to_3line(df: pd.DataFrame, float_format: str | None = None): + idx = df.index + if not isinstance(idx, pd.MultiIndex): + idx = pd.MultiIndex.from_arrays([idx], names=df.index.names) + + rows, prev = [], None + for i, key in enumerate(idx): + ix = [] + for j, x in enumerate(key): + ix.append(str(x) if prev is None or key[:j + 1] != prev[:j + 1] else "") + values = [] + for column, value in df.iloc[i].items(): + if float_format is not None and pd.api.types.is_float_dtype(df[column]): + values.append(format(value, float_format)) + else: + values.append(str(value)) + rows.append(ix + values) + prev = key + + head = ["" if x is None else str(x) for x in idx.names] + [str(c) for c in df.columns] + data = [head] + rows + width = [max(len(r[i]) for r in data) for i in range(len(head))] + align = ["<"] * idx.nlevels + [">" if pd.api.types.is_numeric_dtype(df[c]) else "<" for c in df.columns] + line = tag2ansi('[gray]' + "=" * (sum(width) + 2 * (len(width) - 1)) + '[reset]') + sep = tag2ansi('[gray]' + "-" * (sum(width) + 2 * (len(width) - 1)) + '[reset]') + + def fmt(row, header=False): + out = [] + for i, x in enumerate(row): + x = f"{x:{align[i]}{width[i]}}" + if header or i < idx.nlevels: + x = tag2ansi('[blue]' + x + '[reset]') + out.append(x) + return " ".join(out) + + lines = [] + lines.append(line) + lines.append(fmt(head, header=True)) + lines.append(sep) + for i, row in enumerate(rows): + if i and idx.nlevels > 1 and idx[i][0] != idx[i - 1][0]: + lines.append(sep) + lines.append(fmt(row)) + lines.append(line) + return '\n'.join(lines) diff --git a/src/sr_harness/utils/factory_mixin.py b/src/sr_harness/utils/factory_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..258e66c0a69b8a6709d64a0b774525cfb4f6b0f1 --- /dev/null +++ b/src/sr_harness/utils/factory_mixin.py @@ -0,0 +1,138 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +from __future__ import annotations +from abc import ABCMeta +from typing import Dict, List, Type, TypeVar + +T = TypeVar('T', bound='FactoryMixin') + +class FactoryMeta(ABCMeta): + @property + def all_registered_classes(cls) -> List[Type]: + """Return the registry of all registered classes.""" + return list(cls.REGISTRY_DICT.values()) + + @property + def all_registered_names(cls) -> List[str]: + """Return the registry of all registered class names.""" + return list(cls.REGISTRY_DICT.keys()) + + +class FactoryMixin(metaclass=FactoryMeta): + """ + Mixin class that provides factory pattern capabilities for any class. + + Any class inheriting from this mixin gains the ability to: + 1. Register subclasses via @.register('name') + 2. Create instances via .create(config, *args, **kwargs) + + The base class is automatically registered as 'default' model. + + ═══════════════════════════════════════════════════════════════════════════ + INHERITANCE ORDER (IMPORTANT) + ═══════════════════════════════════════════════════════════════════════════ + + FactoryMixin should be placed BEFORE other base classes in the inheritance: + + class MyModel(FactoryMixin, nn.Module): + ... + + This ensures correct Method Resolution Order (MRO) so that: + 1. create() method resolves correctly + 2. Each subclass has its own independent registry + + ═══════════════════════════════════════════════════════════════════════════ + EXAMPLE + ═══════════════════════════════════════════════════════════════════════════ + + ```python + from sr_harness.utils import FactoryMixin + + class MyModel(FactoryMixin, nn.Module): + def __init__(self, config, tokenizer): + super().__init__() + self.config = config + + @MyModel.register('gcn') + class GCNModel(MyModel): + def __init__(self, config, tokenizer): + super().__init__(config, tokenizer) + # ... custom architecture + + # Usage - create() automatically handles model selection + config = MyConfig(model='gcn') + model = MyModel.create(config, tokenizer) + + # 'default' is automatically the base class + config = MyConfig(model='default') + model = MyModel.create(config, tokenizer) # Returns MyModel instance + ``` + """ + + REGISTRY_DICT: Dict[str, Type] = None # type: ignore + """ + Registry of model classes keyed by name. + + Direct subclasses of FactoryMixin get their own registry. + Grandchildren share the registry with their parent class. + """ + + def __init_subclass__(cls, **kwargs): + """Automatically called when a subclass is created. + + Only create a new registry for direct subclasses of FactoryMixin. + Grandchildren will share the same registry with their parent, + so registering on StatsTool also makes it visible to BaseTool. + """ + super().__init_subclass__(**kwargs) + # Check if FactoryMixin is a direct parent (not just ancestor) + if FactoryMixin in cls.__bases__: + cls.REGISTRY_DICT = {} + # else: inherit REGISTRY_DICT from parent (already via normal inheritance) + + @classmethod + def register(cls, name: str): + """ + Decorator to register a model subclass. + + Usage: + @MyModel.register('gcn') + class GCNModel(MyModel): + ... + """ + def decorator(model_cls: type) -> type: + cls.REGISTRY_DICT[name] = model_cls + model_cls.model_name = name + return model_cls + return decorator + + @classmethod + def create(cls: Type[T], name: str, *args, create_instance=True, **kwargs) -> T | Type[T]: + """ + Factory method to create instance based on config.model. + + Args: + config: Configuration object with model type specified in config.model + *args: Positional arguments passed to constructor + create_instance: + **kwargs: Keyword arguments passed to constructor + + Returns: + Instantiated object of the type specified in config.model + + Raises: + ValueError: If config.model is not found in REGISTRY_DICT + """ + # 'default' refers to the base class itself + if name == 'default': + model_class = cls + elif name in cls.REGISTRY_DICT: + model_class = cls.REGISTRY_DICT[name] + else: + available = ['default'] + list(cls.REGISTRY_DICT.keys()) + raise ValueError( + f"Unknown model type: '{name}'. " + f"Available models: {available}. " + f"Make sure the model class is imported (registration happens at import time)." + ) + + return model_class(*args, **kwargs) if create_instance else model_class diff --git a/src/sr_harness/utils/fix_parser.py b/src/sr_harness/utils/fix_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..9cd19ef00783f7da9ee310197445114e278a2745 --- /dev/null +++ b/src/sr_harness/utils/fix_parser.py @@ -0,0 +1,64 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +import argparse + +def add_minus_flags(parser: argparse.ArgumentParser): + """ + 自动为 argparse.ArgumentParser 中含有下划线的参数添加别名。例如: + --fix_existing -> 添加别名 --fix-existing + --augment_OD_num -> 添加别名 --augment-OD-num + """ + for action in parser._actions: + # 仅处理可选参数(以 '-' 开头的参数) + if not action.option_strings: + continue + aliases_to_add = [] + for opt in action.option_strings: + if opt.startswith('--') and '_' in opt: + new_alias = opt.replace('_', '-') + if new_alias not in action.option_strings: + aliases_to_add.append(new_alias) + for alias in aliases_to_add: + action.option_strings.append(alias) + parser._option_string_actions[alias] = action + return parser + + +def add_negation_flags(parser: argparse.ArgumentParser): + """ + 自动为 parser 中的 store_true 参数添加对应的 --no-xxx 选项。 + """ + args_to_add = [] + + # 建立现有 flag 索引,防止重复添加 + existing_flags = set() + for action in parser._actions: + existing_flags.update(action.option_strings) + for action in parser._actions: + if isinstance(action, argparse._StoreTrueAction): + # 为当前 action 收集所有可能的否定别名 + negation_aliases = [] + for option in action.option_strings: + if not option.startswith('--'): + continue + # 生成否定形式:--use_new_model -> --no-use_new_model + raw_name = option.removeprefix('--') + neg_opt = f'--no-{raw_name}' + # 只有当这个 flag 还不存在时才添加 + if neg_opt not in existing_flags: + negation_aliases.append(neg_opt) + # 如果生成了有效的否定别名,将它们打包准备添加 + if negation_aliases: + # 选取第一个选项名作为帮助文档显示的名称 + primary_name = action.option_strings[0].removeprefix('--') + args_to_add.append({ + 'options': negation_aliases, # 这里是一个列表 + 'dest': action.dest, + 'action': 'store_false', + 'default': action.default, + 'help': f"Disable {primary_name}" + }) + for arg in args_to_add: + parser.add_argument(*arg['options'], dest=arg['dest'], action=arg['action'], default=arg['default'], help=( + arg['help'] + )) + return parser diff --git a/src/sr_harness/utils/format_confusion_matrix.py b/src/sr_harness/utils/format_confusion_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..8adcfdc9c380b96e4c5774881e67fcf12b4855c8 --- /dev/null +++ b/src/sr_harness/utils/format_confusion_matrix.py @@ -0,0 +1,75 @@ +from __future__ import annotations + +from typing import Mapping, Optional + +__all__ = ["format_confusion_matrix"] + + +def color_by_error_rate(text: str, error_rate: float) -> str: + if error_rate >= 0.30: + return f"[red]{text}[reset]" + if error_rate >= 0.10: + return f"[orange]{text}[reset]" + if error_rate > 0.00: + return f"[yellow]{text}[reset]" + return f"[green]{text}[reset]" + + +def format_confusion_matrix( + matrix: Mapping[str, Mapping[str, int]] | None, + *, + max_size: int = 12, + topk: int = 10, +) -> Optional[str]: + if not matrix: + return "(no confusion matrix data)" + + labels = list(matrix) + seen_labels = set(labels) + for row in matrix.values(): + for label in row: + if label not in seen_labels: + labels.append(label) + seen_labels.add(label) + + row_totals = { + gt_label: sum(matrix.get(gt_label, {}).values()) + for gt_label in labels + } + + if len(labels) <= max_size: + short_labels = [label[:8] for label in labels] + width = max(5, min(8, max(len(label) for label in short_labels))) + lines = ["Confusion Matrix (GT rows x Pred cols)"] + lines.append(" " * (width + 1) + " ".join(f"{label:>{width}}" for label in short_labels)) + for gt_label, short_label in zip(labels, short_labels): + row = matrix.get(gt_label, {}) + row_total = row_totals[gt_label] + cells = [] + for pred_label in labels: + count = row.get(pred_label, 0) + if gt_label == pred_label: + cells.append(f"[green]{count:>{width}}[reset]") + else: + error_rate = 0.0 if row_total == 0 else count / row_total + cells.append(color_by_error_rate(f"{count:>{width}}", error_rate)) + lines.append(f"{short_label:>{width}} " + " ".join(cells)) + return "\n".join(lines) + + errors = [] + for gt_label, row in matrix.items(): + row_total = row_totals[gt_label] + if row_total == 0: + continue + for pred_label, count in row.items(): + if gt_label != pred_label and count > 0: + errors.append((count / row_total, count, gt_label, pred_label, row_total)) + errors.sort(key=lambda item: (item[0], item[1]), reverse=True) + if not errors: + return "Top Confusion Errors: none" + + lines = [f"Top {min(topk, len(errors))} Confusion Errors"] + for error_rate, count, gt_label, pred_label, row_total in errors[:topk]: + text = f"{gt_label} -> {pred_label}: {count}/{row_total} ({error_rate:.1%})" + lines.append(color_by_error_rate(text, error_rate)) + return "\n".join(lines) diff --git a/src/sr_harness/utils/format_pareto_front.py b/src/sr_harness/utils/format_pareto_front.py new file mode 100644 index 0000000000000000000000000000000000000000..f932a67ce86f5a2a8cc83a7737d54667f7b87675 --- /dev/null +++ b/src/sr_harness/utils/format_pareto_front.py @@ -0,0 +1,129 @@ +from __future__ import annotations +import pandas as pd +from typing import Literal +from collections.abc import Sequence +from .df_to_3line import df_to_3line + + +ObjectiveDirection = Literal["minimize", "maximize"] +Objective = tuple[str, ObjectiveDirection] + +DEFAULT_PARETO_BALANCE: tuple[Objective, Objective] = ( + ("validation.metrics.complexity", "minimize"), + ("validation.metrics.r2", "maximize"), +) +DEFAULT_PARETO_COLUMNS: tuple[str, ...] = ( + "validation.metrics.complexity", + "validation.metrics.r2", + "train.metrics.r2", + "formula", +) +DEFAULT_TITLE_MAPPING: dict[str, str] = { + "validation.metrics.complexity": "Complexity", + "validation.metrics.r2": "Validation R²", + "train.metrics.r2": "Train R²", + "formula": "Formula", +} + + +def _record_value(record: dict, path: str): + """Read a dotted field, treating split names as data_split_results children.""" + parts = path.split(".") + value = record + if parts[0] in {"train", "validation"}: + value = value.get("data_split_results", {}) + for part in parts: + if not isinstance(value, dict) or part not in value: + return None + value = value[part] + return value + + +def _format_value(value) -> str: + if value is None: + return "N/A" + if isinstance(value, float): + return f"{value:.6g}" + return str(value) + + +def _truncate_formula(formula, formula_max_length: int | None) -> str: + formula = str(formula) + if formula_max_length is None or len(formula) <= formula_max_length: + return formula + if formula_max_length < 4: + raise ValueError("formula_max_length must be at least 4 or None.") + return formula[: formula_max_length - 3] + "..." + + +def _validate_balance(balance: Sequence[Objective]) -> tuple[Objective, Objective]: + if len(balance) != 2: + raise ValueError("balance must contain exactly two objectives.") + normalized = tuple(balance) + for path, direction in normalized: + if not path: + raise ValueError("Pareto objective paths cannot be empty.") + if direction not in {"minimize", "maximize"}: + raise ValueError(f"Unsupported Pareto objective direction: {direction!r}.") + return normalized # type: ignore[return-value] + + +def format_pareto_front( + pareto_front: list[dict] | None, + concise: bool = False, + formula_max_length: int | None = None, + balance: Sequence[Objective] = DEFAULT_PARETO_BALANCE, + columns: Sequence[str] = DEFAULT_PARETO_COLUMNS, + title_mapping: dict[str, str] = DEFAULT_TITLE_MAPPING, +) -> str: + """Format candidate records from ``SRAgent.get_pareto_front``. + + Dotted split paths such as ``validation.metrics.r2`` are resolved below + each record's ``data_split_results`` mapping. ``formula`` and other + top-level fields are resolved directly from the record. + + Args: + - balance: records the two objectives used to construct the supplied + front and their directions. Set ``concise=True`` for an LLM-facing list; + the default renders a richer three-line table for human-facing logs. + - formula_max_length: preserves full formulas, while an integer + truncates formulas to that total length, including the ellipsis. + - title_mapping: maps column names to their display titles. + """ + balance = _validate_balance(balance) + columns = tuple(columns) + if not columns: + raise ValueError("columns cannot be empty.") + + if not pareto_front: + if concise: + return "(No Pareto front yet, call tools that can return candidate formulas to populate it.)" + return "(empty)" + + objective_text = "; ".join( + f"{direction} {title_mapping.get(path, path)}" for path, direction in balance + ) + rows = [] + for record in pareto_front: + row = {} + for column in columns: + value = _record_value(record, column) + if column == "formula": + value = _truncate_formula(value, formula_max_length) + row[column] = value + rows.append(row) + + if concise: + formatted_rows = [] + for index, row in enumerate(rows, 1): + fields = ", ".join( + f"{title_mapping.get(column, column)}={_format_value(row[column])}" + for column in columns + ) + formatted_rows.append(f"{index}. {fields}") + return f"Balance: {objective_text}.\n" + "\n".join(formatted_rows) + else: + frame = pd.DataFrame(rows, columns=columns) + frame.index = pd.Index(range(1, len(frame) + 1), name="#") + frame = frame.rename(columns={column: title_mapping.get(column, column) for column in frame.columns}) + return f"Balance: {objective_text}.\n{df_to_3line(frame, float_format='.6g')}" diff --git a/src/sr_harness/utils/lazy_loader.py b/src/sr_harness/utils/lazy_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..4b600201b2f84267a59ad4ebcc2fcf2e1b1fb14c --- /dev/null +++ b/src/sr_harness/utils/lazy_loader.py @@ -0,0 +1,35 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +import sys +import logging +import importlib +from typing import TYPE_CHECKING, Dict, Tuple + +__all__ = ["setup_lazy_imports", "TYPE_CHECKING"] + +def setup_lazy_imports(module_name: str, import_mapping: Dict[str, Tuple[str, str]]): + def __getattr__(name: str): + if name in import_mapping: + module_path, requires = import_mapping[name] + try: + module = importlib.import_module(module_path, package=module_name) + # 如果这个模块里有同名的属性,返回之 + # 如果没有,说明用户要的就是这个子模块本身,直接返回模块对象 + return getattr(module, name) if hasattr(module, name) else module + except ImportError as e: + raise ImportError( + f"Failed to import '{name}' from '{module_path}' in module '{module_name}' since missing optional dependency." + f"Try to run `pip install sr-harness[{requires}]` or `pip install sr-harness[all]` to install the required dependencies." + ) from e + + raise AttributeError(f"模块 {module_name!r} 中不存在属性 {name!r}") + + def __dir__(): + return list(import_mapping.keys()) + + # 获取调用者的 globals + caller_globals = sys._getframe(1).f_globals + + __all__ = [name for name in caller_globals.keys() if not name.startswith('_')] + __all__.extend(import_mapping.keys()) + + return __getattr__, __dir__, __all__ diff --git a/src/sr_harness/utils/log_exception.py b/src/sr_harness/utils/log_exception.py new file mode 100644 index 0000000000000000000000000000000000000000..618015a805ab5a3c5cdfeffa6cb94040ce99cdc0 --- /dev/null +++ b/src/sr_harness/utils/log_exception.py @@ -0,0 +1,12 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +import traceback +from .tag2ansi import tag2ansi + + +def log_exception(e: Exception, with_traceback=True) -> str: + """Format exception for logging.""" + return tag2ansi( + f"[red bold]{type(e).__name__}[reset]: " + f"[red]{str(e)}[reset]" + f"\n[gray]{traceback.format_exc() if with_traceback else ''}[reset]" + ) diff --git a/src/sr_harness/utils/logger.py b/src/sr_harness/utils/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..4db2398030c17c7f87c033e56157fb67fb6341b8 --- /dev/null +++ b/src/sr_harness/utils/logger.py @@ -0,0 +1,268 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +"""sr_harness 包的日志配置管理。 + +提供统一的日志配置接口,支持三种使用方式: + +**方式 1:SRAgent 快速配置(最简单)** + >>> from sr_harness import SRAgent + >>> agent = SRAgent(..., verbose=True) # 自动配置 DEBUG 级别日志 + >>> agent = SRAgent(..., verbose=True, save_path='logs/train.log') # + 文件保存 + +**方式 2:手动调用 setup_logging()(可指定 exp_name)** + >>> from sr_harness.utils import setup_logging + >>> setup_logging(info_level='debug', exp_name='MyExp', save_path='logs/train.log') + >>> agent = SRAgent(...) # 使用已配置的日志 + +**方式 3:高级用户完全自定义** + >>> import logging + >>> logger = logging.getLogger('sr_harness') + >>> logger.addHandler(my_custom_handler) # 用户自己的 handler + >>> setup_logging() # 会检测到自定义 handler 并跳过 + +所有 sr_harness 子模块通过 logging.getLogger(f'sr_harness.{__name__}') 获取 logger, +自动从父 logger 'sr_harness' 继承 handlers。 +""" +import re +import os +import sys +import time +import logging +from typing import Literal, Optional +from logging.handlers import RotatingFileHandler +from datetime import timedelta + +__all__ = ["setup_logging", "LogFormatter", "is_logging_configured"] + +# 全局状态:记录是否已配置 logging +_configured = False + + +def is_logging_configured() -> bool: + """检查 sr_harness 的 logging 是否已配置。 + + Returns: + True 如果已配置过 logging(通过 setup_logging 或 SRAgent.__init__) + """ + return _configured + + +class LogFormatter(logging.Formatter): + """带颜色的日志格式化器。 + + Attributes: + exp_name: 实验名称,显示在日志前缀中。 + colorful: 是否启用彩色输出。 + start_time: 日志开始时间,用于计算相对时间。 + """ + + color_dict = { + "DEBUG": "\033[0;37m{}\033[0m", + "TRACE": "\033[1;448;5;240m{}\033[0m", + "INFO": "\033[0;34m{}\033[0m", + "NOTE": "\033[1;38;5;46m{}\033[0m", + "WARNING": "\033[1;48;5;220m{}\033[0m", + "ERROR": "\033[0;30;41m{}\033[0m", + "CRITICAL": "\033[0;30;45m{}\033[0m", + } + + def __init__( + self, + exp_name: str = 'SRHarness', + colorful: bool = True, + start_time: Optional[float] = None, + time_format: str = "%b%d %H:%M:%S", + show_lineno_for: tuple = ("TRACE", "WARNING", "ERROR", "CRITICAL"), + ): + super().__init__() + self.exp_name = exp_name + self.colorful = colorful + self.start_time = time.time() if start_time is None else start_time + self.time_format = time_format + self.show_lineno_for = show_lineno_for + + def format(self, record) -> str: + prefixes = [ + self.exp_name, + record.name.split(".")[-1], # 显示 logger 名的最后一部分 + record.levelname[0], # D, I, N, W, E, C + time.strftime(self.time_format), + str(timedelta(seconds=record.created - self.start_time)), + ] + prefix = f"[{'|'.join([str(p) for p in prefixes if str(p).strip()])}]" + + if record.levelname in self.show_lineno_for: + path = os.path.relpath(record.pathname, os.getcwd()) + prefix += f" ({path}:{record.lineno})" + + message = record.getMessage() or "" + message = message.replace("\n", "\n" + " " * 8) # 保持多行日志对齐 + + if self.colorful: + return ( + self.color_dict.get(record.levelname, "{}").format(prefix) + + " " + + message + ) + else: + return prefix + " " + re.sub(r"\033\[[\d;]+m", "", message) + + +# 自定义日志级别:NOTE (between INFO and WARNING) 和 TRACE (between DEBUG and INFO) +def note(self, message, *args, **kwargs): + if self.isEnabledFor(25): + self._log(25, message, args, **kwargs) + + +def trace(self, message, *args, **kwargs): + if self.isEnabledFor(15): + self._log(15, message, args, **kwargs) + + +def _setup_custom_levels(): + """注册自定义日志级别 NOTE 和 TRACE。""" + if not hasattr(logging, 'NOTE'): + logging.addLevelName(25, "NOTE") + logging.Logger.note = note + logging.NOTE = 25 + + if not hasattr(logging, 'TRACE'): + logging.addLevelName(15, "TRACE") + logging.Logger.trace = trace + logging.TRACE = 15 + + +def _has_user_handlers() -> bool: + """检查 sr_harness logger 是否已有用户自定义的 handler。 + + 通过检查 handler 类型来判断: + - 库添加的 handler 会被标记(通过 _sr_harness_lib_handler 属性) + - 用户添加的 handler 没有这些标记 + - NullHandler 是库默认添加的,不算用户自定义 + + Returns: + True 如果检测到用户自定义 handler + """ + logger = logging.getLogger('sr_harness') + for handler in logger.handlers: + # NullHandler 是库默认添加的,不算用户自定义 + if isinstance(handler, logging.NullHandler): + continue + if not getattr(handler, '_sr_harness_lib_handler', False): + return True + return False + + +def setup_logging( + info_level: Literal["debug", "trace", "info", "note", "warning", "error", "critical"] = "info", + exp_name: str = 'SRHarness', + save_path: Optional[str] = None, + colorful: bool = True, + file_max_size_MB: float = 50.0, + file_backup_count: int = 100, + show_lineno_for_all_levels: bool = False, + force: bool = False, +) -> bool: + """配置 sr_harness 包的日志输出。 + + 这是配置 sr_harness 日志的主要入口。支持控制台彩色输出和文件保存。 + + Args: + info_level: 日志级别,默认 "info"。可选:"debug", "trace", "info", "note", "warning", "error", "critical"。 + exp_name: 实验名称,显示在日志前缀中,默认 "SRHarness"。 + save_path: 日志文件路径。None 表示不保存到文件。 + colorful: 是否启用控制台彩色输出,默认 True。 + file_max_size_MB: 单个日志文件最大大小(MB),默认 50。 + file_backup_count: 保留的备份文件数量,默认 100。 + show_lineno_for_all_levels: 是否对所有级别显示行号,默认 False。 + force: 是否强制重新配置(即使已有配置)。默认 False。 + + Returns: + True 如果成功配置,False 如果检测到用户自定义 handler 而跳过配置。 + + Example: + >>> from sr_harness.utils import setup_logging + >>> setup_logging(info_level='debug', exp_name='MyExp', save_path='logs/train.log') + """ + global _configured + + _setup_custom_levels() + + logger = logging.getLogger('sr_harness') + + # 检查是否有用户自定义 handler + if not force and _has_user_handlers(): + logger.warning( + "setup_logging detected user-configured handlers, skipping automatic configuration. " + "Set force=True to override." + ) + return False + + # 如果是 force 模式,清空已有 handlers + if force: + logger.handlers = [] + else: + # 非 force 模式,移除 NullHandler(如果存在) + logger.handlers = [h for h in logger.handlers if not isinstance(h, logging.NullHandler)] + + # 如果已配置且非 force 模式,直接返回 + if _configured and not force: + return True + + # 设置 logger 基础配置 + logger.setLevel(logging.DEBUG) # logger 本身放行所有级别 + logger.propagate = False + + # 准备 handler 级别 + show_lineno_for = ["TRACE", "WARNING", "ERROR", "CRITICAL"] + if show_lineno_for_all_levels: + show_lineno_for.extend(["DEBUG", "INFO", "NOTE"]) + + # 记录 start_time 用于相对时间显示 + start_time = time.time() + + # ========== 控制台 Handler ========== + console_handler = logging.StreamHandler(sys.stdout) + console_handler.stream.reconfigure(encoding='utf-8') + console_handler.setLevel(getattr(logging, info_level.upper())) + console_handler.setFormatter(LogFormatter( + exp_name=exp_name, + colorful=colorful, + start_time=start_time, + show_lineno_for=show_lineno_for, + )) + console_handler._sr_harness_lib_handler = True # 标记为库添加的 handler + logger.addHandler(console_handler) + + # ========== 文件 Handler ========== + if save_path: + os.makedirs(os.path.dirname(save_path), exist_ok=True) + file_handler = RotatingFileHandler( + save_path, + mode="a", + maxBytes=int(file_max_size_MB * 1024 * 1024), + backupCount=file_backup_count, + encoding="utf-8", + ) + file_handler.setLevel(logging.DEBUG) # 文件记录所有级别 + file_handler.setFormatter(LogFormatter( + exp_name=exp_name, + colorful=False, # 文件输出不带颜色 + start_time=start_time, + show_lineno_for=show_lineno_for, + )) + file_handler._sr_harness_lib_handler = True # 标记为库添加的 handler + logger.addHandler(file_handler) + + _configured = True + logger.debug(f"Logging configured: level={info_level}, exp_name={exp_name}, save_path={save_path}") + + return True + + +# 默认添加 NullHandler,避免 "No handler found" 警告 +# NullHandler 是库添加的,不会阻止后续 setup_logging() 的自动配置 +_root_logger = logging.getLogger('sr_harness') +_null_handler = logging.NullHandler() +_null_handler._sr_harness_lib_handler = True # 标记为库添加的 handler +_root_logger.addHandler(_null_handler) +_root_logger.propagate = False diff --git a/src/sr_harness/utils/metrics.py b/src/sr_harness/utils/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..0cc09092e63606a6a8068e73b6c3cae4efe9a44b --- /dev/null +++ b/src/sr_harness/utils/metrics.py @@ -0,0 +1,30 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +import numpy as np + +__all__ = [ + "R2_score", + "RMSE_score", + "sMAPE_score", + "MAPE_score", + "MAE_score", +] + + +def R2_score(true, pred): + return 1 - np.mean((true - pred) ** 2) / np.var(true) + + +def RMSE_score(true, pred): + return np.sqrt(np.mean((true - pred) ** 2)) + + +def sMAPE_score(true, pred): + return 2 * np.mean(np.abs(true - pred) / (np.abs(true) + np.abs(pred) + 1e-6)) + + +def MAPE_score(true, pred): + return np.mean(np.abs(true - pred) / (np.abs(true) + 1e-6)) + + +def MAE_score(true, pred): + return np.mean(np.abs(true - pred)) diff --git a/src/sr_harness/utils/model_store.py b/src/sr_harness/utils/model_store.py new file mode 100644 index 0000000000000000000000000000000000000000..6f2d4958d9c58d96a72a8c77571cd07d495eaaea --- /dev/null +++ b/src/sr_harness/utils/model_store.py @@ -0,0 +1,154 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""Utilities for uploading and downloading model checkpoints.""" +from __future__ import annotations +import os +import shutil +import logging +import requests +from pathlib import Path +from typing import Literal, Optional +from .log_exception import log_exception + + +_logger = logging.getLogger(f"sr_harness.{__name__}") +__all__ = ["get_default", "download_model", "upload_model"] +DEFAULT_GITHUB_REPO = "yuzhTHU/SRHarness" +DEFAULT_GITHUB_RELEASE_TAG = "sr-agent-models" +GITHUB_HEADER = { + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", +} + + +class ModelStoreError(RuntimeError): + """Raised when a model store operation fails.""" + + +def get_default(key: Literal["repo", "release_tag", "token"]) -> Optional[str]: + if key == "repo": + return os.getenv("SR_AGENT_GITHUB_REPO", DEFAULT_GITHUB_REPO) + elif key == "release_tag": + return os.getenv("SR_AGENT_GITHUB_RELEASE_TAG", DEFAULT_GITHUB_RELEASE_TAG) + elif key == "token": + return os.getenv("GITHUB_TOKEN") + else: + raise ValueError(f"Invalid key: {key}") + + +def download_model(name: str, checkpoint: str, repo: str = None, release_tag: str = None, token: str = None) -> Path: + """ 从 Github 的 {repo} 仓库的 {release_tag} 版本中下载名为 {name} 的模型文件,并保存到本地路径 {checkpoint}。 """ + if repo is None: repo = get_default("repo") + if release_tag is None: release_tag = get_default("release_tag") + if token is None: token = get_default("token") + + checkpoint_path = Path(checkpoint).expanduser() + checkpoint_path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = checkpoint_path.with_suffix(checkpoint_path.suffix + ".downloading") + + try: + download_url = get_download_url(repo, release_tag, name, token) + headers = GITHUB_HEADER | {"Authorization": f"Bearer {token}", "Accept": "application/octet-stream"} + with requests.get(download_url, headers=headers, stream=True, timeout=120) as response: + raise_for_status(response, "download model asset") + with open(tmp_path, "wb") as f: + for chunk in response.iter_content(chunk_size=1024 * 1024): + if chunk: f.write(chunk) + shutil.move(str(tmp_path), checkpoint_path) + except Exception as e: + _logger.error(f"Failed to download model {name} from {repo}@{release_tag}: {log_exception(e, with_traceback=False)}") + checkpoint_path = None + finally: + tmp_path.unlink(missing_ok=True) + return checkpoint_path + + +def upload_model(name: str, checkpoint: str, repo: str = None, release_tag: str = None, token: str = None) -> dict: + """ 从本地路径 {checkpoint} 上传模型文件到 Github 的 {repo} 仓库的 {release_tag} 版本,命名为 {name}。 """ + if repo is None: repo = get_default("repo") + if release_tag is None: release_tag = get_default("release_tag") + if token is None: token = get_default("token") + + checkpoint_path = Path(checkpoint).expanduser() + if not checkpoint_path.exists(): + raise FileNotFoundError(f"Model checkpoint not found: {checkpoint_path}") + if not token: + raise ModelStoreError("GITHUB_TOKEN is required to upload model checkpoints to GitHub Releases.") + + try: + upload_url = get_upload_url(repo, release_tag, name, token) + headers = GITHUB_HEADER | {"Content-Type": "application/octet-stream", "Authorization": f"Bearer {token}"} + with open(checkpoint_path, "rb") as f: + with requests.post(upload_url, params={"name": name}, headers=headers, data=f, timeout=300) as response: + raise_for_status(response, "upload model asset") + return response.json() + except Exception as e: + raise ModelStoreError(f"Failed to upload model {name} to {repo}@{release_tag}: {e}") from e + + +def get_download_url(repo: str, release_tag: str, name: str, token: str = None) -> str: + url = f"https://api.github.com/repos/{repo}/releases/tags/{release_tag}" + headers = GITHUB_HEADER | {"Authorization": f"Bearer {token}"} + with requests.get(url, headers=headers, timeout=60) as response: + raise_for_status(response, "get release for download") + release = response.json() or {} + for asset in release.get("assets", []): + if asset.get("name") == name: + return asset['url'] + else: + raise ModelStoreError(f"Model asset not found in {repo}@{release_tag}: {name}") + + +def get_upload_url(repo: str, release_tag: str, name: str, token: str) -> str: + release = None + headers = GITHUB_HEADER | {"Authorization": f"Bearer {token}"} + + # 检索已有 Release + if True: + url = f"https://api.github.com/repos/{repo}/releases/tags/{release_tag}" + with requests.get(url, headers=headers, timeout=60) as response: + if response.status_code == 404: + release = None + else: + raise_for_status(response, "get release for upload") + release = response.json() + + # 若 Release 不存在则创建 + if release is None: + url = f"https://api.github.com/repos/{repo}/releases" + data = { + "tag_name": release_tag, "name": release_tag, + "body": "Model checkpoints used by SRHarness.", + "draft": False, "prerelease": False, + } + with requests.post(url, headers=headers, json=data, timeout=60) as response: + raise_for_status(response, "create GitHub release") + release = response.json() + + # 删除已有或刚刚创建的 Release + for asset in release.get("assets", []): + if asset.get("name") == name: + url = f"https://api.github.com/repos/{repo}/releases/assets/{asset['id']}" + with requests.delete(url, headers=headers, timeout=60) as response: + raise_for_status(response, "delete existing model asset") + + # 返回上传 URL + return release["upload_url"].split("{", 1)[0] + + +def raise_for_status(response: requests.Response, action: str) -> None: + if response.ok: + return + try: + detail = response.json() + except ValueError: + detail = response.text + hint = "" + if response.status_code == 403 and isinstance(detail, dict): + message = str(detail.get("message", "")) + if "Resource not accessible by personal access token" in message: + hint = ( + " Hint: make sure the token is authorized for this repository, " + "has Contents: Read and write permission, and has been approved/SSO-authorized " + "by the organization if required." + ) + raise ModelStoreError(f"Failed to {action}: HTTP {response.status_code}: {detail}.{hint}") diff --git a/src/sr_harness/utils/nn/__init__.py b/src/sr_harness/utils/nn/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b8aa87b23245d70faeb9950d8a139ff8562c8dd0 --- /dev/null +++ b/src/sr_harness/utils/nn/__init__.py @@ -0,0 +1,3 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +from .gnn import GNN +from .positional_encoding import PositionalEncoding diff --git a/src/sr_harness/utils/nn/gnn.py b/src/sr_harness/utils/nn/gnn.py new file mode 100644 index 0000000000000000000000000000000000000000..a398699029eb3256a3ce685f6a715a67e4b07803 --- /dev/null +++ b/src/sr_harness/utils/nn/gnn.py @@ -0,0 +1,113 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +import torch +import torch.nn as nn +import torch.nn.functional as F + +class GNNLayer(nn.Module): + def __init__(self, node_dim, edge_dim, out_dim, residual=False): + super().__init__() + self.node_dim = node_dim + self.edge_dim = edge_dim + self.out_dim = out_dim + self.residual = residual + + self.update_node = nn.Sequential( + nn.Linear(node_dim * 2 + edge_dim, out_dim), + nn.ReLU(), + nn.Linear(out_dim, out_dim) + ) + self.update_edge = nn.Sequential( + nn.Linear(node_dim * 2 + edge_dim, out_dim), + nn.ReLU(), + nn.Linear(out_dim, out_dim) + ) + if residual: + self.shortcut_node = nn.Linear(node_dim, out_dim) \ + if node_dim != out_dim else nn.Identity() + self.shortcut_edge = nn.Linear(edge_dim, out_dim) \ + if edge_dim != out_dim else nn.Identity() + + # ⚠️ 移除了 A,并将 G 改名为 edge_list 以防混淆 + def forward(self, v, e, edge_list, num_nodes): + """ + - v: [N, V, node_dim] (N: SampleNum, V: TotalNodes) + - e: [N, E, edge_dim] (N: SampleNum, E: TotalEdges) + - edge_list: [2, E] (第0行: source, 第1行: target) + - num_nodes: [N] (每个样本的节点数量) + - return: [N, V, out_dim], [N, E, out_dim] + """ + N, V, _ = v.shape + _, E, _ = e.shape + + # 1. 获取源节点和目标节点的索引: [E] + sour_idx = edge_list[0] + term_idx = edge_list[1] + + # 2. 提取特征: [N, E, node_dim] + v_sour = v[:, sour_idx, :] + v_term = v[:, term_idx, :] + x = torch.cat([v_sour, v_term, e], dim=-1) + + # 3. 计算节点消息 + y = self.update_node(x) # [N, E, out_dim] + + # 4. 消息聚合 (Scatter Add) + update_v = torch.zeros(N, V, self.out_dim, device=y.device) + # 调整 target index 的形状以匹配 src (y) + # term_idx.view(1, -1, 1) -> [1, E, 1] -> 展开为 [N, E, out_dim] + scatter_idx = term_idx.view(1, -1, 1).expand(N, E, self.out_dim) + update_v.scatter_add_(dim=1, index=scatter_idx, src=y) + + # 🌟 5. 核心修改:动态计算稀疏度数 (Degree) + # torch.bincount 可以统计 term_idx 中每个节点作为目标节点出现了多少次 + degree = torch.bincount(term_idx, minlength=V).clamp(min=1).float() # [V,] + + # 将 degree 调整为 [1, V, 1] 以支持广播除法 + update_v = update_v / degree.view(1, V, 1) # [N, V, out_dim] + + # 6. 计算边更新 + update_e = self.update_edge(x) # [N, E, out_dim] + + if self.residual: + update_v = update_v + self.shortcut_node(v) + update_e = update_e + self.shortcut_edge(e) + + return F.relu(update_v), F.relu(update_e) + + +class GNN(nn.Module): + def __init__(self, d_emb, n_layers, node_dim, edge_dim, dropout): + super(GNN, self).__init__() + self.d_emb = d_emb + self.n_layers = n_layers + self.node_dim = node_dim + self.edge_dim = edge_dim + + self.GNN_layers = nn.ModuleList([GNNLayer(node_dim, edge_dim, d_emb)] + \ + [GNNLayer(d_emb, d_emb, d_emb) for _ in range(n_layers - 1)]) + self.dropout = nn.Dropout(p=dropout) + + def fwd(self, v, e, edge_list, num_nodes): + for net in self.GNN_layers: + v, e = net(v, e, edge_list, num_nodes) + v = self.dropout(v) + e = self.dropout(e) + return v, e + + def forward(self, v, e, edge_list, num_nodes, chunk_size=None): + if chunk_size is None or chunk_size >= v.size(0): + return self.fwd(v, e, edge_list, num_nodes) + + v_out_list = [] + e_out_list = [] + for v_chunk, e_chunk in zip( + torch.split(v, chunk_size, dim=0), + torch.split(e, chunk_size, dim=0) + ): + v_chunk_out, e_chunk_out = self.fwd(v_chunk, e_chunk, edge_list, num_nodes) + v_out_list.append(v_chunk_out) + e_out_list.append(e_chunk_out) + v_final = torch.cat(v_out_list, dim=0) + e_final = torch.cat(e_out_list, dim=0) + + return v_final, e_final diff --git a/src/sr_harness/utils/nn/positional_encoding.py b/src/sr_harness/utils/nn/positional_encoding.py new file mode 100644 index 0000000000000000000000000000000000000000..a9fb6c6e78e320bff0c403b66eb5237e52e8f662 --- /dev/null +++ b/src/sr_harness/utils/nn/positional_encoding.py @@ -0,0 +1,22 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +import torch +import torch.nn as nn +import torch.nn.functional as F +from math import log + +class PositionalEncoding(nn.Module): + # batch_first=True + def __init__(self, d_emb, dropout=0.2, max_len=5000): + super(PositionalEncoding, self).__init__() + self.dropout = nn.Dropout(p=dropout) + pe = torch.zeros(max_len, d_emb) + position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) + div_term = torch.exp(torch.arange(0, d_emb, 2, dtype=torch.float) * (-log(10000.0) / d_emb)) + pe[:, 0::2] = torch.sin(position * div_term) + pe[:, 1::2] = torch.cos(position * div_term) + pe = pe.unsqueeze(0) # (1, max_len, d_emb) + self.register_buffer('pe', pe) + + def forward(self, x): + x = x + self.pe[:, :x.shape[1], :] + return self.dropout(x) diff --git a/src/sr_harness/utils/openat2.py b/src/sr_harness/utils/openat2.py new file mode 100644 index 0000000000000000000000000000000000000000..031eb330d410b8bb8a47b64624d26dde4a80c0c2 --- /dev/null +++ b/src/sr_harness/utils/openat2.py @@ -0,0 +1,63 @@ +"""Minimal Linux ``openat2`` bindings for path-constrained file access.""" + +from __future__ import annotations + +import ctypes +import errno +import os +import platform +from pathlib import Path + +_LIBC = ctypes.CDLL(None, use_errno=True) +_SYS_OPENAT2 = {"x86_64": 437, "aarch64": 437} +_RESOLVE_NO_MAGICLINKS = 0x02 +_RESOLVE_NO_SYMLINKS = 0x04 +_RESOLVE_BENEATH = 0x08 + + +class _OpenHow(ctypes.Structure): + _fields_ = [ + ("flags", ctypes.c_uint64), + ("mode", ctypes.c_uint64), + ("resolve", ctypes.c_uint64), + ] + + +def open_beneath( + root: Path, + relative_path: str | Path, + *, + disallow_symlinks: bool = False, + flags: int = os.O_RDONLY | os.O_CLOEXEC, +) -> int: + """Atomically open a path without allowing resolution above ``root``.""" + syscall_number = _SYS_OPENAT2.get(platform.machine()) + if syscall_number is None: + raise OSError(errno.ENOSYS, "openat2 is unsupported on this architecture") + root_fd = os.open(root, os.O_PATH | os.O_DIRECTORY | os.O_CLOEXEC) + try: + resolve = _RESOLVE_BENEATH | _RESOLVE_NO_MAGICLINKS + if disallow_symlinks: + resolve |= _RESOLVE_NO_SYMLINKS + how = _OpenHow(flags=flags, mode=0, resolve=resolve) + result = int( + _LIBC.syscall( + syscall_number, + root_fd, + ctypes.c_char_p(os.fsencode(relative_path or ".")), + ctypes.byref(how), + ctypes.sizeof(how), + ) + ) + if result < 0: + code = ctypes.get_errno() + if code in {errno.EXDEV, errno.ELOOP}: + raise PermissionError( + errno.EACCES, + "Path resolves outside its authorized root", + relative_path, + ) + raise OSError(code, os.strerror(code), relative_path) + return result + finally: + os.close(root_fd) diff --git a/src/sr_harness/utils/parse_json_with_template.py b/src/sr_harness/utils/parse_json_with_template.py new file mode 100644 index 0000000000000000000000000000000000000000..5a9002c12294d8d041d59f852fd0954579d7aa68 --- /dev/null +++ b/src/sr_harness/utils/parse_json_with_template.py @@ -0,0 +1,154 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +"""Template-guided JSON parsing for LLM outputs.""" + +from __future__ import annotations + +import ast +import json +import re +from collections.abc import Mapping +from typing import Any + +import yaml + + +def parse_json_with_template(text: str, template: Any) -> Any: + """Parse an LLM response and coerce it to the shape described by template. + + Template examples: + {"score": float, "detail": [{"claim_id": str, "score": float, "detail": str}]} + {"equation_list": [str], "detail": str} + [{"key1": float, "key2": str}] + """ + errors = [] + for candidate in _candidate_texts(text): + for loader in (_loads_json, _loads_python_literal, _loads_yaml): + try: + return _coerce_to_template(loader(candidate), template) + except Exception as exc: + errors.append(exc) + raise ValueError(f"Could not parse response with template. Last errors: {errors[-3:]}") + + +def _candidate_texts(text: str) -> list[str]: + text = text.strip() + candidates = [] + + fenced_blocks = re.findall(r"```(?:json|python)?\s*(.*?)\s*```", text, flags=re.S | re.I) + candidates.extend(block.strip() for block in fenced_blocks if block.strip()) + + candidates.extend(_balanced_snippets(text)) + if text: + candidates.append(text) + + deduped = [] + for candidate in candidates: + if candidate not in deduped: + deduped.append(candidate) + return deduped + + +def _balanced_snippets(text: str) -> list[str]: + snippets = [] + stack = [] + start = None + quote = None + escaped = False + + pairs = {"{": "}", "[": "]"} + opens = set(pairs) + closes = set(pairs.values()) + + for idx, char in enumerate(text): + if quote: + if escaped: + escaped = False + elif char == "\\": + escaped = True + elif char == quote: + quote = None + continue + + if char in ("'", '"'): + quote = char + continue + + if char in opens: + if not stack: + start = idx + stack.append(pairs[char]) + elif char in closes and stack: + if char != stack[-1]: + stack.clear() + start = None + continue + stack.pop() + if not stack and start is not None: + snippets.append(text[start : idx + 1]) + start = None + + return snippets + + +def _loads_json(text: str) -> Any: + return json.loads(text) + + +def _loads_python_literal(text: str) -> Any: + return ast.literal_eval(text) + + +def _loads_yaml(text: str) -> Any: + return yaml.safe_load(text) + + +def _coerce_to_template(value: Any, template: Any) -> Any: + if template is Any: + return value + + if isinstance(template, Mapping): + if not isinstance(value, Mapping): + raise TypeError(f"Expected mapping, got {type(value).__name__}") + return {key: _coerce_to_template(value[key], child) for key, child in template.items()} + + if isinstance(template, list): + if not isinstance(value, list): + raise TypeError(f"Expected list, got {type(value).__name__}") + if len(template) == 0: + return value + if len(template) != 1: + if len(value) != len(template): + raise ValueError(f"Expected list of length {len(template)}, got {len(value)}") + return [_coerce_to_template(item, child) for item, child in zip(value, template)] + return [_coerce_to_template(item, template[0]) for item in value] + + if template is float: + return _coerce_float(value) + if template is int: + return int(value) + if template is str: + return str(value) + if template is bool: + return _coerce_bool(value) + if isinstance(template, type): + return template(value) + + return value + + +def _coerce_float(value: Any) -> float: + if isinstance(value, str): + value = value.strip() + if value.endswith("%"): + return float(value[:-1]) / 100.0 + return float(value) + + +def _coerce_bool(value: Any) -> bool: + if isinstance(value, str): + lowered = value.strip().lower() + if lowered in {"true", "yes", "y", "1"}: + return True + if lowered in {"false", "no", "n", "0"}: + return False + return bool(value) diff --git a/src/sr_harness/utils/plot.py b/src/sr_harness/utils/plot.py new file mode 100644 index 0000000000000000000000000000000000000000..c9e49dec74f0ccfbcf954eb27981834a66f25344 --- /dev/null +++ b/src/sr_harness/utils/plot.py @@ -0,0 +1,369 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +import os +import re +import numpy as np +import matplotlib.pyplot as plt +import matplotlib.colors as mcolors +from typing import List, Dict, Literal, Tuple + + +def get_fig(RN, CN, FW=None, FH=None, AW=None, AH=None, A_ratio=1.0, + LM=3, RM=3, TM=3, BM=3, HS=None, VS=None, dpi=300, + fontsize=7, lw=0.5, gridspec=False, **kwargs): + # 基础字体和尺寸 + plt.rcParams['font.family'] = kwargs.get('font_family', 'Arial') + plt.rcParams['font.size'] = fontsize + # --- 字体大小设置 (Font Sizes) --- + plt.rcParams['axes.labelsize'] = fontsize + plt.rcParams['axes.titlesize'] = fontsize + plt.rcParams['xtick.labelsize'] = fontsize * (5/7) + plt.rcParams['ytick.labelsize'] = fontsize * (5/7) + plt.rcParams['legend.fontsize'] = fontsize * (5/7) + plt.rcParams['figure.titlesize'] = fontsize + # --- 线条宽度设置 (Line Widths) --- + plt.rcParams['lines.linewidth'] = lw + plt.rcParams['axes.linewidth'] = lw + plt.rcParams['xtick.major.width'] = lw + plt.rcParams['ytick.major.width'] = lw + plt.rcParams['xtick.minor.width'] = lw + plt.rcParams['ytick.minor.width'] = lw + plt.rcParams['grid.linewidth'] = lw + plt.rcParams['patch.linewidth'] = lw + # --- 导出设置 (Export Settings) --- + plt.rcParams['pdf.fonttype'] = 42 + plt.rcParams['svg.fonttype'] = 'none' + + LM = LM * fontsize / 72 + RM = RM * fontsize / 72 + TM = TM * fontsize / 72 + BM = BM * fontsize / 72 + HS = HS * fontsize / 72 if HS is not None else LM + VS = VS * fontsize / 72 if VS is not None else TM + + if AW is not None: + AW /= 2.54 + FW = LM + CN * AW + (CN - 1) * HS + RM + if AH is not None: + AH /= 2.54 + FH = TM + RN * AH + (RN - 1) * VS + BM + A_ratio = AW / AH + else: + AH = AW / A_ratio + FH = TM + RN * AH + (RN - 1) * VS + BM + elif AH is not None: + AH /= 2.54 + AW = AH * A_ratio + FH = TM + RN * AH + (RN - 1) * VS + BM + FW = LM + CN * AW + (CN - 1) * HS + RM + elif FW is not None: + FW /= 2.54 + AW = (FW - LM - RM - (CN - 1) * HS) / CN + if FH is not None: + FH /= 2.54 + AH = (FH - TM - BM - (RN - 1) * VS) / RN + A_ratio = AW / AH + else: + AH = AW / A_ratio + FH = TM + RN * AH + (RN - 1) * VS + BM + elif FH is not None: + FH /= 2.54 + AH = (FH - TM - BM - (RN - 1) * VS) / RN + AW = AH * A_ratio + FW = LM + CN * AW + (CN - 1) * HS + RM + + figinfo = dict(RN=RN, CN=CN, FW=FW, FH=FH, AW=AW, AH=AH, + LM=LM, RM=RM, TM=TM, BM=BM, HS=HS, VS=VS, + r_AW=AW/FW, r_AH=AH/FH, r_HS=HS/FW, r_VS=VS/FH, + r_LM=LM/FW, r_RM=RM/FW, r_TM=TM/FH, r_BM=BM/FH, + fontsize=fontsize, lw=lw, + top_box=(LM/FW, 1-TM/FH, 1-(LM+RM)/FW, TM/FH), + bottom_box=(LM/FW, 0, 1-(LM+RM)/FW, BM/FH), + right_box=(1-RM/FW, BM/FH, RM/FW, 1-(TM+BM)/FH), + left_box=(0, BM/FH, LM/FW, 1-(TM+BM)/FH), + ) + if gridspec: + fig = plt.figure(figsize=(FW, FH), dpi=dpi, **kwargs) + gs = fig.add_gridspec(RN, CN, wspace=HS/AW, hspace=VS/AH, left=LM/FW, right=1-RM/FW, top=1-TM/FH, bottom=BM/FH) + return figinfo, fig, gs + else: + fig, axes = plt.subplots(RN, CN, figsize=(FW, FH), dpi=dpi, **kwargs) + fig.subplots_adjust(left=LM/FW, right=1-RM/FW, top=1-TM/FH, bottom=BM/FH, wspace=HS/AW, hspace=VS/AH) + axes = axes.ravel() if RN * CN > 1 else [axes] + return figinfo, fig, axes + + +def plot_resilience(f:callable, extent=(0, 1, 0, 1), gridnum=(1000, 1000), cmap=None, norm=None, ax=None, reset_xylim=True, lw=1): + """ + 绘制二维函数的韧性 + - f: 二维函数,如 lambda x, y: y - 3*y**2 - y**3 + x*y**3 + - extent: 函数定义域 (xmin, xmax, ymin, ymax) + - gridnum: 网格数量 (xnum, ynum) + --- + Example: + >>> f = lambda x, y: y - 3*y**2 - y**3 + x*y**3 + >>> plot_resilience(f, ax=axes[0], extent=(0, 5, 0, 5)) + >>> f = lambda x, y: np.sin(np.sqrt(x**2 + y ** 2)) + >>> plot_resilience(f, ax=axes[1], extent=(-4*np.pi, 4*np.pi, -4*np.pi, 4*np.pi)) + >>> f = lambda x, y: np.sin(np.sqrt(x ** 2 + y ** 2)) * x - y * np.cos(np.sqrt(x ** 2 + y ** 2)) + >>> plot_resilience(f, ax=axes[2], extent=(-4*np.pi, 4*np.pi, -4*np.pi, 4*np.pi)) + """ + if cmap is None: cmap = mcolors.LinearSegmentedColormap.from_list('my_bwr', ['#74b9ff', 'white', '#ff7675']) + if norm is None: norm = mcolors.SymLogNorm(linthresh=0.01, linscale=0.01, vmin=-1, vmax=1) + if ax is None: ax = plt.gca() + + def plot1(x, y): + ax.plot(x, y, 'black', linewidth=lw, linestyle='-', solid_capstyle='round') + + def plot2(x, y): + ax.plot(x, y, 'gray', linewidth=lw, linestyle=(3, (3, 1)), solid_capstyle='round') + + xmin, xmax, ymin, ymax = extent + xnum, ynum = gridnum + x = np.linspace(xmin, xmax, xnum) + y = np.linspace(ymin, ymax, ynum) + x, y = np.meshgrid(x, y) + z = f(x, y) + + ax.imshow(z, origin='lower', aspect='auto', cmap=cmap, norm=norm, zorder=0, extent=(xmin, xmax, ymin, ymax)) + + contours = ax.contour(x, y, z, levels=[0], linewidths=0) + for coll in contours.collections: coll.remove() + + dzdy = np.gradient(z)[0] + for coll in contours.collections: + for path in coll.get_paths(): + saved = [] + sign = None + for (x0, y0) in path.vertices: + saved.append((x0, y0)) + x_idx = int(np.floor((x0-xmin) / (xmax-xmin) * (xnum - 1))) + y_idx = int(np.floor((y0-ymin) / (ymax-ymin) * (ynum - 1))) + if sign is None: sign = np.sign(dzdy[y_idx, x_idx]) + if np.sign(dzdy[y_idx, x_idx] * sign) < 0: + if sign < 0: plot1(*np.array(saved).T) + else: plot2(*np.array(saved).T) + sign *= -1 + saved = [] + else: + pass + if saved: + if sign < 0: plot1(*np.array(saved).T) + else: plot2(*np.array(saved).T) + + if reset_xylim: + scale = lambda min, max, ratio=0.1: (min - (max - min) * ratio / 2, max + (max - min) * ratio / 2) + ax.set_xlim(*scale(xmin, xmax)) + ax.set_ylim(*scale(ymin, ymax)) + + +class EqualizeNormalize(mcolors.Normalize): + """ 按分布而非值进行归一化 """ + def __init__(self, samples, clip=False): + super().__init__(vmin=samples.min(), vmax=samples.max(), clip=clip) + hist, bin_edges = np.histogram(samples.flatten(), bins=256, range=(self.vmin, self.vmax), density=True) + cdf = hist.cumsum() + cdf = (cdf - cdf.min()) / (cdf.max() - cdf.min()) + self.bin_edges = bin_edges + self.cdf = cdf + def __call__(self, value, clip=False): + value = np.array(value) + return np.ma.masked_array(np.interp(value.flatten(), self.bin_edges[:-1], self.cdf).reshape(value.shape)) + def inverse(self, value): + value = np.array(value) + return np.ma.masked_array(np.interp(value.flatten(), self.cdf, self.bin_edges[:-1]).reshape(value.shape)) + + +def plotOD(ax, source:List[str], destination:List[str], flow:List[float], location:Dict[str, Tuple[float, float]], + linetype:Literal['straight', 'parabola', 'rotated_parabola', 'projected_parabola']='straight', N=100, zorder=10, + **kwargs): + """ 绘制OD流量 """ + cmap = mcolors.LinearSegmentedColormap.from_list('cmap', ['#0308F8', '#FD0B1B', '#ffff00'], gamma=5.0) + norm = EqualizeNormalize(flow.values) + t = np.linspace(0, 1, N) + ignored = set(list(source) + list(destination)) - set(location.keys()) + if ignored: print(f'\033[33mWarning: {ignored} are not in location\033[0m') + for (s, d, f) in zip(source, destination, flow): + if s not in location or d not in location: continue + p1 = np.array(location[s])[:, np.newaxis] # (2, 1) + p2 = np.array(location[d])[:, np.newaxis] # (2, 1) + if linetype == 'straight': + ax.plot(*(p1 * (1 - t) + p2 * t), lw=0.05+0.1*norm(f), alpha=0.4+0.4*norm(f), color=cmap(norm(f)), zorder=zorder+norm(f), rasterized=kwargs.get('rasterized', False)) + elif linetype == 'parabola': + y_scale = locals().get('y_scale', np.diff(ax.get_ylim())[0]) + xy = p1 * (1-t) + p2 * t + np.array([[0], [1]]) * 4 * t * (1-t) * norm(f) * y_scale * kwargs.get('scale', 0.1) + ax.plot(*xy, lw=0.05+0.1*norm(f), alpha=0.4+0.4*norm(f), color=cmap(norm(f)), zorder=zorder+norm(f), rasterized=kwargs.get('rasterized', False)) + elif linetype == 'rotated_parabola': + height = 0.5 * norm(f) + C, S = (p2 - p1)[:, 0] + A = np.array([[C, -S], [S, C]]) / 2 + if kwargs.get('adjust_up', None) and (C < 0): A = -A + if kwargs.get('adjust_down', None) and (C > 0): A = -A + xy = A @ np.array([2 * t - 1, height * 4 * t * (1 - t)]) + 0.5 * (p1 + p2) + ax.plot(*xy, lw=0.05+0.1*norm(f), alpha=0.4+0.4*norm(f), color=cmap(norm(f)), zorder=zorder+norm(f), rasterized=kwargs.get('rasterized', False)) + elif linetype == 'projected_parabola': + p0 = locals().get('p0', np.array(kwargs.get('p0', [np.mean(ax.get_xlim()), np.mean(ax.get_ylim())]))[:, np.newaxis]) + D = kwargs.get('D', 10) + xy = p0 + D * (p1 * (1-t) + p2 * t - p0) / (D - 4*t*(1 - t)*(norm(f) + 1)) + ax.plot(*xy, lw=0.05+0.1*norm(f), alpha=0.4+0.4*norm(f), color=cmap(norm(f)), zorder=zorder+norm(f), rasterized=kwargs.get('rasterized', False)) + else: + raise ValueError(f'Invalid linetype: {linetype}') + return ax + + +def clear_svg(path, debug=False): + """ + matplotlib 生成的 svg 中会使用 2020-02-02 的语法,而 Powerpoint 无法识别 font: 9.8px 'Arial'; 的简写记法,只能识别 font-family: 'Arial'; font-size: 9.8px; 的记法。因此需要进行转换。考虑的属性包括: + - font-size + - font-family + - font-weight + - font-style + """ + raise DeprecationWarning("现在好像不需要 clear 了,直接导入 PPT 即可") + from lxml import etree + tree = etree.parse(path) + root = tree.getroot() + + for text in root.findall('.//{http://www.w3.org/2000/svg}tspan') + root.findall('.//{http://www.w3.org/2000/svg}text'): + style = text.attrib.pop('style', '') + + font_size = re.search(r'font:[^;]*\s+(\d+\.?\d*px)(?:\s|$)', style) + font_family = re.search(r'font:[^;]*\s+\'([^\']*)\'(?:\s|$)', style) + font_style = re.search(r'font:[^;]*\s+(italic|oblique)(?:\s|$)', style) + font_weight = re.search(r'font:[^;]*\s+(bold|normal|bolder|lighter)(?:\s|$)', style) + line_height = re.search(r'line-height:\s+([\d\.]+(px|em|%)?)', style) + font_variant = re.search(r'font-variant:\s+([\w-]+)', style) + text_anchor = re.search(r'text-anchor:\s+([\w-]+)', style) + + if font_size: text.set('font-size', font_size.group(1)) + if font_family: text.set('font-family', font_family.group(1)) + if font_style: text.set('font-style', font_style.group(1)) + if font_weight: text.set('font-weight', font_weight.group(1)) + if line_height: text.set('line-height', line_height.group(1)) + if font_variant: text.set('font-variant', font_variant.group(1)) + if text_anchor: text.set('text-anchor', text_anchor.group(1)) + + if debug: print(f'"{style}" -> "{text.attrib}"') + tree.write(path) + + +def load_font(): + """ + - plt.title("示例图表:数字平方", fontproperties=font, size=15) + - plt.xlabel("数字", fontproperties=font, size=12) + - plt.ylabel("平方", fontproperties=font, size=12) + """ + import requests + from matplotlib.font_manager import FontProperties + + url = "https://ghp.ci/https://github.com/notofonts/noto-cjk/blob/main/Sans/SubsetOTF/SC/NotoSansSC-Regular.otf" + font_path = "/tmp/SimHei.otf" + if not os.path.exists(font_path): + response = requests.get(url) + if response.status_code == 200: + with open(font_path, "wb") as f: + f.write(response.content) + else: + raise Exception("Failed to download the font.") + font = FontProperties(fname=font_path) + plt.rcParams["font.family"] = "sans-serif" + plt.rcParams["font.sans-serif"] = [font_path] # 这里指定.otf文件路径 + plt.rcParams["axes.unicode_minus"] = False # 正确显示负号 + return font + + +# 计算两个 box 的重叠面积 +def _overlapping_area(bbox1, bbox2): + x0 = max(bbox1.x0, bbox2.x0) + x1 = min(bbox1.x1, bbox2.x1) + y0 = max(bbox1.y0, bbox2.y0) + y1 = min(bbox1.y1, bbox2.y1) + return max(0, x1 - x0) * max(0, y1 - y0) + + +# 计算 point 到 box 的最近距离 +def _distance_to_box(point, box): + x = max(box.x0, min(point[0], box.x1)) + y = max(box.y0, min(point[1], box.y1)) + return np.sqrt((point[0] - x) ** 2 + (point[1] - y) ** 2) + + +# 调整文本位置的函数 +def adjust_text(texts, ax, step=0.01, max_iterations=100, mode="xy"): + raw_pos = np.array([text.get_position() for text in texts], dtype=float) + cur_pos = raw_pos.copy() + + overlap = np.zeros((len(texts), len(texts))) + + def update(i, utri_only=False): + bbox1 = texts[i].get_window_extent(renderer=ax.figure.canvas.get_renderer()) + for j, text2 in enumerate(texts): + if j == i: + continue + if utri_only and j <= i: + continue + bbox2 = text2.get_window_extent(renderer=ax.figure.canvas.get_renderer()) + overlap[i, j] = overlap[j, i] = _overlapping_area(bbox1, bbox2) + + def normalize(v): + return v / np.linalg.norm(v).clip(1e-6) + + # 初始化 + for i in range(len(texts)): + update(i, utri_only=True) + + for iteration in range(max_iterations): + i, j = random.choice(list(np.stack(np.nonzero(overlap), axis=-1))) + + # i 对 j 的排斥 + F1 = cur_pos[j] - cur_pos[i] + + # raw_pos[j] 对 j 的吸引 + bbox = texts[j].get_window_extent(renderer=ax.figure.canvas.get_renderer()) + F2 = ( + normalize(raw_pos[j] - cur_pos[j]) + * _distance_to_box(raw_pos[j], bbox) + * 0.001 + ) + # F2 = 0.0 + + # 随机扰动 + F3 = np.random.randn(2) + + # 合力 + F = F1 + F2 + F3 + if mode == "x": + F[1] = 0 + if mode == "y": + F[0] = 0 + + # 更新位置 + cur_pos[j] += F * step + texts[j].set_position(cur_pos[j]) + update(j) + if (overlap == 0).all(): + break + + +def use_chinese_font(fontpath="/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc"): + font_prop = FontProperties(fname=fontpath) + rcParams["font.family"] = font_prop.get_name() + rcParams["axes.unicode_minus"] = False + + +def merge_axes(axes, fig=None): + if fig is None: fig = axes[0].figure + xmin = min(ax.get_position().bounds[0] for ax in axes) # axes[0, 2] 的左上角坐标 + xmax = max(ax.get_position().bounds[0] + ax.get_position().bounds[2] for ax in axes) # axes[1, 3] 的右下角坐标 + ymin = min(ax.get_position().bounds[1] for ax in axes) # axes[0, 2] 的左上角坐标 + ymax = max(ax.get_position().bounds[1] + ax.get_position().bounds[3] for ax in axes) # axes[1, 3] 的右下角坐标 + merged_ax = fig.figure.add_axes([xmin, ymin, xmax - xmin, ymax - ymin]) + + # 如果 axes[0] 被设置与其他的 ax 共享坐标轴,则需要设置 merged_ax 也共享坐标轴 + # if axes[0].get_shared_x_axes() is not None: + # merged_ax.get_shared_x_axes().join(merged_ax, *axes) + # if axes[0].get_shared_y_axes() is not None: + # merged_ax.get_shared_y_axes().join(merged_ax, *axes) + + for ax in axes: + fig.delaxes(ax) + return merged_ax diff --git a/src/sr_harness/utils/render_markdown.py b/src/sr_harness/utils/render_markdown.py new file mode 100644 index 0000000000000000000000000000000000000000..57ce702ce4af5f8b99c9a51bbdcb75125afcbdce --- /dev/null +++ b/src/sr_harness/utils/render_markdown.py @@ -0,0 +1,23 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +import re +from rich.console import Console +from rich.markdown import Markdown +from rich.syntax import Syntax + + +def render_markdown(text: str, width=120, theme="staroffice") -> str: + console = Console(record=True, width=width) + with console.capture() as capture: + matches = list(re.finditer(r"```(\w+)?\n(.*?)\n```", text, re.DOTALL)) + current = 0 + for match in matches: + lang, code = match.groups() + start, end = match.span() + md = Markdown(text[current:start]) + code = Syntax(code, lang or "text", word_wrap=True, line_numbers=True, theme=theme) + console.print(md) + console.print(code) + current = end + if current < len(text): + console.print(Markdown(text[current:])) + return capture.get() diff --git a/src/sr_harness/utils/render_python.py b/src/sr_harness/utils/render_python.py new file mode 100644 index 0000000000000000000000000000000000000000..64ea8ff22c513565383ae2ed274438e8c6de151e --- /dev/null +++ b/src/sr_harness/utils/render_python.py @@ -0,0 +1,18 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +from rich.console import Console +from rich.markdown import Markdown +from rich.syntax import Syntax + +def render_python(text: str, width=120, highlight_lines=[], theme="staroffice") -> str: + console = Console(record=True, width=width) + with console.capture() as capture: + code = Syntax( + text, + "python", + theme=theme, + word_wrap=True, + line_numbers=True, + highlight_lines=highlight_lines, + ) + console.print(code) + return capture.get() diff --git a/src/sr_harness/utils/sanitize_filename.py b/src/sr_harness/utils/sanitize_filename.py new file mode 100644 index 0000000000000000000000000000000000000000..e53c107c928217701ebd555ddfb44bd10c6dfa9c --- /dev/null +++ b/src/sr_harness/utils/sanitize_filename.py @@ -0,0 +1,6 @@ +import re + + +def sanitize_filename(value: str) -> str: + value = re.compile(r'[ <>:"/\\|?*\x00-\x1f]').sub("_", value.strip()) + return (value or "unnamed")[:255] diff --git a/src/sr_harness/utils/save_args.py b/src/sr_harness/utils/save_args.py new file mode 100644 index 0000000000000000000000000000000000000000..ffd2b73ab9f08c2945ea9d078d97312e30f48e45 --- /dev/null +++ b/src/sr_harness/utils/save_args.py @@ -0,0 +1,77 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +from __future__ import annotations +import json +from typing import Any +from pathlib import Path +from datetime import datetime +from collections.abc import MutableMapping +from .serialize import serialize + + +def save_args(args: Any, args_path: Path, excluded_keys=("saved_time", "command")) -> None: + """Save args to JSON, backing up an existing file and printing meaningful diffs.""" + args_path = Path(args_path) + + # Serialize args to a dictionary + if isinstance(args, MutableMapping): + args["saved_time"] = datetime.now().isoformat(timespec="seconds") + args_dict = serialize(args) + else: + args.saved_time = datetime.now().isoformat(timespec="seconds") + args_dict = serialize(vars(args)) + + if args_path.exists(): + # Backup existing file + old_args = json.loads(args_path.read_text(encoding="utf-8")) + if not isinstance(old_args, dict): + raise ValueError(f"Expected {args_path} to contain a JSON object, got {type(old_args).__name__}") + + saved_time = old_args["saved_time"] + if not isinstance(saved_time, str): + raise TypeError(f"Expected {args_path} saved_time to be a string") + timestamp = datetime.fromisoformat(saved_time.strip()) + timestamp = timestamp.strftime('%Y%m%d_%H%M%S') + + backup_path = args_path.with_name(f"{args_path.stem}.{timestamp}{args_path.suffix}") + i = 1 + while backup_path.exists(): + backup_path = args_path.with_name(f"{args_path.stem}.{timestamp}.{i}{args_path.suffix}") + i += 1 + args_path.rename(backup_path) + + # Compare Difference + rows = [] + for key in sorted((set(old_args) | set(args_dict)) - set(excluded_keys)): + old_value = old_args.get(key, "") + new_value = args_dict.get(key, "") + try: + old_text = json.dumps(old_value, ensure_ascii=False, sort_keys=True) + except TypeError: + old_text = repr(old_value) + try: + new_text = json.dumps(new_value, ensure_ascii=False, sort_keys=True) + except TypeError: + new_text = repr(new_value) + if old_text != new_text: + rows.append((key, old_text, new_text)) + + if rows: + print(f"Argument differences detected for {args_path}:") + widths = [ + max(len("key"), *(len(key) for key, old_text, new_text in rows)), + max(len("old"), *(len(old_text) for key, old_text, new_text in rows)), + max(len("new"), *(len(new_text) for key, old_text, new_text in rows)), + ] + lines = [ + f"{'key':<{widths[0]}} {'old':<{widths[1]}} {'new':<{widths[2]}}", + f"{'-' * widths[0]} {'-' * widths[1]} {'-' * widths[2]}", + ] + [ + f"{key:<{widths[0]}} {old_text:<{widths[1]}} {new_text:<{widths[2]}}" + for key, old_text, new_text in rows + ] + print("\n".join(lines)) + + # Save new args + args_path.parent.mkdir(parents=True, exist_ok=True) + with open(args_path, "w", encoding="utf-8") as f: + json.dump(args_dict, f, indent=4, ensure_ascii=False) diff --git a/src/sr_harness/utils/serialize.py b/src/sr_harness/utils/serialize.py new file mode 100644 index 0000000000000000000000000000000000000000..649e1b5f22fce63058b427fab63b5a8041e75b94 --- /dev/null +++ b/src/sr_harness/utils/serialize.py @@ -0,0 +1,35 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +from __future__ import annotations +from typing import Any +from pathlib import Path +from datetime import datetime +from collections.abc import Mapping + + +def serialize(args: Any): + if args is None or isinstance(args, (str, int, float, bool)): + return args + if isinstance(args, Path): + return str(args) + if isinstance(args, datetime): + return args.isoformat(timespec="seconds") + if isinstance(args, Mapping): + return {str(key): serialize(value) for key, value in args.items()} + if isinstance(args, (list, tuple)): + return [serialize(value) for value in args] + if isinstance(args, set): + return [serialize(value) for value in sorted(args, key=repr)] + + try: + import numpy as np + + if isinstance(args, np.ndarray): + return serialize(args.tolist()) + if isinstance(args, np.generic): + return args.item() + except ImportError: + pass + + if hasattr(args, "__dict__"): + return serialize(vars(args)) + return repr(args) diff --git a/src/sr_harness/utils/symbolic_acc.py b/src/sr_harness/utils/symbolic_acc.py new file mode 100644 index 0000000000000000000000000000000000000000..b0b83fa8b76572e7b0b4d12d1559587f08ebf829 --- /dev/null +++ b/src/sr_harness/utils/symbolic_acc.py @@ -0,0 +1,285 @@ +# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License. +from __future__ import annotations +import time +import math +import logging +import numpy as np +import sr_harness_engine as engine +from .tag2ansi import tag2ansi +from fractions import Fraction +from itertools import combinations, product +from typing import Any, Dict, List, Tuple + +__all__ = [ "get_symbolic_acc" ] +_logger = logging.getLogger(f"sr_harness.{__name__}") + + +def llm_judge_equivalence( + f_true: engine.Expression, + f_pred: engine.Expression, + ranges: Dict[str, Tuple[float, float]], + llm_provider, + llm_model, + max_retry = 3, + retry_timeout = 5, +): + from ..api import BaseAPI # utils 内的模块原则上不应该依赖于外部代码,加上这个防止循环依赖 + from .parse_json_with_template import parse_json_with_template + + messages = [] + messages.append({'role': 'system', 'content': ( + "You are judging exact structural recovery in symbolic regression. " + "Two expressions are equivalent only if they represent the same mathematical " + "function throughout the specified continuous domain, allowing algebraic " + "rearrangements and small fitted-coefficient rounding errors. " + "First expand products and collect every repeated term carefully (two copies " + "of a*x add to 2*a*x); then compare function families and coefficients. " + "A numerically negligible extra term may be treated as coefficient rounding. " + "A polynomial or rational approximation to an exponential, logarithm, " + "trigonometric function, root, or other distinct function is NOT equivalent, " + "even if its sampled predictions are nearly identical. " + "Likewise, a low-error Taylor approximation is NOT equivalent. " + "Domain identities such as abs(a) = a for a >= 0 are allowed, but a finite " + "sample range is not grounds to accept a merely close approximation. " + "Judge mathematical structure, not numerical fit quality. " + "Return a JSON object with keys 'reason' (brief string) and 'equivalent' (boolean)." + )}) + messages.append({'role': 'user', 'content': ( + f"Ground truth: {f_true.to_str()}\n" + f"Predicted: {f_pred.to_str()}\n" + "Variable ranges:\n" + + "\n".join(f"- {name}: [{lo}, {hi}]" for name, (lo, hi) in ranges.items()) + )}) + api = BaseAPI.create(llm_provider, model=llm_model) + total_usage = {'token': {}, 'price': {}} + + def merge_usage(usage): + for group in ('token', 'price'): + for key, value in (usage or {}).get(group, {}).items(): + total_usage[group][key] = total_usage[group].get(key, 0) + value + + for _ in range(max_retry): + content = "" + response = None + usage_merged = False + try: + # Reasoning models may consume most of a 1k budget before emitting + # the required JSON, yielding an otherwise successful empty answer. + response = api(messages, n=1, max_tokens=4096, temperature=0.0) + for sample in response: + content = sample.content or "" + merge_usage({"token": response.token_usage, "price": response.money_usage}) + usage_merged = True + _logger.debug(f"Response: {content!r}") + parsed = parse_json_with_template(content, {'reason': str, 'equivalent': bool}) + parsed['usage'] = total_usage + return parsed + except Exception as e: + if response is not None and not usage_merged and response.ok is not None: + merge_usage({"token": response.token_usage, "price": response.money_usage}) + _logger.trace(f"Failed to parse LLM response: [{type(e).__name__}]{str(e)}. Response was: {content}") + time.sleep(retry_timeout) + else: + _logger.warning(f"Failed to parse LLM response after {max_retry} attempts.") + return {'equivalent': None, 'reason': f"Failed to parse LLM response after {max_retry} attempts.", 'usage': total_usage} + + +def my_nsimplify( + vals: List[float] | float, + constants: Dict[str, float] = {}, + tolerance=1e-5, + max_denominator=1000, + relation_bound=4, + max_relation_terms=2 +) -> List[str] | str: + constants = {str(k): float(v) for k, v in constants.items() if math.isfinite(float(v)) and float(v) != 0} + if is_single := isinstance(vals, (int, float)): + vals = [vals] + else: + vals = list(vals) + ans = [] + + for x in vals: + x, candidates = float(x), [] + if not math.isfinite(x): + ans.append(str(x)); continue + + q = Fraction(x).limit_denominator(max_denominator) + v = float(q) + if abs(v - x) <= tolerance * max(1, abs(v), abs(x)): + e = str(q.numerator) if q.denominator == 1 else f"{q.numerator}/{q.denominator}" + candidates.append({"expr": e, "err": abs(v - x), "score": len(e) + math.log2(abs(q.numerator) + 1) + math.log2(q.denominator + 1)}) + + for name, c in constants.items(): + if abs(c - x) <= tolerance * max(1, abs(c), abs(x)): + candidates.append({"expr": name, "err": abs(c - x), "score": len(name) - 3}) + + q = Fraction(x / c).limit_denominator(max_denominator) + v = float(q) * c + if abs(v - x) <= tolerance * max(1, abs(v), abs(x)): + s, qabs = "-" if q < 0 else "", abs(q) + n, d = qabs.numerator, qabs.denominator + e = f"{s}{name}" if n == d == 1 else f"{s}{n}*{name}" if d == 1 else f"{s}{name}/{d}" if n == 1 else f"{s}{n}*{name}/{d}" + candidates.append({"expr": e, "err": abs(v - x), "score": len(e) + math.log2(n + 1) + math.log2(d + 1)}) + + names = list(constants) + for k in range(1, min(max_relation_terms, len(names)) + 1): + for subset in combinations(names, k): + cs = [constants[n] for n in subset] + for a0 in range(1, relation_bound + 1): + for coeffs in product(range(-relation_bound, relation_bound + 1), repeat=k + 1): + if all(a == 0 for a in coeffs[:-1]): continue + rel = a0 * x + sum(a * c for a, c in zip(coeffs[:-1], cs)) + coeffs[-1] + v = x - rel / a0 + if abs(v - x) > tolerance * max(1, abs(v), abs(x)): continue + + parts, fracs = [], [] + for a, name in zip(coeffs[:-1], subset): + q = Fraction(-a, a0); fracs.append(q) + if q == 0: continue + s, qabs = 1 if q > 0 else -1, abs(q) + n, d = qabs.numerator, qabs.denominator + term = name if n == d == 1 else f"{n}*{name}" if d == 1 else f"{name}/{d}" if n == 1 else f"{n}*{name}/{d}" + parts.append((s, term)) + + q = Fraction(-coeffs[-1], a0); fracs.append(q) + if q: + s, qabs = 1 if q > 0 else -1, abs(q) + term = str(qabs.numerator) if qabs.denominator == 1 else f"{qabs.numerator}/{qabs.denominator}" + parts.append((s, term)) + + e = "0" if not parts else "".join((p if i == 0 and s > 0 else f"-{p}" if i == 0 else f" + {p}" if s > 0 else f" - {p}") for i, (s, p) in enumerate(parts)) + candidates.append({"expr": e, "err": abs(v - x), "score": len(e) + 5 + sum(math.log2(abs(f.numerator) + 1) + math.log2(f.denominator + 1) for f in fracs)}) + + ans.append(min(candidates, key=lambda c: (c["score"], c["err"]))["expr"] if candidates else repr(x)) + + return ans[0] if is_single else ans + + +def get_symbolic_acc( + f_true: engine.Expression, + f_pred: engine.Expression, + data: Dict[str, np.ndarray], + atol = 1e-8, + rtol = 1e-6, + nsimplify_tolerance = 1e-5, + llm_judge: bool = True, + llm_provider: str = "deepseek", + llm_model: str = "deepseek-v4-flash", + wait_for_human: bool = False, + return_details: bool = False, +) -> Dict[str, Any]: + """Check candidate recovery with numeric diagnostics and a structural judge. + + The numeric comparison on ``data`` is a diagnostic, not proof of symbolic + identity. With ``llm_judge=True``, the structural verdict decides the final + result (allowing small coefficient rounding and domain identities). + """ + for var in ( + [var.name for var in f_true.iter_preorder() if isinstance(var, engine.Variable)] + + [var.name for var in f_pred.iter_preorder() if isinstance(var, engine.Variable)] + ): + if var in data: + pass + elif var.lower() == 'pi': + data[var] = math.pi + elif var.lower() == 'e': + data[var] = math.e + else: + raise ValueError(f"Variable '{var}' not found in data and is not recognized as a constant.") + + def numeric_equivalence(y_true, y_pred): + if not np.any(is_finite := np.isfinite(y_true)): + return {'equivalent': False, 'reason': 'y_true is all non-finite'} + if not np.all(np.isfinite(y_pred[is_finite])): + return {'equivalent': False, 'reason': 'y_pred has non-finite values where y_true is finite'} + if np.allclose(y_true[is_finite], y_pred[is_finite], atol=atol, rtol=rtol): + return {'equivalent': True, 'reason': 'y_pred is close to y_true within tolerances'} + else: + return {'equivalent': False, 'reason': 'y_pred is not close to y_true within tolerances'} + + result = {'equivalent': None, 'reason': None} + + # 直接判断是否数值等价 + if True: + y_true = f_true.eval(data) + y_pred = f_pred.eval(data) + numeric_result = numeric_equivalence(y_true, y_pred) + + # 尝试对数值常数进行 nsimplify,看看能否得到数值等价 + if not numeric_result['equivalent']: + nsimplified_f_pred = f_pred.copy() + numbers = [num for num in nsimplified_f_pred.iter_preorder() if isinstance(num, engine.Number)] + values = my_nsimplify( + [num.value for num in numbers], + tolerance=nsimplify_tolerance, + constants={'PI': math.pi, 'E': math.e, 'sqrt(2)': math.sqrt(2), 'sqrt(3)': math.sqrt(3), 'sqrt(5)': math.sqrt(5)} + ) + for num, value in zip(numbers, values): + value = engine.parse(value, {'PI': math.pi, 'E': math.e}) + nsimplified_f_pred = nsimplified_f_pred.replace(num, value) + _logger.debug(f"Applied nsimplify to f_pred. Original: {f_pred.to_str()}, Simplified: {nsimplified_f_pred.to_str()}") + nsimplified_y_pred = nsimplified_f_pred.eval(data) + nsimplified_numeric_result = numeric_equivalence(y_true, nsimplified_y_pred) + nsimplified_numeric_result['reason'] = f"nsimplified f_pred to obtain y_pred. {nsimplified_numeric_result['reason']}" + if nsimplified_numeric_result['equivalent']: + f_pred = nsimplified_f_pred + y_pred = nsimplified_y_pred + numeric_result = nsimplified_numeric_result + + assert numeric_result['equivalent'] in {True, False}, f"numeric_result['equivalent'] must be True or False, got {numeric_result['equivalent']!r}" + + # 尝试用 LLM 判断结构等价 + if llm_judge: + var_ranges = {name: (np.nanmin(values), np.nanmax(values)) for name, values in data.items()} + llm_result = llm_judge_equivalence( + f_pred=f_pred, + f_true=f_true, + ranges=var_ranges, + llm_provider=llm_provider, + llm_model=llm_model, + ) + result['llm_usage'] = llm_result.get('usage', {'token': {}, 'price': {}}) + result['llm_judgement'] = { + 'equivalent': llm_result.get('equivalent'), + 'reason': llm_result.get('reason'), + } + if numeric_result['equivalent'] == llm_result['equivalent']: + result['equivalent'] = llm_result['equivalent'] + result['reason'] = f"{numeric_result['reason']}; LLM judgement agrees: {llm_result['reason']}" + elif wait_for_human: + foo = lambda x: tag2ansi('[blue]NONE[reset]' if x is None else ('[green]EQUIVALENT[reset]' if x else '[red]NOT EQUIVALENT[reset]')) + accept = input( + f"Numeric equivalent is {foo(numeric_result['equivalent'])}, " + f"while LLM judges the formulas {foo(llm_result['equivalent'])} since {llm_result['reason']}:\n" + f" f_true = {f_true.to_str()}\n" + f" f_pred = {f_pred.to_str()}\n" + f"Accept LLM judgement? [y/N] " + ).strip().lower() in {"y", "yes", "true", "1", ""} + if accept: + result['equivalent'] = llm_result['equivalent'] + result['reason'] = f"{numeric_result['reason']}; but human accepted LLM judgement: {llm_result['equivalent']} ({llm_result['reason']})" + else: + result['equivalent'] = numeric_result['equivalent'] + result['reason'] = f"{numeric_result['reason']}; and human rejected LLM judgement: {llm_result['equivalent']} ({llm_result['reason']})" + else: + foo = lambda x: tag2ansi('[blue]NONE[reset]' if x is None else ('[green]EQUIVALENT[reset]' if x else '[red]NOT EQUIVALENT[reset]')) + accept = llm_result['equivalent'] is not None + _logger.warning( + f"Numeric equivalent is {foo(numeric_result['equivalent'])}, " + f"while LLM judges the formulas {foo(llm_result['equivalent'])} since {llm_result['reason']}:\n" + f" f_true = {f_true.to_str()}\n" + f" f_pred = {f_pred.to_str()}\n" + f"Automatically {'accept' if accept else 'reject'} LLM judgement without human review." + ) + if accept: + result['equivalent'] = llm_result['equivalent'] + result['reason'] = f"{numeric_result['reason']}; automatically accepted LLM judgement: {llm_result['equivalent']} ({llm_result['reason']})" + else: + result['equivalent'] = numeric_result['equivalent'] + result['reason'] = f"{numeric_result['reason']}; automatically rejected LLM judgement: {llm_result['equivalent']} ({llm_result['reason']})" + else: + result['equivalent'] = numeric_result['equivalent'] + result['reason'] = numeric_result['reason'] + + return result if return_details else result['equivalent'] diff --git a/src/sr_harness/utils/tag2ansi.py b/src/sr_harness/utils/tag2ansi.py new file mode 100644 index 0000000000000000000000000000000000000000..d79878d499d8f8c30bb7f638dddd0b6c5a3e6d0b --- /dev/null +++ b/src/sr_harness/utils/tag2ansi.py @@ -0,0 +1,170 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +import re + +__all__ = ["tag2ansi"] + +RESET_CODE = {"reset": "\033[0m"} + +STYLE_TABLE = { + "bold": "1", + "dim": "2", + "italic": "3", + "underline": "4", + "blink": "5", + "reverse": "7", + "hidden": "8", + "strike": "9", +} + +COLOR_TABLE = { + "black": "30", + "red": "31", + "green": "32", + "yellow": "33", + "blue": "34", + "magenta": "35", + "cyan": "36", + "white": "37", + "brightblack": "90", + "brightred": "91", + "brightgreen": "92", + "brightyellow": "93", + "brightblue": "94", + "brightmagenta": "95", + "brightcyan": "96", + "brightwhite": "97", + # --- 扩展常用颜色 (256色或TrueColor) --- + "orange": "38;5;208", + "pink": "38;5;213", + "hotpink": "38;5;205", + "purple": "38;5;129", + "violet": "38;5;177", + "brown": "38;5;94", + "olive": "38;5;100", + "lime": "38;5;118", + "teal": "38;5;30", + "navy": "38;5;19", + "gold": "38;5;220", + "silver": "38;5;250", + "gray": "38;5;245", + "darkgray": "38;5;240", + "lightgray": "38;5;252", + "indigo": "38;5;57", + "coral": "38;5;203", + "skyblue": "38;5;117", + "turquoise": "38;5;45", +} + + +def parse_tag(tag: str) -> str: + """ + 支持 [bold+red], [italic+#FFAA00], [color123] + """ + parts = tag.split(" ") + seq = "" + for part in parts: + part = part.lower() + if part in STYLE_TABLE: + seq += f"\033[{STYLE_TABLE[part]}m" + elif part in COLOR_TABLE: + seq += f"\033[{COLOR_TABLE[part]}m" + elif part.startswith("color"): + try: + idx = int(part.removeprefix("color")) + assert 0 <= idx <= 255 + seq += f"\033[38;5;{idx}m" + except ValueError: + pass + elif part.startswith("#") and len(part) == 7: + try: + r = int(part[1:3], 16) + g = int(part[3:5], 16) + b = int(part[5:7], 16) + seq += f"\033[38;2;{r};{g};{b}m" + except ValueError: + pass + else: + pass + return seq + + +def find_matching_paren(s: str, start_idx: int) -> int: + stack = [] + pairs = {")": "(", "}": "{", "]": "["} + opens = set(pairs.values()) + closes = set(pairs.keys()) + for i, ch in enumerate(s[start_idx:], start=start_idx): + if ch in opens: + stack.append(ch) + elif ch in closes and stack and pairs[ch] == stack[-1]: + stack.pop() + if not stack: + return i + return -1 + + +def auto_insert_reset(segment: str) -> str: + if (reset_pos := segment.find("[reset]")) != -1: + return segment[:reset_pos] + RESET_CODE["reset"] + segment[reset_pos + len("[reset]") :] + elif not (stripped := segment.lstrip()): + return segment + RESET_CODE["reset"] + elif (first_char := stripped[0]).isalnum(): + m = re.search(r"[^a-zA-Z0-9/_-]", stripped) + if not m: + return segment + RESET_CODE["reset"] + offset = len(segment) - len(stripped) + insert_at = offset + m.start() + return segment[:insert_at] + RESET_CODE["reset"] + segment[insert_at:] + elif first_char in "({[": + offset = len(segment) - len(stripped) + match_idx = find_matching_paren(segment, offset) + if match_idx == -1: + return segment + RESET_CODE["reset"] + return segment[: match_idx + 1] + RESET_CODE["reset"] + segment[match_idx + 1 :] + else: + return segment + RESET_CODE["reset"] + + +def tag2ansi(text: str) -> str: + """ + 将 [tag1 tag2] 转换为 ANSI 码并智能插入 reset。 + 支持多种颜色定义方式、样式组合、自动闭合。 + """ + pattern = re.compile(r"\[(?!reset)([a-zA-Z0-9+#]+(?: [a-zA-Z0-9+#]+)*)\]") + + result = [] + last_end = 0 + active_tag = None + + for match in pattern.finditer(text): + tag = match.group(1) + start, end = match.span() + + # 先加前一段 + if last_end < start: + seg = text[last_end:start] + if active_tag: + seg = auto_insert_reset(seg) + result.append(seg) + last_end = end + + # 当前标签 + if tag.lower() == "reset": + result.append(RESET_CODE) + active_tag = None + else: + seq = parse_tag(tag) + if seq: + result.append(seq) + active_tag = tag + else: + result.append(match.group(0)) + + # 收尾 + if last_end < len(text): + seg = text[last_end:] + if active_tag: + seg = auto_insert_reset(seg) + result.append(seg) + + return "".join(result) diff --git a/src/sr_harness/utils/timing.py b/src/sr_harness/utils/timing.py new file mode 100644 index 0000000000000000000000000000000000000000..ebeda1380db00d6ddad24b14bdff19d45cda5c04 --- /dev/null +++ b/src/sr_harness/utils/timing.py @@ -0,0 +1,283 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +""" +Lightweight timing utilities for optional performance diagnostics. +""" + +import enum +import time +import numpy as np +import pandas as pd +from typing import Literal + +__all__ = ["Timer", "NamedTimer", "ParallelTimer"] + + + +Mode = Literal["time", "count", "pace", "speed"] + + +def humanize_time(time): + """Convert time in seconds to a human-readable string.""" + if time == 0: return "0 s" + unit_scale = pd.Series({ # 需要保证从小到大排列 + 'μs': 1e-6, 'ms': 1e-3, 's': 1e0, 'min': 60, 'h': 3600, 'day': 86400 + }) + idx = max(0, unit_scale.searchsorted(time, side='right')-1) + time_unit, scale = unit_scale.index[idx], unit_scale.iloc[idx] + return f"{time / scale:.3g} {time_unit}" + + +def humanize_count(count, unit="iter"): + """Convert count to a human-readable string.""" + if count == 0: return f"0 {unit}" + unit_scale = pd.Series({ # 需要保证从小到大排列 + f'n{unit}': 1e-9, f'μ{unit}': 1e-6, f'm{unit}': 1e-3, + f'{unit}': 1, f'k{unit}': 1e3, f'M{unit}': 1e6, f'G{unit}': 1e9 + }) + idx = max(0, unit_scale.searchsorted(count, side='right')-1) + count_unit, scale = unit_scale.index[idx], unit_scale.iloc[idx] + return f"{count / scale:.3g} {count_unit}" + + +def humanize_pace(pace, unit="iter"): + """Convert pace (second/iter) to a human-readable string.""" + if pace == 0: return f"0 s/{unit}" + unit_scale = pd.Series({ # 需要保证从小到大排列 + f'μs/{unit}': 1e-6, f'ms/{unit}': 1e-3, f's/{unit}': 1e0, + f'min/{unit}': 60, f'h/{unit}': 3600, f'day/{unit}': 86400 + }) + idx = max(0, unit_scale.searchsorted(pace, side='right')-1) + pace_unit, scale = unit_scale.index[idx], unit_scale.iloc[idx] + return f"{pace / scale:.3g} {pace_unit}" + + +def humanize_speed(speed, unit="iter"): + """Convert speed (iter/second) to a human-readable string.""" + if speed == 0: return f"0 {unit}/s" + unit_scale = pd.Series({ # 需要保证从小到大排列 + f'{unit}/day': 1/86400, f'{unit}/h': 1/3600, f'{unit}/min': 1/60, f'{unit}/s': 1, + f'k{unit}/s': 1e3, f'M{unit}/s': 1e6, f'G{unit}/s': 1e9 + }) + idx = max(0, unit_scale.searchsorted(speed, side='right')-1) + speed_unit, scale = unit_scale.index[idx], unit_scale.iloc[idx] + return f"{speed / scale:.3g} {speed_unit}" + + +class Timer: + def __init__(self, unit="iter"): + """ 计时器 """ + self._count = 0 + self._time = 0 + self.unit = unit + self.last_add_time = time.time() + + def add(self, n=1, by: Literal["increment", "absolute"]="increment"): + if by == "increment": self._count += n + elif by == "absolute": self._count = n + self._time += (now := time.time()) - self.last_add_time + self.last_add_time = now + + def clear(self, reset_last_add_time=False): + self._count = 0 + self._time = 0 + if reset_last_add_time: + self.last_add_time = time.time() + + def to_str(self, mode: Mode = 'pace'): + if mode == 'pace': return humanize_pace(self.pace, unit=self.unit) + elif mode == "speed": return humanize_speed(self.speed, unit=self.unit) + elif mode == "count": return humanize_count(self.count, unit=self.unit) + elif mode == "time": return humanize_time(self.time) + else: raise ValueError(f"Unknown mode: {mode}. Supported modes are 'pace', 'speed', 'count', and 'time'.") + + def __str__(self): + time = self.time_str() + count = self.count_str() + pace = self.pace_str() + speed = self.speed_str() + return f"{type(self).__name__}(time={time}, count={count}, pace={pace}, speed={speed})" + + def __repr__(self): + return self.__str__() + + @property + def time(self): return self._time + @property + def count(self): return self._count + @property + def pace(self): return self.time / self.count if self.count != 0 else 0 + @property + def speed(self): return self.count / self.time if self.time != 0 else 0 + def time_str(self): return humanize_time(self.time) + def count_str(self): return humanize_count(self.count, unit=self.unit) + def pace_str(self): return humanize_pace(self.pace, unit=self.unit) + def speed_str(self): return humanize_speed(self.speed, unit=self.unit) + + def to_dict(self): + return { + '_count': self._count, + '_time': self._time, + 'unit': self.unit, + } + + @classmethod + def from_dict(cls, dict): + timer = cls(unit=dict['unit']) + timer._count = dict['_count'] + timer._time = dict['_time'] + return timer + + +class NamedTimer(Timer): + def __init__(self, unit="iter"): + """ 对 Timer 的扩展, 支持将 count 和 time 统计到不同的名称下 """ + super().__init__(unit=unit) + self._count = {} + self._time = {} + + def add(self, name, n=1, by: Literal["increment", "absolute"]="increment"): + if name and name not in self.names: + self._time[name] = self._count[name] = 0 + if name is None: pass + elif by == "increment": self._count[name] += n + elif by == "absolute": self._count[name] = n + self._time[name] += (now := time.time()) - self.last_add_time + self.last_add_time = now + + def clear(self, reset_last_add_time=False): + self._count = {} + self._time = {} + if reset_last_add_time: + self.last_add_time = time.time() + + def to_str( + self, + mode: Mode='pace', + mode_of_detail: Mode|None='pace', + mode_of_percent: Literal['by_time', 'by_count']|None='by_time', + ): + if mode == "time": total = humanize_time(self.time) + elif mode == "count": total = humanize_count(self.count, unit=self.unit) + elif mode == "pace": total = humanize_pace(self.pace, unit=self.unit) + elif mode == "speed": total = humanize_speed(self.speed, unit=self.unit) + else: raise ValueError(f"Unknown mode: {mode}. Supported modes are 'pace', 'speed', 'count', and 'time'.") + + if mode_of_detail is None: detail = {k: "" for k in self.names} + elif mode_of_detail == "time": detail = {k: humanize_time(self.get_named_time(k)) for k in self.names} + elif mode_of_detail == "count": detail = {k: humanize_count(self.get_named_count(k), unit=self.unit) for k in self.names} + elif mode_of_detail == "pace": detail = {k: humanize_pace(self.get_named_pace(k), unit=self.unit) for k in self.names} + elif mode_of_detail == "speed": detail = {k: humanize_speed(self.get_named_speed(k), unit=self.unit) for k in self.names} + else: raise ValueError(f"Unknown mode_of_detail: {mode_of_detail}. Supported modes are 'pace', 'speed', 'count', and 'time'.") + + if mode_of_percent is None: percent = {k: 0 for k in self.names} + elif mode_of_percent == 'by_time': percent = {k: self.get_named_time(k) / self.time if self.time > 0 else 0 for k in self.names} + elif mode_of_percent == 'by_count': percent = {k: self.get_named_count(k) / self.count if self.count > 0 else 0 for k in self.names} + else: raise ValueError(f"Unknown mode: {mode_of_percent}. Supported modes are 'by_time' and 'by_count'.") + + detail_str = [] + for k in sorted(self.names, key=percent.get, reverse=True): + if detail[k] and percent[k]: + detail_str.append(f"{k}={detail[k]}[{percent[k]:.0%}]") + elif detail[k]: + detail_str.append(f"{k}={detail[k]}") + elif percent[k]: + detail_str.append(f"{k}[{percent[k]:.0%}]") + else: + pass + detail_str = f" ({'; '.join(detail_str)})" if detail_str else "" + return f'{total}{detail_str}' + + @property + def names(self): return list(self._time.keys()) + @property + def time(self): return sum(self._time.values()) + @property + def count(self): return sum(self._count.values()) + def get_named_time(self, name): return self._time[name] + def get_named_count(self, name): return self._count[name] + def get_named_pace(self, name): return self._time[name] / self._count[name] if self._count[name] != 0 else 0 + def get_named_speed(self, name): return self._count[name] / self._time[name] if self._time[name] != 0 else 0 + @property + def named_time(self): return {k: self.get_named_time(k) for k in self.names} + @property + def named_count(self): return {k: self.get_named_count(k) for k in self.names} + @property + def named_pace(self): return {k: self.get_named_pace(k) for k in self.names} + @property + def named_speed(self): return {k: self.get_named_speed(k) for k in self.names} + + +class ParallelTimer(Timer): + def __init__(self, unit="iter"): + """ 对 Timer 的扩展, 支持将 count 统计到不同的名称下, 但 time 在各名称间共享 """ + super().__init__(unit=unit) + self._count = {} + + def add(self, name, n=1, by: Literal["increment", "absolute"]="increment"): + if name and name not in self.names: + self._count[name] = 0 + if name is None: pass + elif by == "increment": self._count[name] += n + elif by == "absolute": self._count[name] = n + self._time += (now := time.time()) - self.last_add_time + self.last_add_time = now + + def clear(self, reset_last_add_time=False): + self._count = {} + self._time = 0 + if reset_last_add_time: + self.last_add_time = time.time() + + def to_str( + self, + mode: Mode='pace', + mode_of_detail: Mode|None='pace', + mode_of_percent: Literal['by_time', 'by_count']|None='by_time' + ): + if mode == "time": total = humanize_time(self.time) + elif mode == "count": total = humanize_count(self.count, unit=self.unit) + elif mode == "pace": total = humanize_pace(self.pace, unit=self.unit) + elif mode == "speed": total = humanize_speed(self.speed, unit=self.unit) + else: raise ValueError(f"Unknown mode: {mode}. Supported modes are 'pace', 'speed', 'count', and 'time'.") + + if mode_of_detail is None: detail = {k: "" for k in self.names} + elif mode_of_detail == "time": detail = {k: humanize_time(self.get_named_time(k)) for k in self.names} # 不建议,因为 time 是共享的 + elif mode_of_detail == "count": detail = {k: humanize_count(self.get_named_count(k), unit=self.unit) for k in self.names} + elif mode_of_detail == "pace": detail = {k: humanize_pace(self.get_named_pace(k), unit=self.unit) for k in self.names} + elif mode_of_detail == "speed": detail = {k: humanize_speed(self.get_named_speed(k), unit=self.unit) for k in self.names} + else: raise ValueError(f"Unknown mode_of_detail: {mode_of_detail}. Supported modes are 'pace', 'speed', 'count', and 'time'.") + + if mode_of_percent is None: percent = {k: None for k in self.names} + elif mode_of_percent == 'by_time': percent = {k: self.get_named_time(k) / self.time if self.time > 0 else None for k in self.names} # 不建议,因为 time 是共享的 + elif mode_of_percent == 'by_count': percent = {k: self.get_named_count(k) / self.count if self.count > 0 else None for k in self.names} + else: raise ValueError(f"Unknown mode: {mode_of_percent}. Supported modes are 'by_time' and 'by_count'.") + + detail_str = [] + for k in sorted(self.names, key=lambda x: percent.get(x) or -float('inf'), reverse=True): + if detail[k] and percent[k]: + detail_str.append(f"{k}={detail[k]}[{percent[k]:.0%}]") + elif detail[k]: + detail_str.append(f"{k}={detail[k]}") + elif percent[k]: + detail_str.append(f"{k}[{percent[k]:.0%}]") + else: + pass + detail_str = f" ({'; '.join(detail_str)})" if detail_str else "" + return f'{total}{detail_str}' + + @property + def names(self): return list(self._count.keys()) + @property + def count(self): return sum(self._count.values()) + def get_named_time(self, name): return self._time + def get_named_count(self, name): return self._count[name] + def get_named_pace(self, name): return self._time / self._count[name] if self._count[name] != 0 else 0 + def get_named_speed(self, name): return self._count[name] / self._time if self._time != 0 else 0 + @property + def named_time(self): return {k: self.get_named_time(k) for k in self.names} + @property + def named_count(self): return {k: self.get_named_count(k) for k in self.names} + @property + def named_pace(self): return {k: self.get_named_pace(k) for k in self.names} + @property + def named_speed(self): return {k: self.get_named_speed(k) for k in self.names} diff --git a/src/sr_harness/utils/utils.py b/src/sr_harness/utils/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..059de54b708cd46c6cef7882664a1bfebd23c722 --- /dev/null +++ b/src/sr_harness/utils/utils.py @@ -0,0 +1,44 @@ +# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License. +import os +import random +import builtins + +__all__ = [ + "softmax", + "seed_all", + "bounded_value", +] + + +def bounded_value(value, min, max, default, converter=None): + """Convert a value when requested, then constrain it to an inclusive range.""" + try: + parsed = converter(value) if converter is not None else value + except (TypeError, ValueError): + parsed = default + return builtins.max(min, builtins.min(max, parsed)) + + +def softmax(x): + import numpy as np + x = np.exp(x - x.max()) + return x / x.sum() + + +def seed_all(seed): + os.environ["PL_GLOBAL_SEED"] = str(seed) + random.seed(seed) + try: + import numpy as np + np.random.seed(seed) + except ImportError: + pass + try: + import torch + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + torch.cuda.manual_seed(seed) + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False + except ImportError: + pass diff --git a/src/sr_harness/web/__init__.py b/src/sr_harness/web/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2656f9a1a90ac21729b84186de3f8463f1f960f0 --- /dev/null +++ b/src/sr_harness/web/__init__.py @@ -0,0 +1,2 @@ +"""Web visualization for SRHarness search records.""" +from .app import create_app diff --git a/src/sr_harness/web/app.py b/src/sr_harness/web/app.py new file mode 100644 index 0000000000000000000000000000000000000000..1086d28a8f8d7f016c908377690f41d777872dc1 --- /dev/null +++ b/src/sr_harness/web/app.py @@ -0,0 +1,338 @@ +from __future__ import annotations + +import asyncio +import json +import math +import re +from contextlib import asynccontextmanager +from importlib.metadata import version as package_version +from pathlib import Path +from typing import Any + +import sr_harness_engine as engine +from fastapi import Body, FastAPI, HTTPException, Query, Request +from fastapi.responses import FileResponse, JSONResponse, StreamingResponse +from fastapi.staticfiles import StaticFiles + +from ..runtime import SRInteractionManager +from .responses import worker_json_response, worker_event_response +from .isolation import RequestWorkPool, RequestBodyLimit, install_route_isolation + +WEB_DIR = Path(__file__).resolve().parent +STATIC_DIR = WEB_DIR / "static" +DEFAULT_LOG_DIR = Path.cwd() / "logs" + + +def create_app( + log_dir: str | Path = DEFAULT_LOG_DIR, + *, + session=None, + conversation_registry=None, + read_only: bool = False, +) -> FastAPI: + """Create app. + + Args: + log_dir: The log dir value. + session: The session value. + conversation_registry: Optional persistent conversation registry. + + Returns: + FastAPI: The operation result. + """ + version = package_version("sr-harness") + work_pool = RequestWorkPool() + + @asynccontextmanager + async def lifespan(app): + work_pool.start() + try: + yield + finally: + work_pool.close() + + app = FastAPI(title="SRHarness Search Viewer", version=version, lifespan=lifespan) + app.state.work_pool = work_pool + install_route_isolation(app, work_pool) + app.state.log_dir = Path(log_dir).resolve() + app.state.session = session + app.state.conversation_registry = conversation_registry + app.state.read_only = bool( + read_only or getattr(conversation_registry, "read_only", False) + ) + app.state.interaction_manager = SRInteractionManager() if session is None else None + + @app.middleware("http") + async def enforce_read_only(request: Request, call_next): + if app.state.read_only and request.method not in {"GET", "HEAD", "OPTIONS"}: + path = request.url.path + selection = ( + request.method == "POST" + and re.fullmatch(r"/api/conversations/[^/]+/select", path) is not None + ) + pure_computation = request.method == "POST" and path == "/api/data/context/heatmap" + if not (selection or pure_computation): + return JSONResponse( + status_code=403, + content={"detail": "SRHarness is running in read-only mode"}, + ) + return await call_next(request) + if conversation_registry is not None: + from .conversations import mount_conversations + mount_conversations(app, conversation_registry) + app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static") + + @app.get("/") + async def index(): + return FileResponse(STATIC_DIR / ("platform.html" if session is not None else "index.html")) + + @app.get("/viewer") + async def viewer(): + return FileResponse(STATIC_DIR / "index.html") + + @app.get("/health", include_in_schema=False) + async def health(): + return {"status": "ok"} + + @app.get("/api/version") + async def application_version(): + return {"version": version} + + if session is not None: + from .platform import mount_platform + mount_platform(app, session) + + @app.get("/api/runs") + def list_runs(): + state = getattr(session, "run_state", None) if session is not None else None + if state is None: + return {"runs": []} + count = state.node_count + return {"runs": [{ + "run_id": state.run_id, + "run_key": state.run_id, + "manifest": {"run_id": state.run_id}, + "record_count": count, + "last_seq": count, + }]} + + @app.get("/api/control/status") + def control_status(): + manager = session.sr_interaction_manager if session is not None else app.state.interaction_manager + return manager.status() + + @app.get("/api/control/events") + def control_events(after_seq: int = Query(0, ge=0)): + manager = session.sr_interaction_manager if session is not None else app.state.interaction_manager + return worker_event_response(manager, after_seq) + + @app.post("/api/control/command") + def control_command(payload: dict = Body(...)): + try: + manager = session.sr_interaction_manager if session is not None else app.state.interaction_manager + return manager.command( + str(payload.get("action", "")), + str(payload.get("message", "")) or None, + ) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + + @app.get("/api/runs/{run_id}/records") + def list_records(run_id: str, after_seq: int = Query(0, ge=0), include_detail: bool = False): + state = _resolve_run_state(session, run_id) + all_records = _number_records(state.records(include_detail=True)) + records_by_id = { + record["node_id"]: record for record in all_records if record.get("node_id") + } + records = [] + for record in all_records: + if int(record.get("seq", 0)) <= after_seq: + continue + record = _with_core_derivatives(record, records_by_id) + records.append(record if include_detail else _strip_detail(record)) + return worker_json_response({"records": records}) + + @app.get("/api/runs/{run_id}/records/{node_id}") + def get_record(run_id: str, node_id: str): + state = _resolve_run_state(session, run_id) + all_records = _number_records(state.records(include_detail=True)) + records_by_id = { + record["node_id"]: record for record in all_records if record.get("node_id") + } + for record in all_records: + if record.get("node_id") == node_id: + return worker_json_response(_with_core_derivatives(record, records_by_id)) + raise HTTPException(status_code=404, detail=f"Node not found: {node_id}") + + @app.get("/api/runs/{run_id}/stream") + async def stream_records(run_id: str, request: Request, after_seq: int = Query(0, ge=0)): + state = _resolve_run_state(session, run_id) + + def encode_batch(next_seq): + batch = [] + all_records = _number_records(state.records(include_detail=True)) + records_by_id = {record["node_id"]: record for record in all_records if record.get("node_id")} + for record in all_records: + seq = int(record.get("seq", 0)) + if seq > next_seq: + batch.append(_strip_detail(_with_core_derivatives(record, records_by_id))) + next_seq = max(next_seq, seq) + if len(batch) >= 32: + break + payload = worker_json_response(_sanitize_json_value({"records": batch})).body.decode('utf-8') if batch else None + return next_seq, payload + + async def event_source(): + next_seq = after_seq + while not await request.is_disconnected(): + try: + next_seq, payload = await work_pool.run(encode_batch, next_seq) + except HTTPException as exc: + yield "event: error\ndata: " + json.dumps({"detail": exc.detail}) + "\n\n" + return + if payload is not None: + yield f"data: {payload}\n\n" + else: + yield ": keepalive\n\n" + await asyncio.sleep(1.0) + + return StreamingResponse(event_source(), media_type="text/event-stream") + + app.add_middleware(RequestBodyLimit) + return app + + +def _resolve_run_state(session, run_id: str): + state = getattr(session, "run_state", None) if session is not None else None + if state is None or state.run_id != run_id: + raise HTTPException(status_code=404, detail=f"Run not found: {run_id}") + return state + + +def _number_records(records: list[dict[str, Any]]) -> list[dict[str, Any]]: + """Attach Web-only cursors without storing them in the search state.""" + return [dict(record, seq=index) for index, record in enumerate(records, 1)] + + +def _sanitize_json_value(value: Any) -> Any: + """Return a standards-compliant JSON value by replacing non-finite floats.""" + if isinstance(value, float): + return value if math.isfinite(value) else None + if isinstance(value, dict): + return {key: _sanitize_json_value(item) for key, item in value.items()} + if isinstance(value, list): + return [_sanitize_json_value(item) for item in value] + if isinstance(value, tuple): + return [_sanitize_json_value(item) for item in value] + return value + + +def _strip_detail(record: dict[str, Any]) -> dict[str, Any]: + return {k: v for k, v in record.items() if k != "detail"} + + +def _with_core_derivatives( + record: dict[str, Any], + records_by_id: dict[str, dict[str, Any]] | None = None, +) -> dict[str, Any]: + record = _with_formula_latex(record) + return _with_tool_summary(record, records_by_id or {}) + + +def _with_formula_latex(record: dict[str, Any]) -> dict[str, Any]: + core = record.get("core") + if not isinstance(core, dict) or core.get("formula_latex"): + return record + formula = core.get("formula") + if not formula: + return record + record = dict(record) + core = dict(core) + try: + core["formula_latex"] = engine.parse(str(formula).replace("^", "**")).to_str(latex=True) + except Exception: + core["formula_latex"] = None + record["core"] = core + return record + + +def _with_tool_summary( + record: dict[str, Any], + records_by_id: dict[str, dict[str, Any]], +) -> dict[str, Any]: + core = record.get("core") + if not isinstance(core, dict) or core.get("tool_summary"): + return record + record = dict(record) + core = dict(core) + output_counts: dict[str, int] = {} + for name in core.get("tool_names") or []: + if name: + output_counts[str(name)] = output_counts.get(str(name), 0) + 1 + prompt_counts = _prompt_tool_counts(record.get("detail", {}).get("prompt", [])) + ancestor_counts = _ancestor_tool_counts(record, records_by_id) + for name, count in ancestor_counts.items(): + prompt_counts[name] = max(prompt_counts.get(name, 0), count) + names = sorted(set(prompt_counts) | set(output_counts)) + core["tool_summary"] = [ + { + "name": name, + "display_name": name.replace("_", " ").title(), + "prompt_count": prompt_counts.get(name, 0), + "output_count": output_counts.get(name, 0), + } + for name in names + ] + record["core"] = core + return record + + +def _ancestor_tool_counts( + record: dict[str, Any], + records_by_id: dict[str, dict[str, Any]], + seen: set[str] | None = None, +) -> dict[str, int]: + seen = seen or set() + counts: dict[str, int] = {} + for parent in record.get("parents") or []: + if not isinstance(parent, dict): + continue + parent_id = parent.get("node_id") + if not parent_id or parent_id in seen: + continue + parent_record = records_by_id.get(parent_id) + if not parent_record: + continue + seen.add(parent_id) + for name in (parent_record.get("core") or {}).get("tool_names") or []: + if name: + name = str(name) + counts[name] = counts.get(name, 0) + 1 + for name, count in _ancestor_tool_counts(parent_record, records_by_id, seen).items(): + counts[name] = counts.get(name, 0) + count + return counts + + +def _prompt_tool_counts(prompt: list[Any]) -> dict[str, int]: + counts: dict[str, int] = {} + if not isinstance(prompt, list): + return counts + for msg in prompt: + if not isinstance(msg, dict): + continue + if msg.get("role") == "tool" and msg.get("name"): + name = str(msg["name"]) + counts[name] = counts.get(name, 0) + 1 + if counts: + return counts + for msg in prompt: + if not isinstance(msg, dict): + continue + for call in msg.get("tool_calls") or []: + if not isinstance(call, dict): + continue + name = call.get("name") or (call.get("function") or {}).get("name") + if name: + name = str(name) + counts[name] = counts.get(name, 0) + 1 + return counts diff --git a/src/sr_harness/web/conversations.py b/src/sr_harness/web/conversations.py new file mode 100644 index 0000000000000000000000000000000000000000..62fc33b6de134d1068f291726ef43581da4e86cc --- /dev/null +++ b/src/sr_harness/web/conversations.py @@ -0,0 +1,981 @@ +"""Persistent conversation registry for the interactive Web workbench.""" + +from __future__ import annotations + +import json +import logging +import os +import shutil +import tempfile +import threading +import time +import uuid +import zipfile +from contextvars import ContextVar +from datetime import datetime, timezone +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from fastapi import Body, HTTPException, Request +from fastapi.responses import FileResponse, JSONResponse +from starlette.background import BackgroundTask +from starlette.concurrency import run_in_threadpool + +from .session import InteractiveSession +from .isolation import request_work_keys, request_session_lease, request_mutating + +if TYPE_CHECKING: + from ..runtime.workspace import Workspace + + +CLIENT_COOKIE = "sr_harness_client" +CONVERSATION_HEADER = "X-SR-Harness-Conversation" +CONVERSATION_QUERY = "conversation" +DEFAULT_CONVERSATION_NAME = "Unnamed Conversation" +# This is a cache lifetime, not a browser-visible conversation lifetime. An +# evicted transient is reconstructed with the same ID from the next request. +TRANSIENT_IDLE_SECONDS = 60 * 60 + + +def _now() -> str: + return datetime.now(timezone.utc).isoformat() + + +class ConversationSessionProxy: + """Resolve attribute access to the session bound to the current request.""" + + def __init__(self, registry: "ConversationRegistry"): + object.__setattr__(self, "_registry", registry) + object.__setattr__(self, "_current", ContextVar("sr_harness_session", default=None)) + + def bind(self, session: InteractiveSession): + return self._current.set(session) + + def reset(self, token) -> None: + self._current.reset(token) + + def current_session(self) -> InteractiveSession: + session = self._current.get() + if session is None: + raise RuntimeError("No InteractiveSession is bound to the current request") + return session + + def __getattr__(self, name: str): + return getattr(self.current_session(), name) + + def __setattr__(self, name: str, value: Any) -> None: + setattr(self.current_session(), name, value) + + +class ConversationRegistry: + """Persist conversation metadata and lazily own one session per conversation.""" + + def __init__( + self, + workspace_dir: str | Path, + *, + workspace_files: list[str] | None = None, + isolate_users: bool = False, + run_root: str | Path | None = None, + persist_sessions: bool = False, + persistence_interval: float = 5.0, + read_only: bool = False, + ): + self.workspace_dir = Path(workspace_dir).expanduser().resolve() + self.read_only = bool(read_only) + if self.read_only: + if not self.workspace_dir.is_dir(): + raise FileNotFoundError( + f"Read-only workspace directory does not exist: {self.workspace_dir}" + ) + else: + self.workspace_dir.mkdir(parents=True, exist_ok=True) + self.manifest_path = self.workspace_dir / "conversations.json" + self.visit_log_path = self.workspace_dir / "conversation-visits.jsonl" + self.workspaces_dir = self.workspace_dir / "workspaces" + self.sessions_dir = self.workspace_dir / "sessions" + self.runs_dir = ( + Path(run_root).expanduser().resolve() + if run_root is not None else self.workspace_dir / "runs" + ) + if not self.read_only: + self.workspaces_dir.mkdir(exist_ok=True) + self.sessions_dir.mkdir(exist_ok=True) + self.runs_dir.mkdir(parents=True, exist_ok=True) + self.workspace_files = list(workspace_files or []) + self.isolate_users = bool(isolate_users) + if self.read_only and self.workspace_files: + raise ValueError("Read-only conversation registries cannot add workspace mounts") + self.persist_sessions = bool(persist_sessions) and not self.read_only + self.persistence_interval = max(1.0, float(persistence_interval)) + self.lock = threading.RLock() + self._active_lock = threading.Lock() + self._persistence_stop = threading.Event() + self._persistence_thread: threading.Thread | None = None + self._persistence_errors: dict[str, Exception] = {} + self._saved_idle_revisions: dict[str, str] = {} + self._sessions: dict[str, InteractiveSession] = {} + self._session_locks: dict[str, threading.Lock] = {} + self._transient_records: dict[str, dict[str, Any]] = {} + self._transient_clients: dict[str, str] = {} + self._transient_roots: dict[str, tempfile.TemporaryDirectory] = {} + self._transient_last_seen: dict[str, float] = {} + self._active_requests: dict[str, int] = {} + self._retired_transient_roots: dict[str, tempfile.TemporaryDirectory] = {} + self._read_only_refresh_at = 0.0 + self.read_only_refresh_interval = 30.0 + self._snapshot_signatures: dict[str, tuple[int, int, int] | None] = {} + self._records = self._load_records() + if not self._records and self.read_only: + raise ValueError("Read-only conversation registry contains no conversations") + self.session_proxy = ConversationSessionProxy(self) + if self.persist_sessions: + self._persistence_thread = threading.Thread( + target=self._persistence_loop, + name="sr-harness-session-persistence", + daemon=True, + ) + self._persistence_thread.start() + + @property + def default_session(self) -> InteractiveSession: + self._refresh_read_only() + with self.lock: + record = next((item for item in self._records if not item["archived"]), None) + if record is None: + if self.read_only: + raise RuntimeError("Read-only conversation registry has no active conversation") + record = self._create_record(owner_id=None) + return self._session_for(record) + + def _load_records(self) -> list[dict[str, Any]]: + if not self.manifest_path.exists(): + if self.read_only: + raise FileNotFoundError( + f"Read-only conversation registry does not exist: {self.manifest_path}" + ) + return [] + try: + payload = json.loads(self.manifest_path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + raise ValueError(f"Unable to load conversation registry: {exc}") from exc + if not isinstance(payload, dict) or set(payload) != {"version", "conversations"}: + raise ValueError("Conversation registry does not match the current schema") + if payload["version"] != 1: + raise ValueError("Unsupported conversation registry version") + records = payload["conversations"] + if not isinstance(records, list): + raise ValueError("Conversation registry must contain a conversations list") + required = { + "id", "name", "owner_id", "workspace", "run_dir", "created_at", + "updated_at", "archived", + } + for record in records: + if not isinstance(record, dict) or set(record) != required: + raise ValueError("Conversation registry contains an invalid record") + if not all( + isinstance(record[key], str) and record[key] + for key in required - {"owner_id", "archived"} + ): + raise ValueError("Conversation registry record fields must be non-empty strings") + if record["owner_id"] is not None and not isinstance(record["owner_id"], str): + raise ValueError("Conversation owner_id must be a string or None") + if not isinstance(record["archived"], bool): + raise ValueError("Conversation archived must be a boolean") + return records + + @staticmethod + def _snapshot_signature(path: Path) -> tuple[int, int, int] | None: + try: + stat = path.stat() + return stat.st_ino, stat.st_mtime_ns, stat.st_size + except FileNotFoundError: + return None + + def _refresh_read_only(self) -> None: + """Refresh metadata and invalidate changed snapshots at most every 30 seconds. + + Existing requests retain their session object; subsequent requests lazily + restore the new snapshot in a worker thread. No source files are written. + """ + if not self.read_only: + return + with self.lock: + now = time.monotonic() + if now < self._read_only_refresh_at: + return + self._read_only_refresh_at = now + self.read_only_refresh_interval + try: + records = self._load_records() + signatures = { + record["id"]: self._snapshot_signature(self._session_snapshot_path(record)) + for record in records if record["id"] in self._sessions + } + except (OSError, ValueError): + # Keep the last usable view during a transient source read failure. + return + self._records = records + for conversation_id in list(self._sessions): + if (conversation_id not in signatures or + signatures[conversation_id] != self._snapshot_signatures.get(conversation_id)): + self._sessions.pop(conversation_id, None) + self._snapshot_signatures.pop(conversation_id, None) + + def _write_records(self, records: list[dict[str, Any]] | None = None) -> None: + if self.read_only: + raise PermissionError("Conversation registry is read-only") + payload = {"version": 1, "conversations": records if records is not None else self._records} + temporary = self.manifest_path.with_suffix(".json.tmp") + temporary.write_text( + json.dumps(payload, ensure_ascii=False, indent=2) + "\n", + encoding="utf-8", + ) + temporary.replace(self.manifest_path) + + def _create_record( + self, + *, + owner_id: str | None, + name: str | None = None, + ) -> dict[str, Any]: + if self.read_only: + raise PermissionError("Conversation registry is read-only") + if name is None: + name = DEFAULT_CONVERSATION_NAME + else: + name = name.strip() + if not name: + raise ValueError("Conversation name cannot be empty") + conversation_id = uuid.uuid4().hex + created_at = _now() + run_dir = self.runs_dir / conversation_id + try: + stored_run_dir = str(run_dir.relative_to(self.workspace_dir)) + except ValueError: + stored_run_dir = str(run_dir) + record = { + "id": conversation_id, + "name": name, + "owner_id": owner_id, + "workspace": str(Path("workspaces") / conversation_id), + "run_dir": stored_run_dir, + "created_at": created_at, + "updated_at": created_at, + "archived": False, + } + workspace = self.workspace_dir / record["workspace"] + workspace.mkdir(parents=True, exist_ok=False) + run_dir.mkdir(parents=True, exist_ok=True) + self._session_dir(record).mkdir(parents=True, exist_ok=True) + self._records.append(record) + self._write_records() + return record + + def _append_visit_event( + self, + event: str, + *, + client_id: str, + transient_id: str, + conversation_id: str | None = None, + reason: str | None = None, + ) -> None: + """Append an analytics event without turning a visit into a conversation.""" + if self.read_only: + return + payload = { + "timestamp": _now(), + "event": event, + "visitor_id": client_id, + "transient_id": transient_id, + } + if conversation_id is not None: + payload["conversation_id"] = conversation_id + if reason is not None: + payload["reason"] = reason + with self.visit_log_path.open("a", encoding="utf-8") as stream: + stream.write(json.dumps(payload, ensure_ascii=False) + "\n") + + def _create_transient_record( + self, + client_id: str, + *, + name: str | None = None, + source: str = "visit", + conversation_id: str | None = None, + ) -> dict[str, Any]: + """Create a temporary browser session that is absent from the registry manifest.""" + if self.read_only: + raise PermissionError("Conversation registry is read-only") + if name is None: + name = DEFAULT_CONVERSATION_NAME + else: + name = name.strip() + if not name: + raise ValueError("Conversation name cannot be empty") + conversation_id = conversation_id or uuid.uuid4().hex + temporary = tempfile.TemporaryDirectory(prefix="sr-harness-visit-") + root = Path(temporary.name) + created_at = _now() + record = { + "id": conversation_id, + "name": name, + "owner_id": client_id if self.isolate_users else None, + "workspace": str(root / "workspace"), + "run_dir": str(root / "run"), + "created_at": created_at, + "updated_at": created_at, + "archived": False, + } + (root / "workspace").mkdir() + (root / "run").mkdir() + (root / "session").mkdir() + self._transient_records[conversation_id] = record + self._transient_clients[conversation_id] = client_id + self._transient_roots[conversation_id] = temporary + self._transient_last_seen[conversation_id] = time.monotonic() + self._append_visit_event( + "visit_started", + client_id=client_id, + transient_id=conversation_id, + reason=source, + ) + return record + + def _transient_visible(self, record: dict[str, Any], client_id: str) -> bool: + return self._transient_clients.get(record["id"]) == client_id + + def _reusable_transient_id(self, selected_id: str | None) -> str | None: + """Return a safe expired transient ID that can be reconstructed.""" + if selected_id is None or len(selected_id) != 32: + return None + try: + if uuid.UUID(hex=selected_id).hex != selected_id: + return None + except ValueError: + return None + if ( + selected_id in self._transient_records + or any(record["id"] == selected_id for record in self._records) + ): + return None + return selected_id + + def _retire_transient_root( + self, + conversation_id: str, + temporary: tempfile.TemporaryDirectory | None, + ) -> None: + if temporary is None: + return + with self._active_lock: + if self._active_requests.get(conversation_id, 0): + self._retired_transient_roots[conversation_id] = temporary + return + temporary.cleanup() + + def _drop_transient(self, conversation_id: str) -> None: + session = self._sessions.pop(conversation_id, None) + if session is not None: + session.interrupt_active_work() + self._transient_records.pop(conversation_id, None) + self._transient_clients.pop(conversation_id, None) + self._transient_last_seen.pop(conversation_id, None) + temporary = self._transient_roots.pop(conversation_id, None) + self._retire_transient_root(conversation_id, temporary) + + def _sweep_transients(self) -> None: + cutoff = time.monotonic() - TRANSIENT_IDLE_SECONDS + expired = [ + conversation_id + for conversation_id, last_seen in self._transient_last_seen.items() + if last_seen < cutoff and not self._active_requests.get(conversation_id, 0) + ] + for conversation_id in expired: + self._drop_transient(conversation_id) + + def acquire(self, conversation_id: str) -> None: + with self._active_lock: + self._active_requests[conversation_id] = ( + self._active_requests.get(conversation_id, 0) + 1 + ) + + def release(self, conversation_id: str) -> None: + with self._active_lock: + remaining = self._active_requests.get(conversation_id, 0) - 1 + if remaining > 0: + self._active_requests[conversation_id] = remaining + return + self._active_requests.pop(conversation_id, None) + temporary = self._retired_transient_roots.pop(conversation_id, None) + if temporary is not None: + temporary.cleanup() + + def _materialize( + self, + record: dict[str, Any], + *, + client_id: str, + reason: str, + ) -> tuple[dict[str, Any], InteractiveSession]: + """Promote a temporary visit to a durable conversation before mutation.""" + conversation_id = record["id"] + if conversation_id not in self._transient_records: + return record, self._session_for(record) + transient_session = self._sessions.pop(conversation_id, None) + snapshot = ( + transient_session.export_persistent_state() + if transient_session is not None + else None + ) + old_workspace = self._record_path(record, "workspace") + old_run_dir = self._record_path(record, "run_dir") + old_session_dir = self._session_dir(record) + workspace = self.workspaces_dir / conversation_id + run_dir = self.runs_dir / conversation_id + session_dir = self.sessions_dir / conversation_id + shutil.copytree(old_workspace, workspace) + shutil.copytree(old_run_dir, run_dir) + shutil.copytree(old_session_dir, session_dir) + try: + stored_run_dir = str(run_dir.relative_to(self.workspace_dir)) + except ValueError: + stored_run_dir = str(run_dir) + record["workspace"] = str(Path("workspaces") / conversation_id) + record["run_dir"] = stored_run_dir + record["updated_at"] = _now() + self._transient_records.pop(conversation_id) + self._transient_clients.pop(conversation_id) + self._transient_last_seen.pop(conversation_id, None) + temporary = self._transient_roots.pop(conversation_id) + self._retire_transient_root(conversation_id, temporary) + self._records.append(record) + self._write_records() + session = self._session_for(record) + if snapshot is not None: + session.restore_persistent_state(snapshot) + self._append_visit_event( + "conversation_persisted", + client_id=client_id, + transient_id=conversation_id, + conversation_id=conversation_id, + reason=reason, + ) + return record, session + + def _record_path(self, record: dict[str, Any], field: str) -> Path: + path = Path(record[field]) + return path if path.is_absolute() else self.workspace_dir / path + + def _session_dir(self, record: dict[str, Any]) -> Path: + temporary = self._transient_roots.get(record["id"]) + if temporary is not None: + return Path(temporary.name) / "session" + return self.sessions_dir / record["id"] + + def _session_for(self, record: dict[str, Any]) -> InteractiveSession: + conversation_id = record["id"] + with self.lock: + session = self._sessions.get(conversation_id) + if session is not None: + return session + session_lock = self._session_locks.setdefault(conversation_id, threading.Lock()) + with session_lock: + with self.lock: + session = self._sessions.get(conversation_id) + if session is not None: + return session + workspace = self._record_path(record, "workspace") + session_dir = self._session_dir(record) + run_dir = self._record_path(record, "run_dir") + snapshot_path = session_dir / "interactive-session.json" + if self.read_only: + missing = [path for path in (workspace, session_dir, run_dir) if not path.is_dir()] + if missing: + raise FileNotFoundError( + "Read-only conversation storage is incomplete: " + + ", ".join(str(path) for path in missing) + ) + else: + workspace.mkdir(parents=True, exist_ok=True) + session_dir.mkdir(parents=True, exist_ok=True) + session = InteractiveSession( + run_dir.parent, + workspace_files=self.workspace_files, + run_dir=run_dir, + workspace_path=workspace, + env_path=session_dir / ".env", + read_only=self.read_only, + ) + session.conversation_id = conversation_id + signature = self._snapshot_signature(snapshot_path) if self.read_only else None + if (self.persist_sessions or self.read_only) and snapshot_path.is_file(): + try: + snapshot = json.loads(snapshot_path.read_text(encoding="utf-8")) + session.restore_persistent_state(snapshot) + except (OSError, ValueError, TypeError, KeyError, json.JSONDecodeError) as exc: + raise ValueError( + f"Unable to restore conversation {conversation_id}: {exc}" + ) from exc + with self.lock: + self._sessions[conversation_id] = session + if self.read_only: + self._snapshot_signatures[conversation_id] = signature + return session + + def _session_snapshot_path(self, record: dict[str, Any]) -> Path: + return self._session_dir(record) / "interactive-session.json" + + def persist(self) -> None: + """Atomically persist every materialized InteractiveSession.""" + if not self.persist_sessions: + return + with self.lock: + pairs = [ + (record, self._sessions[record["id"]]) + for record in self._records + if record["id"] in self._sessions + ] + errors = {} + for record, session in pairs: + try: + revision = session.idle_persistence_revision() + snapshot_path = self._session_snapshot_path(record) + if (revision is not None and self._saved_idle_revisions.get(record["id"]) == revision + and snapshot_path.is_file()): + continue + snapshot_path.parent.mkdir(parents=True, exist_ok=True) + temporary = snapshot_path.with_suffix(".json.tmp") + temporary.write_text( + json.dumps(session.export_persistent_state(), ensure_ascii=False, separators=(",", ":")) + "\n", + encoding="utf-8", + ) + temporary.replace(snapshot_path) + if revision is not None: + self._saved_idle_revisions[record["id"]] = revision + else: + self._saved_idle_revisions.pop(record["id"], None) + except Exception as exc: + errors[record["id"]] = exc + logging.getLogger(__name__).warning("Unable to persist conversation %s: %s", record["id"], type(exc).__name__) + with self.lock: + self._persistence_errors = errors + if errors: + raise RuntimeError(f"Unable to persist {len(errors)} conversation(s)") from next(iter(errors.values())) + + def _persistence_loop(self) -> None: + while not self._persistence_stop.wait(self.persistence_interval): + try: + self.persist() + except Exception: + # Per-conversation errors are recorded; unrelated sessions remain usable. + logging.getLogger(__name__).warning("Some conversation snapshots could not be saved") + + def _visible(self, record: dict[str, Any], client_id: str) -> bool: + return not record["archived"] and ( + not self.isolate_users or record["owner_id"] == client_id + ) + + def _owned(self, record: dict[str, Any], client_id: str) -> bool: + return not self.isolate_users or record["owner_id"] == client_id + + def resolve( + self, + client_id: str, + selected_id: str | None, + *, + materialize_reason: str | None = None, + load_session: bool = True, + ) -> tuple[dict[str, Any], InteractiveSession | None]: + self._refresh_read_only() + with self.lock: + self._sweep_transients() + visible = [record for record in self._records if self._visible(record, client_id)] + transient = self._transient_records.get(selected_id or "") + if transient is not None and self._transient_visible(transient, client_id): + record = transient + self._transient_last_seen[record["id"]] = time.monotonic() + else: + record = next((item for item in visible if item["id"] == selected_id), None) + if record is None and visible and ( + selected_id is not None or self.read_only or self.isolate_users + ): + record = visible[0] + if record is None: + if self.read_only: + raise RuntimeError("No conversation is visible in read-only mode") + reusable_id = self._reusable_transient_id(selected_id) + record = self._create_transient_record( + client_id, + source="visit_resumed" if reusable_id is not None else "visit", + conversation_id=reusable_id, + ) + if materialize_reason is not None: + return self._materialize( + record, + client_id=client_id, + reason=materialize_reason, + ) + return record, self._session_for(record) if load_session else None + + def list(self, client_id: str, selected_id: str | None = None) -> dict[str, Any]: + self._refresh_read_only() + with self.lock: + records = [record for record in self._records if self._visible(record, client_id)] + records.extend( + record + for record in self._transient_records.values() + if self._transient_visible(record, client_id) + ) + return { + "isolate_users": self.isolate_users, + "read_only": self.read_only, + "persistence_warning": selected_id in self._persistence_errors, + "selected": selected_id, + "conversations": [ + {key: record[key] for key in ("id", "name", "created_at", "updated_at")} + for record in records + ], + } + + def materialize( + self, + client_id: str, + conversation_id: str, + reason: str, + ) -> tuple[dict[str, Any], InteractiveSession]: + """Make a selected temporary conversation durable.""" + with self.lock: + transient = self._transient_records.get(conversation_id) + if transient is not None: + if not self._transient_visible(transient, client_id): + raise KeyError(conversation_id) + return self._materialize( + transient, + client_id=client_id, + reason=reason, + ) + record = next( + ( + item + for item in self._records + if item["id"] == conversation_id and self._visible(item, client_id) + ), + None, + ) + if record is None: + raise KeyError(conversation_id) + return record, self._session_for(record) + + def create(self, client_id: str, name: str | None = None) -> dict[str, Any]: + if self.read_only: + raise PermissionError("Conversation registry is read-only") + with self.lock: + for conversation_id, record in list(self._transient_records.items()): + if self._transient_visible(record, client_id): + self._drop_transient(conversation_id) + record = self._create_transient_record(client_id, name=name, source="new_conversation") + if name is not None: + record, _ = self._materialize( + record, + client_id=client_id, + reason="conversation_named", + ) + return record + + def select(self, client_id: str, conversation_id: str) -> dict[str, Any]: + self._refresh_read_only() + with self.lock: + transient = self._transient_records.get(conversation_id) + if transient is not None and self._transient_visible(transient, client_id): + record = transient + else: + record = next( + ( + item + for item in self._records + if item["id"] == conversation_id and self._visible(item, client_id) + ), + None, + ) + if record is None: + raise KeyError(conversation_id) + self._session_for(record) + return record + + def rename(self, client_id: str, conversation_id: str, name: str) -> dict[str, Any]: + if self.read_only: + raise PermissionError("Conversation registry is read-only") + name = name.strip() + if not name: + raise ValueError("Conversation name cannot be empty") + if len(name) > 120: + raise ValueError("Conversation name cannot exceed 120 characters") + with self.lock: + record = self.select(client_id, conversation_id) + record, _ = self._materialize( + record, + client_id=client_id, + reason="conversation_renamed", + ) + record["name"] = name + record["updated_at"] = _now() + self._write_records() + return record + + def archive( + self, + client_id: str, + conversation_id: str, + selected_id: str, + ) -> tuple[dict[str, Any], dict[str, Any]]: + """Archive a conversation and choose the conversation that remains selected.""" + if self.read_only: + raise PermissionError("Conversation registry is read-only") + with self.lock: + transient = self._transient_records.get(conversation_id) + if transient is not None and self._transient_visible(transient, client_id): + archived = dict(transient, archived=True, updated_at=_now()) + self._drop_transient(conversation_id) + visible = [item for item in self._records if self._visible(item, client_id)] + if not visible: + visible = [ + self._create_transient_record( + client_id, + source="archive_replacement", + ) + ] + selected = next( + (item for item in visible if item["id"] == selected_id), + visible[0], + ) + return archived, selected + record = next( + ( + item + for item in self._records + if item["id"] == conversation_id + and self._owned(item, client_id) + and not item["archived"] + ), + None, + ) + if record is None: + raise KeyError(conversation_id) + record["archived"] = True + record["updated_at"] = _now() + visible = [item for item in self._records if self._visible(item, client_id)] + if not visible: + visible = [self._create_transient_record(client_id, source="archive_replacement")] + selected = next((item for item in visible if item["id"] == selected_id), visible[0]) + self._write_records() + return record, selected + + @staticmethod + def _write_tree( + archive: zipfile.ZipFile, + root: Path, + prefix: str, + *, + workspace: Workspace | None = None, + ) -> None: + if not root.exists(): + return + opener = workspace.safe_open if workspace is not None else open + for current, directory_names, file_names in os.walk(root, followlinks=False): + current_path = Path(current) + directory_names[:] = sorted( + name for name in directory_names + if not (current_path / name).is_symlink() + ) + for name in sorted(file_names): + path = current_path / name + if name == ".env" or path.is_symlink(): + continue + relative = Path(prefix) / path.relative_to(root) + with opener(path, "rb") as input_stream: + with archive.open(relative.as_posix(), "w") as output_stream: + shutil.copyfileobj(input_stream, output_stream) + + def export(self, client_id: str, conversation_id: str) -> tuple[Path, str]: + """Create a temporary ZIP containing a conversation and its retained state.""" + record = self.select(client_id, conversation_id) + session = self._session_for(record) + with self.lock: + metadata = {key: record[key] for key in ("id", "name", "created_at", "updated_at")} + snapshot = session.export_persistent_state() + workspace = self._record_path(record, "workspace") + run_dir = self._record_path(record, "run_dir") + descriptor, archive_name = tempfile.mkstemp(suffix=".zip") + os.close(descriptor) + Path(archive_name).unlink(missing_ok=True) + try: + with zipfile.ZipFile(archive_name, "w", zipfile.ZIP_DEFLATED) as archive: + archive.writestr( + "conversation.json", + json.dumps(metadata, ensure_ascii=False, indent=2) + "\n", + ) + archive.writestr( + "interactive-session.json", + json.dumps(snapshot, ensure_ascii=False, indent=2) + "\n", + ) + self._write_tree( + archive, + workspace, + "workspace", + workspace=session.workspace_manager, + ) + self._write_tree(archive, run_dir, "run") + except Exception: + Path(archive_name).unlink(missing_ok=True) + raise + return Path(archive_name), f"conversation-{conversation_id}.zip" + + def close(self) -> None: + self._persistence_stop.set() + if self._persistence_thread is not None: + self._persistence_thread.join(timeout=self.persistence_interval + 1) + with self.lock: + sessions = list(self._sessions.values()) + for session in sessions: + session.interrupt_active_work() + for session in sessions: + for thread in (session.thread, session.data_thread, session.evaluator_agent_thread): + if thread: + thread.join(timeout=2) + self.persist() + for temporary in [ + *self._transient_roots.values(), + *self._retired_transient_roots.values(), + ]: + temporary.cleanup() + self._transient_roots.clear() + self._retired_transient_roots.clear() + + +def mount_conversations(app, registry: ConversationRegistry) -> None: + """Bind browser identity, conversation selection, and registry endpoints.""" + + def persistence_timing(request: Request) -> tuple[str | None, str | None]: + path = request.url.path + method = request.method + agent_routes = { + ("POST", "/api/session/start"), + ("POST", "/api/data/agent"), + ("POST", "/api/evaluator/agent/start"), + ("POST", "/api/control/command"), + } + if (method, path) in agent_routes: + return "agent_used", None + workspace_mutation = ( + (path.startswith("/api/workspace") and method in {"POST", "PUT", "PATCH", "DELETE"}) + or (method, path) in { + ("POST", "/api/data/demo"), + ("PUT", "/api/data/selection"), + ("PUT", "/api/data/descriptions"), + ("PUT", "/api/evaluator"), + } + ) + return (None, "workspace_modified") if workspace_mutation else (None, None) + + @app.middleware("http") + async def bind_conversation(request: Request, call_next): + client_id = request.cookies.get(CLIENT_COOKIE) or uuid.uuid4().hex + path = request.url.path + public = path in {"/", "/viewer", "/api/version", "/health"} or path.startswith("/static/") + selected_id = request.headers.get(CONVERSATION_HEADER) or request.query_params.get(CONVERSATION_QUERY) + keys = ("client:" + client_id,) + (("conversation:" + selected_id,) if selected_id else ()) + work_token = request_work_keys.set(keys) + mutation_token = request_mutating.set(request.method not in {"GET", "HEAD", "OPTIONS"}) + request.state.client_id = client_id + try: + if public: + response = await call_next(request) + else: + before_reason, after_reason = persistence_timing(request) + # Listing/creating/selecting chats must not restore a broken current snapshot. + metadata_only = path == "/api/conversations" or ( + path.startswith("/api/conversations/") and path.endswith("/select") + ) + record, session = await app.state.work_pool.run( + registry.resolve, client_id, selected_id, + materialize_reason=before_reason, load_session=not metadata_only, + ) + request_work_keys.set(("client:" + client_id, "conversation:" + record["id"])) + request.state.conversation_id = record["id"] + registry.acquire(record["id"]) + token = registry.session_proxy.bind(session) + lease_token = request_session_lease.set((registry, record["id"])) + try: + response = await call_next(request) + if after_reason is not None and response.status_code < 400: + await app.state.work_pool.run(registry.materialize, client_id, record["id"], after_reason) + finally: + if session is not None and request.method not in {"GET", "HEAD", "OPTIONS"}: + session._persistence_generation = getattr(session, "_persistence_generation", 0) + 1 + registry.session_proxy.reset(token) + request_session_lease.reset(lease_token) + await run_in_threadpool(registry.release, record["id"]) + response.set_cookie(CLIENT_COOKIE, client_id, httponly=True, samesite="lax", max_age=31536000) + return response + except HTTPException as exc: + return JSONResponse({"detail": exc.detail}, status_code=exc.status_code, headers=exc.headers) + finally: + request_work_keys.reset(work_token) + request_mutating.reset(mutation_token) + + @app.get("/api/conversations") + def conversations(request: Request): + return registry.list(request.state.client_id, request.state.conversation_id) + + @app.post("/api/conversations") + def create_conversation(request: Request, payload: dict = Body(default={})): + record = registry.create( + request.state.client_id, str(payload.get("name", "")).strip() or None + ) + return {key: record[key] for key in ("id", "name", "created_at", "updated_at")} + + @app.post("/api/conversations/{conversation_id}/select") + def select_conversation(conversation_id: str, request: Request): + try: + record = registry.select(request.state.client_id, conversation_id) + except KeyError as exc: + raise HTTPException(404, "Conversation not found") from exc + return {"selected": record["id"]} + + @app.patch("/api/conversations/{conversation_id}") + def rename_conversation(conversation_id: str, request: Request, payload: dict = Body(...)): + try: + record = registry.rename( + request.state.client_id, conversation_id, str(payload.get("name", "")) + ) + except KeyError as exc: + raise HTTPException(404, "Conversation not found") from exc + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + return {key: record[key] for key in ("id", "name", "created_at", "updated_at")} + + @app.delete("/api/conversations/{conversation_id}") + def archive_conversation(conversation_id: str, request: Request): + try: + record, selected = registry.archive( + request.state.client_id, + conversation_id, + request.state.conversation_id, + ) + except KeyError as exc: + raise HTTPException(404, "Conversation not found") from exc + return {"archived": record["id"], "selected": selected["id"]} + + @app.get("/api/conversations/{conversation_id}/export") + def export_conversation(conversation_id: str, request: Request): + try: + archive, filename = registry.export(request.state.client_id, conversation_id) + except KeyError as exc: + raise HTTPException(404, "Conversation not found") from exc + return FileResponse( + archive, + filename=filename, + media_type="application/zip", + background=BackgroundTask(archive.unlink, missing_ok=True), + ) diff --git a/src/sr_harness/web/demo_data.py b/src/sr_harness/web/demo_data.py new file mode 100644 index 0000000000000000000000000000000000000000..a262d7e2dbf2a2146483acef2069b7e5c2e62ab7 --- /dev/null +++ b/src/sr_harness/web/demo_data.py @@ -0,0 +1,139 @@ +"""Deterministic sample datasets exposed by the interactive web application.""" +from __future__ import annotations + +from typing import Any + +import numpy as np +from scipy.integrate import solve_ivp + + +DEMO_KINDS = frozenset({"polynomial", "grouped_parameters", "driven_ode", "kuramoto_ba"}) + + +def _variable(description: str, axes: list[str]) -> dict[str, Any]: + return {"description": description, "axes": axes} + + +def _ba_edges(rng: np.random.Generator, n_nodes: int = 10, attachments: int = 2) -> np.ndarray: + """Build a small Barabási–Albert graph without an optional network package.""" + edges = [(left, right) for left in range(attachments + 1) for right in range(left + 1, attachments + 1)] + degrees = np.zeros(n_nodes, dtype=float) + for left, right in edges: + degrees[left] += 1 + degrees[right] += 1 + for node in range(attachments + 1, n_nodes): + probabilities = degrees[:node] / degrees[:node].sum() + neighbors = rng.choice(node, size=attachments, replace=False, p=probabilities) + for neighbor in neighbors: + edges.append((int(neighbor), node)) + degrees[neighbor] += 1 + degrees[node] += 1 + return np.asarray(edges, dtype=np.int64) + + +def _kuramoto_sample(rng: np.random.Generator) -> tuple[dict[str, np.ndarray], dict[str, Any], str]: + n_nodes = 10 + undirected_edges = _ba_edges(rng, n_nodes=n_nodes) + edges = np.concatenate([undirected_edges, undirected_edges[:, ::-1]], axis=0) + adjacency = np.zeros((n_nodes, n_nodes), dtype=float) + adjacency[edges[:, 0], edges[:, 1]] = 1 + adjacency[edges[:, 1], edges[:, 0]] = 1 + degrees = adjacency.sum(axis=1) + natural_frequencies = rng.normal(0, 0.65, n_nodes) + natural_frequencies -= natural_frequencies.mean() + coupling = 1.35 + + def derivative(_time: float, phases: np.ndarray) -> np.ndarray: + phase_difference = phases[None, :] - phases[:, None] + return natural_frequencies + coupling * (adjacency * np.sin(phase_difference)).sum(axis=1) / degrees + + t = np.linspace(0, 24, 481) + initial = rng.uniform(-np.pi, np.pi, n_nodes) + solution = solve_ivp(derivative, (float(t[0]), float(t[-1])), initial, t_eval=t, rtol=1e-9, atol=1e-11) + if not solution.success: + raise RuntimeError(f"Kuramoto sample integration failed: {solution.message}") + x = solution.y.T + dx_dt = np.stack([derivative(float(time), state) for time, state in zip(t, x)]) + omega = np.broadcast_to(natural_frequencies, x.shape).copy() + arrays = {"t": t, "omega": omega, "x": x, "dx_dt": dx_dt, "A": edges} + manifest = { + "variables": { + "omega": _variable("Angular-frequency measurement at each time and node.", ["t", "node"]), + "x": _variable("Observed oscillator phase at each time and node.", ["t", "node"]), + "dx_dt": _variable("Time derivative of the observed oscillator phase.", ["t", "node"]), + "A": { + **_variable("Directed edge representation of the observed network.", ["edge", "endpoint"]), + "kind": "relation", + }, + }, + "axes": { + "t": {"file": "t.npy", "description": "Simulation time."}, + "node": {"values": [f"node{index + 1}" for index in range(n_nodes)], "description": "Network node."}, + "edge": {"size": len(edges), "description": "Network edge index."}, + "endpoint": {"values": ["target", "source"], "description": "Endpoint role in A."}, + }, + "num_nodes": n_nodes, + } + return arrays, manifest, "dx_dt" + + +def build_demo(kind: str) -> tuple[dict[str, np.ndarray], dict[str, Any], str]: + """Return arrays, a context.data manifest, and the suggested target variable.""" + if kind not in DEMO_KINDS: + raise ValueError(f"Unknown sample dataset: {kind}") + rng = np.random.default_rng(42) + if kind == "polynomial": + x1 = rng.uniform(-2, 2, 240) + x2 = rng.uniform(-1.5, 1.5, 240) + arrays = {"x1": x1, "x2": x2, "y": 1 + x1**2 + 2*x1*x2} + descriptions = { + "x1": "First continuous input variable.", + "x2": "Second continuous input variable.", + "y": "Observed target variable.", + } + elif kind == "grouped_parameters": + x1 = rng.uniform(0.5, 2.5, 300) + x2 = rng.uniform(0.05, 3, 300) + label = rng.choice(np.asarray(["alpha", "beta", "gamma"]), size=300) + group_values = {"alpha": 0.45, "beta": 0.9, "gamma": 1.35} + grouped = np.asarray([group_values[value] for value in label]) + arrays = {"x1": x1, "x2": x2, "label": label, "y": x1*np.exp(-(grouped**2)*x2)} + descriptions = { + "x1": "First continuous input variable.", + "x2": "Second continuous input variable.", + "label": "Categorical input variable with three groups.", + "y": "Observed target variable.", + } + elif kind == "driven_ode": + t = np.linspace(0, 36, 721) + + def derivative(time: float, state: np.ndarray) -> np.ndarray: + x = state[0] + return np.asarray([1.15*np.sin(1.35*time) + 0.42*np.sin(2.7*time) - 0.24*x - 0.075*x**3]) + + solution = solve_ivp(derivative, (float(t[0]), float(t[-1])), [0.35], t_eval=t, rtol=1e-10, atol=1e-12) + if not solution.success: + raise RuntimeError(f"ODE sample integration failed: {solution.message}") + x = solution.y[0] + dx_dt = np.asarray([derivative(float(time), np.asarray([value]))[0] for time, value in zip(t, x)]) + arrays = {"t": t, "x": x, "dx_dt": dx_dt} + manifest = { + "variables": { + "x": _variable("Observed state trajectory.", ["t"]), + "dx_dt": _variable("Time derivative of the observed oscillatory state x.", ["t"]), + }, + "axes": {"t": {"file": "t.npy", "description": "Simulation time."}}, + } + return arrays, manifest, "dx_dt" + else: + return _kuramoto_sample(rng) + + sample_count = len(next(iter(arrays.values()))) + manifest = { + "variables": { + name: _variable(description, ["sample"]) + for name, description in descriptions.items() + }, + "axes": {"sample": {"size": sample_count, "description": "Sample index."}}, + } + return arrays, manifest, "y" diff --git a/src/sr_harness/web/isolation.py b/src/sr_harness/web/isolation.py new file mode 100644 index 0000000000000000000000000000000000000000..19578af2e2d55ae902098745bace69d240ad774d --- /dev/null +++ b/src/sr_harness/web/isolation.py @@ -0,0 +1,174 @@ +"""Bound synchronous HTTP work so one conversation cannot monopolize workers.""" +from __future__ import annotations + +import asyncio +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from contextvars import ContextVar, copy_context +from functools import wraps +import inspect +import threading + +from fastapi import HTTPException +from fastapi.routing import APIRoute +from starlette.responses import JSONResponse, Response + +from .responses import worker_json_response + +request_mutating: ContextVar[bool] = ContextVar("request_mutating", default=False) + +request_session_lease: ContextVar = ContextVar("request_session_lease", default=None) + +request_work_keys: ContextVar[tuple[str, ...]] = ContextVar("request_work_keys", default=("unbound",)) + + +class RequestWorkPool: + """No unbounded queue; timed-out work keeps its slot until it really exits. + + Python threads cannot be killed safely. Admission accounting deliberately + outlives the HTTP timeout, preventing retries from spawning unlimited work. + This is containment of HTTP work, not OS-level memory/GIL isolation. + """ + + def __init__(self, *, workers=16, per_key=4, timeout=30.0): + self.workers = workers + self.per_key = per_key + self.timeout = timeout + self._executor = ThreadPoolExecutor(max_workers=workers, thread_name_prefix="srh-http") + self._lock = threading.Lock() + self._counts = Counter() + self._total = 0 + self._closed = False + + async def run(self, function, *args, **kwargs): + keys = tuple(set(request_work_keys.get())) + with self._lock: + if any(self._counts[key] >= self.per_key for key in keys): + raise HTTPException(429, "This conversation has too much pending work; retry shortly.", headers={"Retry-After": "3"}) + if self._total >= self.workers: + raise HTTPException(503, "Request workers are busy; retry shortly.", headers={"Retry-After": "3"}) + self._total += 1 + self._counts.update(keys) + + def release(_future=None): + with self._lock: + self._total -= 1 + for key in keys: + self._counts[key] -= 1 + if not self._counts[key]: + del self._counts[key] + + lease = request_session_lease.get() + try: + if lease is not None: + lease[0].acquire(lease[1]) + except BaseException: + release() + raise + + def completed(future): + try: + if lease is not None: + lease[0].release(lease[1]) + finally: + release(future) + + context = copy_context() + try: + future = self._executor.submit(context.run, function, *args, **kwargs) + except BaseException: + completed(None) + raise + future.add_done_callback(completed) + wrapped = asyncio.wrap_future(future) + # Consume late exceptions even after the HTTP caller has timed out. + wrapped.add_done_callback(lambda task: None if task.cancelled() else task.exception()) + try: + return await asyncio.wait_for(asyncio.shield(wrapped), timeout=self.timeout) + except TimeoutError as exc: + raise HTTPException(504, "This request took too long. It may still be finishing; check its state before retrying.") from exc + + def start(self): + with self._lock: + if self._closed: + self._executor = ThreadPoolExecutor(max_workers=self.workers, thread_name_prefix="srh-http") + self._closed = False + + def close(self): + self._closed = True + self._executor.shutdown(wait=False, cancel_futures=True) + + +def install_route_isolation(app, pool): + class IsolatedRoute(APIRoute): + def __init__(self, path, endpoint, **kwargs): + if not inspect.iscoroutinefunction(endpoint): + original = endpoint + + def execute(*args, **kwargs): + try: + result = original(*args, **kwargs) + return result if isinstance(result, Response) else worker_json_response(result) + finally: + # A timed-out mutating endpoint may finish after middleware exits. + if request_mutating.get() and app.state.conversation_registry is not None: + try: + session = app.state.session.current_session() + except RuntimeError: + session = None + if session is not None: + session._persistence_generation = getattr(session, "_persistence_generation", 0) + 1 + + @wraps(original) + async def endpoint(*args, **kwargs): + return await pool.run(execute, *args, **kwargs) + + # Resolve postponed annotations in the original module, not here. + endpoint.__signature__ = inspect.signature(original, eval_str=True).replace(return_annotation=Response) + super().__init__(path, endpoint, **kwargs) + + app.router.route_class = IsolatedRoute + + +class RequestBodyLimit: + """Reject large bodies before JSON parsing, including chunked requests.""" + + def __init__(self, app, max_bytes=4 * 1024 * 1024): + self.app = app + self.max_bytes = max_bytes + + async def __call__(self, scope, receive, send): + if scope['type'] != 'http' or scope.get('method') in {'GET', 'HEAD', 'OPTIONS'}: + return await self.app(scope, receive, send) + # Upload already streams to disk with its own 256 MiB size check. + if scope.get('path') == '/api/workspace/upload': + return await self.app(scope, receive, send) + limit = self.max_bytes + headers = dict(scope.get('headers', [])) + try: + declared = int(headers.get(b'content-length', b'0')) + except ValueError: + declared = limit + 1 + if declared > limit: + return await JSONResponse({'detail': 'Request exceeds the 4 MiB limit.'}, status_code=413)(scope, receive, send) + # Buffer only small API bodies, then replay them once to the application. + body = bytearray() + while True: + message = await receive() + if message['type'] == 'http.disconnect': + return + body.extend(message.get('body', b'')) + if len(body) > limit: + return await JSONResponse({'detail': 'Request exceeds the 4 MiB limit.'}, status_code=413)(scope, receive, send) + if not message.get('more_body', False): + break + delivered = False + + async def replay(): + nonlocal delivered + if not delivered: + delivered = True + return {'type': 'http.request', 'body': bytes(body), 'more_body': False} + return await receive() + + await self.app(scope, replay, send) diff --git a/src/sr_harness/web/platform.py b/src/sr_harness/web/platform.py new file mode 100644 index 0000000000000000000000000000000000000000..8e1d8018e680e513af9873d412eee69383a22069 --- /dev/null +++ b/src/sr_harness/web/platform.py @@ -0,0 +1,1057 @@ +"""Workspace and lifecycle HTTP endpoints for the interactive workbench.""" + +from __future__ import annotations + +import os +import shutil +import tempfile +import zipfile +from pathlib import Path +from urllib.parse import quote + +import numpy as np +import pandas as pd +from fastapi import Body, HTTPException, Request +from fastapi.responses import FileResponse, StreamingResponse +from starlette.background import BackgroundTask +from starlette.concurrency import run_in_threadpool + +from ..core import json_value, update_context_data_descriptions +from .session import InteractiveSession, SessionStartError +from .responses import worker_json_response, worker_event_response + +MAX_UPLOAD = 256 * 1024 * 1024 + + +def mount_platform(app, session: InteractiveSession): + """Run the ``mount platform`` operation. + + Args: + app: The app value. + session: The session value. + """ + app.state.session = session + + def context_preview_groups(): + with session.lock: + axis_names = session.context.axis_names() + groups = [] + for axis in axis_names: + variables = [ + name for name, dimensions in session.context.variable_axes.items() + if dimensions == (axis,) and session.context.data[name].ndim == 1 + ] + if not variables: + continue + groups.append({ + "id": f"axis:{axis}", + "kind": "axis", + "axis": axis, + "axes": [axis], + "variables": variables, + "shape": [len(session.context.data[axis])], + }) + for name, dimensions in session.context.variable_axes.items(): + value = session.context.data[name] + if value.ndim <= 1: + continue + groups.append({ + "id": f"variable:{name}", + "kind": "relation" if name in session.context.relation_names else "variable", + "variable": name, + "axes": list(dimensions), + "shape": list(value.shape), + "dtype": str(value.dtype), + }) + return groups + + @app.get("/api/session") + def status(): + return worker_json_response(session.snapshot()) + + @app.get("/api/session/capabilities") + def capabilities(agent: str = "search"): + try: + return session.capabilities(agent) + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + + @app.get("/api/session/provider-credential") + def provider_credential(provider: str): + try: + return session.provider_credential(provider) + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + + @app.put("/api/session/provider-credential") + def set_provider_credential(payload: dict = Body(...)): + try: + return session.set_provider_credential( + str(payload.get("provider", "")), + payload.get("api_key"), + ) + except (OSError, ValueError) as exc: + raise HTTPException(400, str(exc)) from exc + + @app.post("/api/session/start") + def start(payload: dict = Body(...)): + try: + return session.start(payload) + except SessionStartError as exc: + raise HTTPException(500, { + "code": "start_response_failed" if exc.started else "start_preflight_failed", + "message": str(exc), + "run_id": exc.run_id, + "started": exc.started, + }) from exc + except (ValueError, OSError) as exc: + raise HTTPException(400, str(exc)) from exc + + @app.post("/api/data/agent") + def prepare_data(payload: dict = Body(...)): + try: + return session.prepare_data(str(payload.get("message", ""))) + except (ValueError, OSError) as exc: + raise HTTPException(400, str(exc)) from exc + + @app.get("/api/data/agent/events") + def data_agent_events(after_seq: int = 0): + return worker_event_response(session.data_interaction_manager, max(0, after_seq)) + + @app.post("/api/data/agent/stop") + def stop_data_preparation(): + try: + return session.stop_data_preparation() + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + + @app.put("/api/data/agent/settings") + def configure_data_agent(payload: dict = Body(...)): + try: + return session.configure_data_agent(payload) + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + + @app.post("/api/data/agent/test") + def test_data_agent_model(payload: dict = Body(...)): + try: + return session.test_data_agent_model(payload) + except Exception as exc: + raise HTTPException(400, str(exc)) from exc + + @app.post("/api/session/test") + def test_model(payload: dict = Body(...)): + try: + return session.test_model(payload) + except Exception as exc: + raise HTTPException(400, str(exc)) from exc + + @app.get("/api/evaluator") + def evaluator_configuration(): + return session.evaluator_configuration() + + @app.put("/api/evaluator") + def configure_evaluator(payload: dict = Body(...)): + try: + return session.configure_evaluator(payload) + except (TypeError, ValueError) as exc: + raise HTTPException(400, str(exc)) from exc + + @app.post("/api/evaluator/test") + def test_evaluator(payload: dict = Body(...)): + try: + return session.test_evaluator(payload) + except Exception as exc: + raise HTTPException(400, str(exc)) from exc + + @app.post("/api/evaluator/agent/start") + def start_evaluator_assistance(payload: dict = Body(...)): + try: + return session.start_evaluator_assistance(payload) + except (OSError, ValueError) as exc: + raise HTTPException(400, str(exc)) from exc + + @app.get("/api/evaluator/agent/events") + def evaluator_agent_events(after_seq: int = 0): + return worker_event_response(session.evaluator_interaction_manager, max(0, after_seq)) + + @app.post("/api/evaluator/agent/stop") + def stop_evaluator_assistance(): + try: + return session.stop_evaluator_assistance() + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + + @app.put("/api/evaluator/agent/settings") + def configure_evaluator_agent(payload: dict = Body(...)): + try: + return session.configure_evaluator_agent(payload) + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + + @app.post("/api/evaluator/agent/test") + def test_evaluator_agent_model(payload: dict = Body(...)): + try: + return session.test_evaluator_agent_model(payload) + except Exception as exc: + raise HTTPException(400, str(exc)) from exc + + @app.get("/api/data/context") + def data_context(rows: int = 300): + rows = max(1, min(rows, 1000)) + with session.lock: + schema = session.context.schema() + all_axis_names = set(session.context.axis_names()) + groups = {} + for name, value in session.context.data.items(): + if name in all_axis_names or value.ndim != 1: + continue + key = tuple(session.context.variable_axes.get(name, (f"length:{len(value)}",))) + groups.setdefault(key, []).append(name) + preferred = next(( + names for names in groups.values() + if session.context.target in names + ), None) + names = preferred or max(groups.values(), key=lambda item: (len(item), item), default=[]) + total = len(session.context.data[names[0]]) if names else 0 + referenced_axes = list(dict.fromkeys( + axis + for name in names + for axis in session.context.variable_axes.get(name, ()) + )) + matching_axes = [name for name in all_axis_names if len(session.context.data[name]) == total] + axis_names = [ + name for name in referenced_axes if name in matching_axes + ] + [ + name for name in matching_axes if name not in referenced_axes + ] + preview_columns = [*axis_names, *names] + columns = [ + *session.context.axis_names(), + *(name for name in session.context.data if name not in all_axis_names), + ] + arrays = { + **{name: session.context.data[name] for name in axis_names}, + **{name: session.context.data[name] for name in names}, + } + count = min(total, rows) + records = [ + {name: json_value(arrays[name][index]) for name in preview_columns} + for index in range(count) + ] + descriptions = { + name: session.context.variable_descriptions.get(name, "") + for name in session.context.data + } + return { + **json_value(schema), + "preview_groups": context_preview_groups(), + "columns": columns, + "preview_columns": preview_columns, + "column_kinds": { + **{name: "axis" for name in all_axis_names}, + **{name: "variable" for name in session.context.data if name not in all_axis_names}, + }, + "rows": total, + "variable_descriptions": descriptions, + "data": records, + "truncated": total > count, + } + + @app.get("/api/data/context/preview") + def data_context_preview(group: str, limit: int = 100): + limit = max(1, min(limit, 300)) + with session.lock: + groups = {item["id"]: item for item in context_preview_groups()} + selected = groups.get(group) + if selected is None: + raise HTTPException(404, "Unknown context data preview group") + if selected["kind"] == "axis": + axis = selected["axis"] + columns = [axis, *selected["variables"]] + arrays = {name: session.context.data[name] for name in columns} + size = len(arrays[axis]) + count = min(size, limit) + return { + **selected, + "dtype": str(arrays[axis].dtype), + "columns": columns, + "column_kinds": {axis: "axis"} | {name: "variable" for name in selected["variables"]}, + "data": [ + {name: json_value(arrays[name][index]) for name in columns} + for index in range(count) + ], + "truncated": size > count, + } + + name = selected["variable"] + value = session.context.data[name] + axes = selected["axes"] + if selected["kind"] == "relation": + num_nodes = session.context.num_nodes or 0 + relation_limit = min(limit, len(value)) + candidate_axes = [] + for order, axis in enumerate(session.context.axis_names()): + if len(session.context.data[axis]) != num_nodes: + continue + uses_as_structure_axis = sum( + dimensions and dimensions[-1] == axis + for variable, dimensions in session.context.variable_axes.items() + if variable not in session.context.relation_names + and variable not in session.context.variable_structures + ) + if uses_as_structure_axis: + candidate_axes.append((-uses_as_structure_axis, order, axis)) + node_axis = min(candidate_axes)[2] if candidate_axes else None + labels = ( + session.context.data[node_axis] + if node_axis is not None else np.arange(num_nodes) + ) + max_nodes = 160 + if num_nodes <= max_nodes: + node_ids = list(range(num_nodes)) + else: + node_ids = [] + seen = set() + for row in value[:relation_limit]: + for endpoint in row: + endpoint = int(endpoint) + if endpoint not in seen and len(node_ids) < max_nodes: + seen.add(endpoint) + node_ids.append(endpoint) + visible_nodes = set(node_ids) + coordinates = [ + row for row in value[:relation_limit] + if all(int(endpoint) in visible_nodes for endpoint in row) + ] + return { + **selected, + "description": session.context.variable_descriptions.get(name, ""), + "values": json_value(value[:relation_limit]), + "axis_values": { + axis: json_value(session.context.data[axis][:limit]) + for axis in axes if axis in session.context.data + }, + "node_axis": node_axis, + "nodes": [{"id": node, "label": json_value(labels[node])} for node in node_ids], + "coordinates": json_value(np.asarray(coordinates)), + "endpoint_count": int(value.shape[1]), + "relation_count": int(value.shape[0]), + "truncated": (len(coordinates) < len(value) or len(node_ids) < num_nodes), + } + result = { + **selected, + "description": session.context.variable_descriptions.get(name, ""), + "axis_values": {axis: json_value(session.context.data[axis][:limit]) for axis in axes}, + "axis_truncated": {axis: len(session.context.data[axis]) > limit for axis in axes}, + } + if value.ndim == 2: + row_count = min(value.shape[0], limit) + column_count = min(value.shape[1], limit) + result.update({ + "values": json_value(value[:row_count, :column_count]), + "truncated": [value.shape[0] > row_count, value.shape[1] > column_count], + }) + elif value.ndim >= 3: + flattened = value.reshape(-1) + result["sample_values"] = json_value(flattened[:min(8, flattened.size)]) + if value.dtype.kind in "iufcb" and flattened.size: + numeric = np.asarray(flattened, dtype=float) + finite = numeric[np.isfinite(numeric)] + if finite.size: + result["value_range"] = [float(finite.min()), float(finite.max())] + return result + + @app.get("/api/data/context/plot") + def data_context_plot( + x: str, y: str, hue: str | None = None, size: str | None = None, limit: int = 2000, + ): + limit = max(1, min(limit, 5000)) + with session.lock: + selected = { + channel: name + for channel, name in {"x": x, "y": y, "hue": hue, "size": size}.items() + if name + } + missing = sorted(set(selected.values()) - set(session.context.data)) + if missing: + raise HTTPException(404, f"Unknown context variables: {missing}") + axis_names = set(session.context.axis_names()) + dimensions = { + name: ((name,) if name in axis_names else session.context.variable_axes[name]) + for name in selected.values() + } + repeated = { + name: axes for name, axes in dimensions.items() if len(set(axes)) != len(axes) + } + if repeated: + raise HTTPException(400, f"Repeated axis names are not supported: {repeated}") + broadcast_axes = list( + dict.fromkeys(axis for name in selected.values() for axis in dimensions[name]) + ) + broadcast_shape = tuple(len(session.context.data[axis]) for axis in broadcast_axes) + total = int(np.prod(broadcast_shape, dtype=np.int64)) if broadcast_shape else 1 + count = min(total, limit) + flat_indices = ( + np.arange(total, dtype=np.int64) if total <= limit + else np.linspace(0, total - 1, count, dtype=np.int64) + ) + coordinates = np.unravel_index(flat_indices, broadcast_shape) if broadcast_shape else () + values = {} + numeric = {} + for name in selected.values(): + value = session.context.data[name] + source_axes = dimensions[name] + permutation = sorted( + range(len(source_axes)), + key=lambda index: broadcast_axes.index(source_axes[index]), + ) + ordered_axes = tuple(source_axes[index] for index in permutation) + aligned = np.transpose(value, permutation) if permutation else value + aligned_shape = tuple( + aligned.shape[ordered_axes.index(axis)] if axis in ordered_axes else 1 + for axis in broadcast_axes + ) + broadcast = np.broadcast_to(aligned.reshape(aligned_shape), broadcast_shape) + sampled = ( + broadcast[coordinates] if broadcast_shape else np.asarray([broadcast.item()]) + ) + values[name] = json_value(sampled) + numeric[name] = value.dtype.kind in "iufcb" + return { + "channels": selected, + "axes": broadcast_axes, + "shape": list(broadcast_shape), + "total": total, + "count": count, + "truncated": total > count, + "values": values, + "numeric": numeric, + } + + @app.post("/api/data/context/heatmap") + def data_context_heatmap(payload: dict = Body(...)): + with session.lock: + raw_row = payload.get("row", []) + raw_column = payload.get("column", []) + if not isinstance(raw_row, list) or not isinstance(raw_column, list): + raise HTTPException(400, "row and column must be lists") + row = [str(name) for name in raw_row] + column = [str(name) for name in raw_column] + color = str(payload.get("color", "")) + z = str(payload.get("z", "")) + try: + z_index = int(payload.get("z_index", 0)) + except (TypeError, ValueError) as exc: + raise HTTPException(400, "z_index must be an integer") from exc + axis_names = set(session.context.axis_names()) + names = {*row, *column, *([color] if color else []), *([z] if z else [])} + missing = sorted(names - set(session.context.data)) + if missing: + raise HTTPException(404, f"Unknown context variables: {missing}") + + if color: + if color in axis_names: + raise HTTPException(400, "Color must be a two- or three-dimensional variable") + color_axes = session.context.variable_axes[color] + if len(color_axes) not in {2, 3}: + raise HTTPException(400, "Color must be a two- or three-dimensional variable") + if len(row) != 1 or row[0] not in axis_names: + raise HTTPException(400, "Row must contain exactly one axis") + if len(column) != 1 or column[0] not in axis_names: + raise HTTPException(400, "Column must contain exactly one axis") + row_axis, column_axis = row[0], column[0] + if ( + row_axis == column_axis + or row_axis not in color_axes + or column_axis not in color_axes + ): + raise HTTPException( + 400, "Row and column must be different axes of the color variable" + ) + remaining = [axis for axis in color_axes if axis not in {row_axis, column_axis}] + if remaining: + if z != remaining[0]: + raise HTTPException( + 400, f"Z must be the remaining color axis {remaining[0]!r}" + ) + z_size = len(session.context.data[z]) + if not 0 <= z_index < z_size: + raise HTTPException(400, f"z_index must be in [0, {z_size})") + matrix = np.take( + session.context.data[color], + z_index, + axis=color_axes.index(z), + ) + remaining_axes = tuple(axis for axis in color_axes if axis != z) + z_value = json_value(session.context.data[z][z_index]) + else: + if z: + raise HTTPException( + 400, "Z is only used with a three-dimensional color variable" + ) + matrix = session.context.data[color] + remaining_axes = color_axes + z_size = 0 + z_value = None + if remaining_axes != (row_axis, column_axis): + matrix = np.transpose( + matrix, + ( + remaining_axes.index(row_axis), + remaining_axes.index(column_axis), + ), + ) + row_labels = session.context.data[row_axis] + column_labels = session.context.data[column_axis] + mode = "tensor" + else: + row_is_axis = len(row) == 1 and row[0] in axis_names + column_is_axis = len(column) == 1 and column[0] in axis_names + if row_is_axis == column_is_axis: + raise HTTPException( + 400, + "Place one axis in row or column and aligned one-dimensional variables on the other side", + ) + axis = row[0] if row_is_axis else column[0] + variables = column if row_is_axis else row + if not variables: + raise HTTPException(400, "Select at least one aligned one-dimensional variable") + invalid = [ + name + for name in variables + if name in axis_names or session.context.variable_axes[name] != (axis,) + ] + if invalid: + raise HTTPException(400, f"Variables must use only axis {axis!r}: {invalid}") + arrays = [session.context.data[name] for name in variables] + if row_is_axis: + matrix = np.column_stack(arrays) + row_axis, column_axis = axis, "variables" + row_labels, column_labels = session.context.data[axis], np.asarray(variables) + else: + matrix = np.vstack(arrays) + row_axis, column_axis = "variables", axis + row_labels, column_labels = np.asarray(variables), session.context.data[axis] + z_size = 0 + z_value = None + mode = "aligned_variables" + + row_count = min(matrix.shape[0], 80) + column_count = min(matrix.shape[1], 80) + shown = matrix[:row_count, :column_count] + return { + "mode": mode, + "row_axis": row_axis, + "column_axis": column_axis, + "row_labels": json_value(row_labels[:row_count]), + "column_labels": json_value(column_labels[:column_count]), + "values": json_value(shown), + "shape": list(matrix.shape), + "dtype": str(matrix.dtype), + "numeric": matrix.dtype.kind in "iufcb", + "truncated": row_count < matrix.shape[0] or column_count < matrix.shape[1], + "z_axis": z or None, + "z_index": z_index if z else None, + "z_value": z_value, + "z_size": z_size, + } + + @app.post("/api/data/context/reload") + def reload_data_context(): + try: + return session.reload_context_data() + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + + @app.put("/api/data/selection") + def update_data_selection(payload: dict = Body(...)): + with session.lock: + if session.data_state in {"running", "stopping"}: + raise HTTPException( + 409, + "Wait for the data-preparation agent to finish before changing variable roles", + ) + if session.state not in {"idle", "running"}: + raise HTTPException( + 409, "Variable roles cannot be changed in the current run state" + ) + if session.state == "running": + control_status = session.sr_interaction_manager.status() + if not (control_status["interaction_state"] == "paused"): + raise HTTPException( + 409, + "Pause symbolic regression and wait for the safe-boundary acknowledgement " + "before changing variable roles", + ) + target = str(payload.get("target", "")).strip() + features = payload.get("features") + if not isinstance(features, list) or any( + not isinstance(name, str) for name in features + ): + raise HTTPException(400, "features must be a list of variable names") + try: + descriptions = payload.get("variable_descriptions", {}) + if not isinstance(descriptions, dict) or any( + not isinstance(name, str) or not isinstance(value, str) + for name, value in descriptions.items() + ): + raise ValueError("variable_descriptions must map variable names to text") + descriptions = {name: value.strip() for name, value in descriptions.items()} + manifest_path = session.workspace / "context.data" / "manifest.json" + if manifest_path.is_file(): + update_context_data_descriptions( + manifest_path.parent, + descriptions, + workspace=session.workspace_manager, + ) + change = session.context.update_selection( + target=target, + features=features, + variable_descriptions=descriptions, + ) + except (OSError, ValueError) as exc: + raise HTTPException(400, str(exc)) from exc + session.variable_descriptions = dict(session.context.variable_descriptions) + return { + **change, + "context": session.context.schema(), + } + + @app.put("/api/data/descriptions") + def update_data_descriptions(payload: dict = Body(...)): + with session.lock: + if session.data_state in {"running", "stopping"}: + raise HTTPException( + 409, + "Wait for the data-preparation agent to finish before changing variable descriptions", + ) + if session.state == "running": + control_status = session.sr_interaction_manager.status() + if not (control_status["interaction_state"] == "paused"): + raise HTTPException( + 409, + "Pause symbolic regression and wait for the safe-boundary acknowledgement " + "before changing variable descriptions", + ) + descriptions = payload.get("variable_descriptions", {}) + if not isinstance(descriptions, dict) or any( + not isinstance(name, str) or not isinstance(value, str) + for name, value in descriptions.items() + ): + raise HTTPException( + 400, + "variable_descriptions must map variable names to text", + ) + descriptions = {name: value.strip() for name, value in descriptions.items()} + manifest_path = session.workspace / "context.data" / "manifest.json" + try: + if manifest_path.is_file(): + update_context_data_descriptions( + manifest_path.parent, + descriptions, + workspace=session.workspace_manager, + ) + elif unknown := set(descriptions) - set(session.context.data): + raise ValueError(f"unknown context variables: {sorted(unknown)}") + except (OSError, ValueError) as exc: + raise HTTPException(400, str(exc)) from exc + changed = False + for name in session.context.data: + if ( + name in descriptions + and session.context.variable_descriptions[name] != descriptions[name] + ): + session.context.variable_descriptions[name] = descriptions[name] + changed = True + if changed: + session.context.args.data_revision += 1 + session.variable_descriptions = dict(session.context.variable_descriptions) + return session.context.schema() + + @app.post("/api/session/settings") + def settings(payload: dict = Body(...)): + try: + return session.configure(payload) + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + + def resolve(path, *, access="read"): + try: + return session.resolve(path, access=access) + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + + @app.get("/api/workspace") + def files(path: str = "", recursive: bool = False): + with session.lock: + directory = resolve(path) + if not directory.is_dir(): + raise HTTPException(404, "Directory not found") + readonly_roots = {logical.name for logical in session.workspace_manager.mount_map} + + def list_entries(logical_directory, resolved_directory, ancestors=frozenset()): + try: + identity = (resolved_directory.stat().st_dev, resolved_directory.stat().st_ino) + except FileNotFoundError: + return [] + if identity in ancestors: + return [] + descendants = ancestors | {identity} + entries = [] + for item in resolved_directory.iterdir(): + logical = logical_directory / item.name + try: + resolved = resolve(str(logical)) + is_directory = resolved.is_dir() + mounted = bool(logical.parts and logical.parts[0] in readonly_roots) + locked = not mounted and session.workspace_manager.is_locked(logical) + entry = { + "name": item.name, + "path": str(logical), + "directory": is_directory, + "read_only": mounted or locked, + "mounted": mounted, + "locked": locked, + } + if is_directory: + children = list_entries(logical, resolved, descendants) + entry["size"] = None + if recursive: + entry["children"] = children + else: + with session.workspace_manager.safe_open(resolved, "rb") as stream: + entry["size"] = os.fstat(stream.fileno()).st_size + entries.append(entry) + except (FileNotFoundError, HTTPException): + continue + return sorted( + entries, + key=lambda entry: ( + not entry["directory"], + entry["name"].lower(), + entry["name"], + ), + ) + + entries = list_entries(Path(path), directory) + return {"path": path, "entries": entries} + + @app.get("/api/workspace/size") + def workspace_item_size(path: str): + with session.lock: + item = resolve(path) + if item.is_file(): + with session.workspace_manager.safe_open(item, "rb") as stream: + return {"path": path, "size": os.fstat(stream.fileno()).st_size} + if not item.is_dir(): + raise HTTPException(404, "File or directory not found") + total = 0 + for current, _, filenames in os.walk(item): + relative_directory = Path(current).relative_to(item) + for filename in filenames: + relative = relative_directory / filename + try: + source = resolve(str(Path(path) / relative)) + except HTTPException: + continue + if source.is_file(): + with session.workspace_manager.safe_open(source, "rb") as stream: + total += os.fstat(stream.fileno()).st_size + return {"path": path, "size": total} + + @app.get("/api/workspace/download") + def download(path: str): + with session.lock: + item = resolve(path) + if item.is_file(): + stream = session.workspace_manager.safe_open(item, "rb") + return StreamingResponse( + iter(lambda: stream.read(1024 * 1024), b""), + media_type="application/octet-stream", + headers={ + "Content-Disposition": ("attachment; filename*=UTF-8''" + quote(item.name)), + }, + background=BackgroundTask(stream.close), + ) + if not item.is_dir(): + raise HTTPException(404, "File or directory not found") + descriptor, archive_name = tempfile.mkstemp(suffix=".zip") + os.close(descriptor) + archive = Path(archive_name) + try: + with zipfile.ZipFile( + archive, + mode="w", + compression=zipfile.ZIP_DEFLATED, + ) as output: + for current, directories, filenames in os.walk(item): + current_path = Path(current) + relative_directory = current_path.relative_to(item) + if not directories and not filenames: + output.writestr( + str(Path(item.name) / relative_directory) + "/", + "", + ) + for filename in filenames: + relative = relative_directory / filename + try: + source = resolve(str(Path(path) / relative)) + except HTTPException: + continue + if source.is_file(): + archive_path = (Path(item.name) / relative).as_posix() + with session.workspace_manager.safe_open(source, "rb") as input_stream: + with output.open(archive_path, "w") as output_stream: + shutil.copyfileobj(input_stream, output_stream) + except Exception: + archive.unlink(missing_ok=True) + raise + return FileResponse( + archive, + filename=f"{item.name}.zip", + media_type="application/zip", + background=BackgroundTask(archive.unlink, missing_ok=True), + ) + + @app.get("/api/workspace/preview") + def preview(path: str): + with session.lock: + file = resolve(path) + if not file.is_file(): + raise HTTPException(404, "File not found") + if file.suffix.lower() == ".npy": + try: + with session.workspace_manager.safe_open(file, "rb") as stream: + array = np.load(stream, allow_pickle=False) + text = np.array2string( + array, + threshold=1000, + edgeitems=4, + max_line_width=120, + ) + except (OSError, TypeError, ValueError) as exc: + raise HTTPException( + 400, + f"Unable to preview NPY file safely: {exc}", + ) from exc + truncated = array.size > 1000 or len(text) > 65536 + return { + "kind": "npy", + "shape": list(array.shape), + "dtype": str(array.dtype), + "size": int(array.size), + "text": text[:65536], + "truncated": truncated, + } + with session.workspace_manager.safe_open(file, "rb") as stream: + data = stream.read(65537) + return { + "kind": "text", + "text": data[:65536].decode("utf-8", errors="replace"), + "truncated": len(data) > 65536, + } + + @app.post("/api/workspace/directory") + def create_directory(payload: dict = Body(...)): + path = str(payload.get("path", "")).strip() + if not path: + raise HTTPException(400, "Directory path is required") + with session.lock: + try: + session.workspace_manager.create_directory(path) + except FileExistsError as exc: + raise HTTPException(409, "A file or directory already exists at this path") from exc + except HTTPException: + raise + except (OSError, ValueError) as exc: + raise HTTPException(400, str(exc)) from exc + return {"path": path} + + @app.put("/api/workspace/lock") + def set_workspace_item_lock(payload: dict = Body(...)): + path = str(payload.get("path", "")).strip() + locked = payload.get("locked") + if not path: + raise HTTPException(400, "The workspace root cannot be locked") + if not isinstance(locked, bool): + raise HTTPException(400, "locked must be a boolean") + with session.lock: + try: + session.workspace_manager.set_locked(path, locked) + except (OSError, ValueError) as exc: + raise HTTPException(400, str(exc)) from exc + return {"path": path, "locked": locked} + + @app.patch("/api/workspace") + def move_workspace_item(payload: dict = Body(...)): + source_path = str(payload.get("source", "")).strip() + destination_path = str(payload.get("destination", "")).strip() + if not source_path or not destination_path: + raise HTTPException(400, "Source and destination paths are required") + with session.lock: + try: + session.workspace_manager.move(source_path, destination_path) + except FileNotFoundError as exc: + raise HTTPException(404, "Source file or directory not found") from exc + except FileExistsError as exc: + raise HTTPException( + 409, "A file or directory already exists at the destination" + ) from exc + except HTTPException: + raise + except (OSError, ValueError) as exc: + raise HTTPException(400, str(exc)) from exc + return {"source": source_path, "destination": destination_path} + + @app.delete("/api/workspace") + def delete_workspace_item(path: str): + path = path.strip() + if not path: + raise HTTPException(400, "The workspace root cannot be deleted") + with session.lock: + try: + session.workspace_manager.remove(path, recursive=True) + except FileNotFoundError as exc: + raise HTTPException(404, "File or directory not found") from exc + except HTTPException: + raise + except (OSError, ValueError) as exc: + raise HTTPException(400, str(exc)) from exc + return {"path": path} + + @app.get("/api/data/csv-files") + def csv_files(): + with session.lock: + files = [ + str(relative) + for relative, path in session.workspace_manager.iter_files() + if path.suffix.lower() in {".csv", ".xlsx"} + ] + return {"files": sorted(files)} + + @app.get("/api/data/preview") + def data_preview(path: str, rows: int = 300): + rows = max(5, min(rows, 1000)) + with session.lock: + file = resolve(path) + if file.suffix.lower() not in {".csv", ".xlsx"} or not file.is_file(): + raise HTTPException(400, "Select an existing CSV or Excel file") + try: + with session.workspace_manager.safe_open(file, "rb") as stream: + frame = ( + pd.read_excel(stream, nrows=rows + 1) + if file.suffix.lower() == ".xlsx" + else pd.read_csv(stream, nrows=rows + 1) + ) + except Exception as exc: + raise HTTPException(400, f"Unable to read table: {exc}") from exc + if frame.empty or len(frame.columns) < 2: + raise HTTPException(400, "CSV needs at least two columns and one row") + columns = [str(column) for column in frame.columns] + if len(set(columns)) != len(columns): + raise HTTPException(400, "CSV column names must be unique") + frame.columns = columns + truncated = len(frame) > rows + frame = frame.iloc[:rows] + numeric = {column: bool(pd.api.types.is_numeric_dtype(frame[column])) for column in columns} + serializable = frame.astype(object).where(frame.notna(), None) + serializable = serializable.replace([float("inf"), float("-inf")], None) + records = serializable.to_dict(orient="records") + return { + "path": path, + "columns": columns, + "numeric": numeric, + "rows": records, + "truncated": truncated, + } + + @app.post("/api/data/demo") + def create_demo(payload: dict | None = Body(default=None)): + try: + path = session.create_demo(str((payload or {}).get("kind", "polynomial"))) + except FileExistsError as exc: + raise HTTPException(409, str(exc)) from exc + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + relative = str(path.relative_to(session.workspace)) + size = sum(file.stat().st_size for file in path.iterdir() if file.is_file()) + session.data_interaction_manager.publish_event( + "workspace_changed", + { + "operation": "created", + "path": relative, + "size": size, + }, + ) + return {"path": relative} + + @app.post("/api/data/prompts") + def initial_prompts(payload: dict = Body(...)): + try: + return session.preview_initial_prompts(payload) + except (ValueError, OSError, pd.errors.ParserError) as exc: + raise HTTPException(400, str(exc)) from exc + + @app.put("/api/workspace/upload") + async def upload(request: Request, path: str): + # Keep the staging file beside its destination so the final atomic + # replace also works when the run directory and workspace are on + # different filesystems. + temp = None + size = 0 + def stage(): + with session.lock: + destination = resolve(path, access="create") + if destination.exists(): + raise HTTPException(409, "File already exists; rename it before uploading") + parent = str(Path(path).parent) + if parent != ".": + session.workspace_manager.create_directory( + parent, + parents=True, + exist_ok=True, + ) + fd, temp_name = tempfile.mkstemp( + prefix=".sr-harness-upload-", + dir=session.workspace, + ) + return fd, temp_name, destination + + def finish(temp, destination, size): + with session.lock: + current_destination = resolve(path, access="create") + if current_destination != destination: + raise HTTPException(409, "Workspace changed while the file was uploading") + if destination.exists(): + raise HTTPException(409, "File already exists; rename it before uploading") + session.workspace_manager.replace_file(temp, path) + session.data_interaction_manager.publish_event( + "workspace_changed", + { + "operation": "created", + "path": path, + "size": size, + }, + ) + return {"path": path, "size": size} + try: + fd, temp_name, destination = await app.state.work_pool.run(stage) + temp = Path(temp_name) + output = os.fdopen(fd, "wb") + try: + async for chunk in request.stream(): + size += len(chunk) + if size > MAX_UPLOAD: + raise HTTPException(413, "Maximum file size is 256 MiB") + await app.state.work_pool.run(output.write, chunk) + finally: + await run_in_threadpool(output.close) + return await app.state.work_pool.run(finish, temp, destination, size) + except HTTPException: + raise + except OSError as exc: + raise HTTPException(400, f"Unable to upload file: {exc}") from exc + finally: + if temp is not None: + await run_in_threadpool(temp.unlink, missing_ok=True) diff --git a/src/sr_harness/web/responses.py b/src/sr_harness/web/responses.py new file mode 100644 index 0000000000000000000000000000000000000000..6d77582694b65988d8517d257640aeafe4b0b297 --- /dev/null +++ b/src/sr_harness/web/responses.py @@ -0,0 +1,64 @@ +"""Bound large responses and encode them outside the HTTP event loop.""" +from itertools import chain + +from fastapi import HTTPException +from fastapi.encoders import jsonable_encoder +from fastapi.responses import JSONResponse + +MAX_RESPONSE_BYTES = 8 * 1024 * 1024 +MAX_RESPONSE_NODES = 200_000 +MAX_RESPONSE_DEPTH = 64 + + +def check_response_budget(content): + """Iterative traversal bounds work before recursive JSON encoding. + + Shared references count each time they occur in JSON. Cycles exceed the + depth budget without recursive stack overflow or allocating a huge queue. + """ + stack = [(iter((content,)), 0)] + nodes = 0 + text_bytes = 0 + while stack: + iterator, depth = stack[-1] + try: + value = next(iterator) + except StopIteration: + stack.pop() + continue + nodes += 1 + if nodes > MAX_RESPONSE_NODES or depth > MAX_RESPONSE_DEPTH: + raise HTTPException(413, "Response is too large or deeply nested; use a smaller query or export the conversation.") + if isinstance(value, str): + # Check character count first to avoid encoding a huge single string. + if len(value) > MAX_RESPONSE_BYTES: + raise HTTPException(413, "Response exceeds the 8 MiB limit; use a smaller query or export the conversation.") + text_bytes += len(value.encode('utf-8')) + if text_bytes > MAX_RESPONSE_BYTES: + raise HTTPException(413, "Response exceeds the 8 MiB limit; use a smaller query or export the conversation.") + elif isinstance(value, dict): + stack.append((chain.from_iterable(value.items()), depth + 1)) + elif isinstance(value, (list, tuple, set, frozenset)): + stack.append((iter(value), depth + 1)) + + +def worker_json_response(content): + check_response_budget(content) + encoded = jsonable_encoder(content) + check_response_budget(encoded) + response = JSONResponse(encoded) + if len(response.body) > MAX_RESPONSE_BYTES: + raise HTTPException(413, "Response exceeds the 8 MiB limit; use a smaller query or export the conversation.") + return response + + +def worker_event_response(manager, after_sequence): + """Shrink a page to the response budget without skipping any event cursor.""" + limit = 32 + while True: + try: + return worker_json_response(manager.get_recent_events(after_sequence, limit=limit)) + except HTTPException as exc: + if exc.status_code != 413 or limit == 1: + raise + limit = max(1, limit // 2) diff --git a/src/sr_harness/web/session.py b/src/sr_harness/web/session.py new file mode 100644 index 0000000000000000000000000000000000000000..2044208e5a4c87a94c582753543e54f24c001aaf --- /dev/null +++ b/src/sr_harness/web/session.py @@ -0,0 +1,1966 @@ +"""Single interactive run and observable hooks, without changing the search loop.""" + +from __future__ import annotations + +import json +import ast +import logging +import os +import stat +import tempfile +import threading +import uuid +from pathlib import Path +from types import SimpleNamespace +from typing import Any +from urllib.parse import urlparse + +import numpy as np +from dotenv import dotenv_values, set_key, unset_key + +from ..agents.data_preparation_agent import DataPreparationAgent +from ..agents.evaluator_construction_agent import EvaluatorConstructionAgent +from ..agents.sr_agent_interactive import SRAgentInteractive +from ..api import BaseAPI +from ..core import AgentContext, SearchRunState, json_value, load_context_data +from ..evaluator import DelayRolloutEvaluator, GraphEvaluator, load_custom_evaluator +from ..evaluator.load_custom_evaluator import ( + BUILTIN_EVALUATOR_CLASS_NAMES, + CUSTOM_TEMPLATE, + create_builtin_evaluator, + evaluator_catalog, + evaluator_filename, + evaluator_source, +) +from ..parser import BaseParser +from ..runtime import InteractionManager, ModelRouter, SRInteractionManager +from ..runtime.network import proxy_environment +from ..skills import SkillManager +from ..tools import BaseTool, ModelTestTool, ValidateEvaluatorTool +from ..runtime.workspace import Workspace +from .demo_data import build_demo + + +_logger = logging.getLogger(__name__) +RUNTIME_SETTING_NAMES = ( + "llm_provider", + "llm_model", + "strong_llm_provider", + "strong_llm_model", + "auto_routing", + "tool_parser", + "llm_max_tokens", + "tools", + "skills", + "local_sample_size", + "max_refinement_depth", + "global_width", + "max_restart_loop", + "restart_top_k", + "max_workers", + "validation_fraction", + "split_by", + "split_ood_variable", + "split_random_state", + "ranking_metric", + "larger_is_better", + "force_initial_diagnostics", + "pause_on_truncated_response", + "tool_free_stop_review_rounds", + "stop_guard_mode", + "stop_guard_metric", + "stop_guard_threshold", + "stop_guard_split", + "stop_guard_larger_is_better", +) + +DATA_AGENT_SETTING_NAMES = ( + "llm_provider", + "llm_model", + "tool_parser", + "llm_max_tokens", + "tools", + "skills", + "proxy", +) + +EVALUATOR_CONTEXT_SETTING_NAMES = ( + "validation_fraction", + "split_random_state", + "split_by", + "split_ood_variable", + "ranking_metric", + "larger_is_better", +) + + +class SessionStartError(RuntimeError): + """Report which phase failed while starting an interactive search.""" + + def __init__(self, message: str, *, run_id: str, started: bool): + super().__init__(message) + self.run_id = run_id + self.started = started + + +HIDDEN_CAPABILITY_TOOLS = frozenset({"code_executor"}) +EVALUATOR_DEFAULT_TOOLS = ( + "read_source", + "workspace_shell", + "workspace_code_executor", + "validate_evaluator", + "read_skill", +) +MESSAGE_ACCEPTING_INTERACTION_STATES = frozenset( + { + "running", + "pausing", + "interrupting", + "paused", + } +) + +PROVIDER_API_KEY_VARIABLES = { + "openrouter": "OPENROUTER_API_KEY", + "openai": "OPENAI_API_KEY", + "deepseek": "DEEPSEEK_API_KEY", + "siliconflow": "SILICONFLOW_API_KEY", + "gemini": "GEMINI_API_KEY", + "lmstudio": "LMSTUDIO_API_KEY", +} + + +class InteractiveSession: + """Own one run for the lifetime of the server; no account/session registry.""" + + def __init__( + self, + log_dir, + agent_options=None, + initial_prompt="", + env_path=None, + workspace_files=None, + run_dir=None, + workspace_path=None, + read_only=False, + ): + self.sr_interaction_manager = SRInteractionManager() + self.data_interaction_manager = InteractionManager() + self.evaluator_interaction_manager = InteractionManager() + self.lock = threading.RLock() + self.model_test_lock = threading.Lock() + self.evaluator_agent_lock = threading.Lock() + self.run_id = uuid.uuid4().hex + self.conversation_id = None + self.run_dir = ( + Path(run_dir).expanduser().resolve() + if run_dir is not None + else Path(log_dir).expanduser().resolve() / self.run_id + ) + self.read_only = bool(read_only) + if self.read_only: + if not self.run_dir.is_dir(): + raise FileNotFoundError(f"Read-only run directory does not exist: {self.run_dir}") + else: + self.run_dir.mkdir(parents=True, exist_ok=True) + workspace_root = ( + Path(workspace_path) + if workspace_path is not None + else Path(tempfile.mkdtemp(prefix="sr_workspace_")) + ) + self.workspace_manager = Workspace(workspace_root, read_only=self.read_only) + for source in workspace_files or (): + self.workspace_manager.mount(source) + self.workspace = self.workspace_manager.path + self.evaluator_workspace = self.workspace / "context.evaluator" + self.context = AgentContext(workspace=self.workspace_manager) + self.context.args.save_path = str(self.run_dir) + self._capability_skill_manager = SkillManager( + custom_directory=self.workspace / "skills", + workspace=self.workspace_manager, + ) + self.context.args.skill_manager = self._capability_skill_manager + self.env_path = Path(env_path or self.run_dir / ".env").resolve() + env_values = dotenv_values(self.env_path) if self.env_path.exists() else {} + stored_environment = { + str(name): str(value) for name, value in env_values.items() if value is not None + } + if no_proxy := os.environ.get("NO_PROXY") or os.environ.get("no_proxy"): + stored_environment.setdefault("NO_PROXY", no_proxy) + file_http_proxy = env_values.get("HTTP_PROXY") or env_values.get("http_proxy") + file_https_proxy = env_values.get("HTTPS_PROXY") or env_values.get("https_proxy") + configured_proxy = file_https_proxy or file_http_proxy or "" + self.egress_proxy = os.environ.get("SRH_EGRESS_PROXY", "").strip() + self.context.args.api_environment = proxy_environment( + stored_environment, + user_proxy=configured_proxy, + egress_proxy=self.egress_proxy, + ) + self.settings = { + "llm_provider": "openrouter", + "llm_model": "deepseek/deepseek-v4-flash-0731", + "strong_llm_provider": None, + "strong_llm_model": None, + "auto_routing": True, + "tool_parser": "openai", + "llm_max_tokens": 4096, + "tools": None, + "skills": None, + "max_refinement_depth": 50, + "local_sample_size": 1, + "global_width": 1, + "max_restart_loop": 1, + "restart_top_k": 1, + "max_workers": 0, + "validation_fraction": 0.2, + "split_by": "random", + "split_ood_variable": None, + "split_random_state": 42, + "ranking_metric": "mse", + "larger_is_better": False, + "force_initial_diagnostics": False, + "pause_on_truncated_response": True, + "tool_free_stop_review_rounds": 1, + "stop_guard_mode": "none", + "stop_guard_metric": None, + "stop_guard_threshold": None, + "stop_guard_split": "validation", + "stop_guard_larger_is_better": True, + } + self.settings.update(agent_options or {}) + if self.settings["tools"] is None: + self.settings["tools"] = self.capabilities()["default_tools"] + for name in EVALUATOR_CONTEXT_SETTING_NAMES: + setattr(self.context.args, name, self.settings[name]) + self.data_agent_settings = { + "llm_provider": self.settings["llm_provider"], + "llm_model": self.settings["llm_model"], + "tool_parser": self.settings["tool_parser"], + "llm_max_tokens": self.settings["llm_max_tokens"], + "tools": list(DataPreparationAgent.DEFAULT_TOOLS), + "skills": [ + name + for name in self._capability_skill_manager.load_skills() + if name not in DataPreparationAgent.DEFAULT_EXCLUDED_SKILLS + ], + "proxy": configured_proxy, + } + self.evaluator_agent_settings = { + key: self.data_agent_settings[key] + for key in ("llm_provider", "llm_model", "tool_parser", "llm_max_tokens", "proxy") + } + self.evaluator_agent_settings.update( + { + # This model reliably reaches native tool calls when constructing an + # evaluator; the general SR agent keeps the user's configured model. + "llm_provider": "openrouter", + "llm_model": "qwen/qwen3.5-flash-02-23", + "tools": list(EVALUATOR_DEFAULT_TOOLS), + "skills": [ + name + for name in self._capability_skill_manager.load_skills() + if name != "discover-symbolic-laws" + ], + "llm_max_tokens": max(8192, self.data_agent_settings["llm_max_tokens"]), + } + ) + self.pending_settings = None + self.initial_prompt = initial_prompt + self.prompt_overrides = {} + self.variable_descriptions = {} + self.state = "idle" + self.result = None + self.run_state = None + self.thread = None + self.data_thread = None + self.data_state = "idle" + self.data_result = None + self.data_agent = None + self.evaluator_agent = None + self.evaluator_agent_thread = None + self.evaluator_agent_state = "idle" + self.evaluator_agent_result = None + self.sr_agent = None + self._restored_data_agent_buffer = None + self._manifest_description_revision = None + self.start_idempotency_key = None + + def interrupt_active_work(self) -> None: + """Force active model/tool operations toward a safe shutdown boundary.""" + for manager in ( + self.sr_interaction_manager, + self.data_interaction_manager, + self.evaluator_interaction_manager, + ): + if manager.state in {"running", "pausing"}: + manager.command("force_pause") + + def snapshot(self): + """Return a serializable snapshot of the current session.""" + with self.lock: + self._sync_manifest_descriptions() + topk = ( + [] + if self.run_state is None + else json_value( + [record.display_dict() for record in self.run_state.ranked_candidates()] + ) + ) + return { + "state": self.state, + "settings": self.settings.copy(), + "pending_settings": self.pending_settings, + "topk_records": topk, + "result": self.result, + "run_id": self.run_id, + "initial_prompt": self.initial_prompt, + "context_ready": bool(self.context.data), + "workspace": str(self.workspace), + "data_state": self.data_state, + "data_interaction_state": self.data_interaction_manager.state, + "data_agent_settings": self.data_agent_settings.copy(), + "evaluator_agent_settings": self.evaluator_agent_settings.copy(), + "evaluator_agent_state": self.evaluator_agent_state, + "evaluator_interaction_state": self.evaluator_interaction_manager.state, + "evaluator_agent_result": json_value(self.evaluator_agent_result), + "evaluator_id": self._evaluator_metadata()["selected"], + "data_result": json_value(self.data_result), + "data_context": json_value(self.context.schema()), + **self.sr_interaction_manager.status(), + } + + def idle_persistence_revision(self): + """Skip repeated writes only when no agent thread can mutate the session. + + Active or paused agent threads keep the existing persistence behavior. + HTTP mutations also advance a generation even if they raise an error. + """ + with self.lock: + if any(thread is not None and thread.is_alive() for thread in ( + self.thread, self.data_thread, self.evaluator_agent_thread, + )): + return None + metadata = [ + getattr(self, "_persistence_generation", 0), self.run_id, + self.state, self.data_state, self.evaluator_agent_state, + self.settings, self.pending_settings, self.data_agent_settings, + self.evaluator_agent_settings, self.initial_prompt, self.prompt_overrides, + self.variable_descriptions, self.workspace_manager.lock_rules, + self.context.target, getattr(self.context.args, "data_revision", 0), + id(self.result), id(self.data_result), id(self.evaluator_agent_result), + id(self.run_state), self.run_state.node_count if self.run_state else 0, + len(self.data_agent.buffer) if self.data_agent is not None else len(self._restored_data_agent_buffer or []), + *[manager.status()["last_event_seq"] for manager in ( + self.sr_interaction_manager, self.data_interaction_manager, + self.evaluator_interaction_manager, + )], + ] + return json.dumps(json_value(metadata), sort_keys=True, ensure_ascii=False) + + def export_persistent_state(self) -> dict[str, Any]: + """Return a JSON-safe snapshot that can be restored in a new process.""" + with self.lock: + data_agent_buffer = ( + list(self.data_agent.buffer) + if self.data_agent is not None + else self._restored_data_agent_buffer + ) + return json_value( + { + "version": 1, + "run_id": self.run_id, + "state": self.state, + "settings": self.settings, + "pending_settings": self.pending_settings, + "data_agent_settings": self.data_agent_settings, + "evaluator_agent_settings": self.evaluator_agent_settings, + "initial_prompt": self.initial_prompt, + "prompt_overrides": self.prompt_overrides, + "workspace_lock_rules": self.workspace_manager.lock_rules, + "variable_descriptions": self.variable_descriptions, + "result": self.result, + "data_state": self.data_state, + "data_result": self.data_result, + "data_agent_buffer": data_agent_buffer, + "evaluator_agent_state": self.evaluator_agent_state, + "evaluator_agent_result": self.evaluator_agent_result, + "context_target": self.context.target, + "evaluator": self._evaluator_metadata(), + "run_state": self.run_state.export_state() + if self.run_state is not None + else None, + "interactions": { + "search": self.sr_interaction_manager.export_state(), + "data": self.data_interaction_manager.export_state(), + "evaluator": self.evaluator_interaction_manager.export_state(), + }, + } + ) + + def restore_persistent_state(self, snapshot: dict[str, Any]) -> None: + """Restore a durable snapshot and terminate operations lost on restart.""" + expected_fields = { + "version", + "run_id", + "state", + "settings", + "pending_settings", + "data_agent_settings", + "evaluator_agent_settings", + "initial_prompt", + "prompt_overrides", + "workspace_lock_rules", + "variable_descriptions", + "result", + "data_state", + "data_result", + "data_agent_buffer", + "evaluator_agent_state", + "evaluator_agent_result", + "context_target", + "evaluator", + "run_state", + "interactions", + } + if set(snapshot) != expected_fields: + raise ValueError("Persisted InteractiveSession does not match the current schema") + if snapshot["version"] != 1: + raise ValueError("Unsupported InteractiveSession snapshot version") + with self.lock: + self.run_id = str(snapshot["run_id"]) + restored_settings = dict(snapshot["settings"]) + default_settings = self.settings.copy() + legacy_stop_fields = { + "tool_free_stop_review_rounds", + "stop_guard_mode", + "stop_guard_metric", + "stop_guard_threshold", + "stop_guard_split", + "stop_guard_larger_is_better", + } + missing_settings = set(default_settings) - set(restored_settings) + if ( + set(restored_settings) - set(default_settings) + or not missing_settings <= legacy_stop_fields + ): + raise ValueError("Persisted settings do not match the current session schema") + for name in missing_settings: + restored_settings[name] = default_settings[name] + self.settings = restored_settings + self.pending_settings = snapshot["pending_settings"] + restored_data_settings = dict(snapshot["data_agent_settings"]) + if set(restored_data_settings) != set(self.data_agent_settings): + raise ValueError("Persisted data-agent settings do not match the current schema") + self.data_agent_settings = restored_data_settings + restored_evaluator_settings = dict(snapshot["evaluator_agent_settings"]) + if set(restored_evaluator_settings) != set(self.evaluator_agent_settings): + raise ValueError( + "Persisted evaluator-agent settings do not match the current schema" + ) + self.evaluator_agent_settings = restored_evaluator_settings + self.initial_prompt = str(snapshot["initial_prompt"]) + self.prompt_overrides = dict(snapshot["prompt_overrides"]) + self.workspace_manager.load_lock_rules(dict(snapshot["workspace_lock_rules"])) + if "system" in self.prompt_overrides: + self.prompt_overrides["system"] = SRAgentInteractive.normalize_system_prompt( + self.prompt_overrides["system"] + ) + self.variable_descriptions = dict(snapshot["variable_descriptions"]) + self.result = snapshot["result"] + self.data_result = snapshot["data_result"] + self.evaluator_agent_result = snapshot["evaluator_agent_result"] + buffer = snapshot["data_agent_buffer"] + if buffer is not None and not isinstance(buffer, list): + raise TypeError("data_agent_buffer must be a list or None") + self._restored_data_agent_buffer = list(buffer) if buffer is not None else None + for name in EVALUATOR_CONTEXT_SETTING_NAMES: + setattr(self.context.args, name, self.settings[name]) + + data_directory = self.workspace / "context.data" + if (data_directory / "manifest.json").is_file(): + self.context.commit_context_data( + load_context_data(data_directory, workspace=self.workspace_manager) + ) + target = snapshot["context_target"] + if target is not None and target not in self.context.data: + raise ValueError("Persisted context target is missing from context.data") + self.context.target = target + if self.variable_descriptions: + self.context.variable_descriptions.update( + { + name: description + for name, description in self.variable_descriptions.items() + if name in self.context.data + } + ) + + evaluator = snapshot["evaluator"] + if not isinstance(evaluator, dict): + raise TypeError("evaluator snapshot must be a dictionary") + selected = evaluator["selected"] + if isinstance(selected, str) and selected.startswith("custom"): + custom_file = evaluator["custom_file"] + custom_source = evaluator["source"] + self.context.evaluator = load_custom_evaluator( + file=Path(custom_file) if custom_file is not None else None, + source=custom_source, + workspace=self.workspace_manager, + ) + elif selected in {"default", "graph"}: + self.context.evaluator = create_builtin_evaluator(selected) + else: + raise ValueError(f"Unknown persisted evaluator: {selected!r}") + self.context.invalidate_splits() + + run_state = snapshot["run_state"] + if run_state is not None and not isinstance(run_state, dict): + raise TypeError("run_state must be a dictionary or None") + self.run_state = ( + SearchRunState.from_state(run_state, save_path=self.run_dir) + if run_state is not None + else None + ) + interactions = snapshot["interactions"] + search_interrupted = self.sr_interaction_manager.restore_state(interactions["search"]) + data_interrupted = self.data_interaction_manager.restore_state(interactions["data"]) + evaluator_interrupted = self.evaluator_interaction_manager.restore_state( + interactions["evaluator"] + ) + saved_state = str(snapshot["state"]) + if saved_state not in { + "idle", + "starting", + "running", + "completed", + "early_stopped", + "interrupted", + "failed", + }: + raise ValueError(f"Unknown persisted session state: {saved_state!r}") + if search_interrupted or saved_state in {"starting", "running"}: + self.state = "idle" + previous_result = self.result if isinstance(self.result, dict) else {} + self.result = { + **previous_result, + "status": "interrupted", + "restored_after_restart": True, + } + else: + self.state = saved_state + saved_data_state = str(snapshot["data_state"]) + if saved_data_state not in { + "idle", + "running", + "stopping", + "stopped", + "completed", + "failed", + }: + raise ValueError(f"Unknown persisted data-agent state: {saved_data_state!r}") + self.data_state = ( + "stopped" + if data_interrupted or saved_data_state in {"running", "stopping"} + else saved_data_state + ) + saved_evaluator_state = str(snapshot["evaluator_agent_state"]) + if saved_evaluator_state not in { + "idle", + "running", + "stopping", + "stopped", + "completed", + "failed", + }: + raise ValueError( + f"Unknown persisted evaluator-agent state: {saved_evaluator_state!r}" + ) + self.evaluator_agent_state = ( + "stopped" + if evaluator_interrupted or saved_evaluator_state in {"running", "stopping"} + else saved_evaluator_state + ) + + def _sync_manifest_descriptions(self, *, strict: bool = False) -> None: + """Reflect externally edited manifest descriptions in the live context.""" + manifest_path = self.workspace / "context.data" / "manifest.json" + if not self.context.data or not manifest_path.is_file(): + return + stat = manifest_path.stat() + revision = (stat.st_mtime_ns, stat.st_size) + if revision == self._manifest_description_revision and not strict: + return + try: + with self.workspace_manager.safe_open(manifest_path, "r", encoding="utf-8") as stream: + manifest = json.load(stream) + descriptions = {} + for section in ("variables", "axes"): + for name, spec in manifest[section].items(): + description = spec["description"] + if not isinstance(description, str): + if strict: + raise ValueError(f"{section}.{name}.description must be a string") + return + description = description.strip() + if strict and not description: + raise ValueError(f"{section}.{name}.description must not be empty") + descriptions[name] = description + except (KeyError, TypeError, json.JSONDecodeError, OSError) as exc: + if strict: + raise ValueError(f"Invalid context.data manifest descriptions: {exc}") from exc + return + changed = False + for name in self.context.data: + current = self.context.variable_descriptions.get(name, "") + if name in descriptions and current != descriptions[name]: + self.context.variable_descriptions[name] = descriptions[name] + changed = True + self._manifest_description_revision = revision + if changed: + self.variable_descriptions = dict(self.context.variable_descriptions) + self.context.args.data_revision += 1 + + def evaluator_configuration(self): + """Return the selected evaluator and every available evaluator.""" + metadata = self._evaluator_metadata() + return { + "selected": metadata["selected"], + "source": metadata["source"], + "custom_template": CUSTOM_TEMPLATE, + "evaluators": [*evaluator_catalog(), *self._custom_evaluator_catalog()], + "custom_name": metadata["custom_name"], + "custom_file": metadata["custom_file"], + } + + def _custom_evaluator_catalog(self) -> list[dict[str, Any]]: + """Return valid evaluator implementations saved in this workspace.""" + files = self._custom_evaluator_files() + catalog = [] + for file in files: + try: + with self.workspace_manager.safe_open(file, "r", encoding="utf-8") as stream: + source = stream.read() + evaluator = load_custom_evaluator( + source=source, + file=file, + workspace=self.workspace_manager, + ) + except (OSError, UnicodeError, ValueError) as exc: + try: + with self.workspace_manager.safe_open( + file, + "r", + encoding="utf-8", + errors="replace", + ) as stream: + source = stream.read() + except OSError: + source = "" + catalog.append( + { + "id": f"custom:{file.name}", + "label": file.stem, + "label_en": file.stem, + "source": source, + "abstract": False, + "custom": True, + "file": str(file), + "invalid": True, + "error": str(exc), + } + ) + continue + class_name = type(evaluator).__name__ + catalog.append( + { + "id": f"custom:{file.name}", + "label": class_name, + "label_en": class_name, + "source": source, + "abstract": False, + "custom": True, + "file": str(file), + "invalid": False, + "error": None, + } + ) + return catalog + + def _custom_evaluator_files(self) -> list[Path]: + """Return ordinary evaluator files without following workspace links.""" + directory = self.workspace_manager.resolve("context.evaluator") + if directory is None or not directory.is_dir(): + return [] + with os.scandir(directory) as entries: + candidates = [ + Path(entry.path) + for entry in entries + if entry.name.endswith(".py") and entry.is_file(follow_symlinks=False) + ] + files = [] + for path in candidates: + try: + with self.workspace_manager.safe_open(path, "rb") as stream: + if stat.S_ISREG(os.fstat(stream.fileno()).st_mode): + files.append(path) + except OSError: + continue + return sorted(files, key=lambda path: path.name) + + def _evaluator_metadata(self) -> dict[str, Any]: + evaluator = self.context.evaluator + custom = getattr(type(evaluator), "CUSTOM_EVALUATOR", None) + if isinstance(custom, dict) and isinstance(custom.get("source"), str): + file = custom.get("file") + return { + "selected": f"custom:{Path(file).name}" if file is not None else "custom", + "source": custom["source"], + "custom_name": type(evaluator).__name__, + "custom_file": str(file) if file is not None else None, + } + selected = ( + "graph" if type(evaluator) is GraphEvaluator + else "delay_rollout" if type(evaluator) is DelayRolloutEvaluator + else "default" + ) + return { + "selected": selected, + "source": evaluator_source(selected), + "custom_name": None, + "custom_file": None, + } + + def evaluator_editable(self) -> bool: + """Return whether evaluator mutation is safe for the active search.""" + if self.state == "idle": + return True + control = self.sr_interaction_manager.status() + return self.state in {"starting", "running"} and control["interaction_state"] == "paused" + + def configure_evaluator(self, payload): + """Validate and select an evaluator before symbolic regression starts.""" + if not self.evaluator_editable(): + raise ValueError( + "Pause the search and wait for a safe boundary before changing the evaluator" + ) + evaluator_id = str(payload.get("selected", "")).strip() + source = str(payload.get("source", "")) + available = { + item["id"]: item for item in [*evaluator_catalog(), *self._custom_evaluator_catalog()] + } + selected_item = available.get(evaluator_id) + builtin_source = ( + evaluator_source(evaluator_id) + if evaluator_id in {item["id"] for item in evaluator_catalog()} + else None + ) + if builtin_source is not None and source == builtin_source: + evaluator = create_builtin_evaluator(evaluator_id) + source = builtin_source + custom_name = None + elif ( + selected_item is not None + and selected_item.get("custom") + and source == selected_item["source"] + ): + evaluator = load_custom_evaluator( + file=Path(selected_item["file"]), + workspace=self.workspace_manager, + ) + custom_name = type(evaluator).__name__ + else: + try: + declared_names = { + node.name + for node in ast.parse(source, mode="exec").body + if isinstance(node, ast.ClassDef) + } + except SyntaxError: + declared_names = set() + if conflicts := declared_names & BUILTIN_EVALUATOR_CLASS_NAMES: + custom_name = sorted(conflicts)[0] + raise ValueError( + f"Evaluator class name {custom_name!r} conflicts with a built-in evaluator. " + "Rename the class before saving." + ) + evaluator = load_custom_evaluator( + source=source, + workspace=self.workspace_manager, + ) + custom_name = type(evaluator).__name__ + if custom_name in BUILTIN_EVALUATOR_CLASS_NAMES: + raise ValueError( + f"Evaluator class name {custom_name!r} conflicts with a built-in evaluator. " + "Rename the class before saving." + ) + filename = evaluator_filename(custom_name) + save_dir = self.evaluator_workspace + save_dir_relative = str(save_dir.relative_to(self.workspace)) + self.workspace_manager.create_directory( + save_dir_relative, + parents=True, + exist_ok=True, + ) + destination = save_dir / filename + descriptor, temporary_name = tempfile.mkstemp( + prefix=f".{destination.stem}-", suffix=".py", dir=self.run_dir + ) + os.close(descriptor) + temporary = Path(temporary_name) + try: + temporary.write_text(source, encoding="utf-8") + self.workspace_manager.replace_file( + temporary, + str(destination.relative_to(self.workspace)), + ) + finally: + temporary.unlink(missing_ok=True) + evaluator = load_custom_evaluator( + file=destination, + workspace=self.workspace_manager, + ) + evaluator_id = f"custom:{destination.name}" + with self.lock: + self.context.evaluator = evaluator + self.context.invalidate_splits() + return self.evaluator_configuration() + + def test_evaluator(self, payload): + """Validate the selected evaluator against the best available formula.""" + evaluator_id = str(payload.get("selected", self._evaluator_metadata()["selected"])).strip() + source = str(payload.get("source", "")) + available = { + item["id"]: item for item in [*evaluator_catalog(), *self._custom_evaluator_catalog()] + } + selected_item = available.get(evaluator_id) + if ( + selected_item is not None + and selected_item.get("custom") + and source == selected_item["source"] + ): + evaluator = load_custom_evaluator( + file=Path(selected_item["file"]), + workspace=self.workspace_manager, + ) + elif evaluator_id in { + item["id"] for item in evaluator_catalog() + } and source == evaluator_source(evaluator_id): + evaluator = create_builtin_evaluator(evaluator_id) + else: + evaluator = load_custom_evaluator( + source=source, + workspace=self.workspace_manager, + ) + if not self.context.data or not self.context.target or not self.context.feature_names(): + raise ValueError("Prepare data and select a target plus at least one feature first") + test_context = AgentContext( + args=self.context.args, + data=self.context.data, + target=self.context.target, + variable_descriptions=self.context.variable_descriptions, + variable_axes=self.context.variable_axes, + variable_structures=self.context.variable_structures, + num_nodes=self.context.num_nodes, + evaluator=evaluator, + workspace=self.context.workspace, + ) + ranked = self.run_state.ranked_candidates() if self.run_state is not None else [] + best_formula = next((record.formula for record in ranked if record.formula), None) + features = self.context.feature_names() + baseline = " + ".join( + ["param('intercept')"] + + [f"param('coefficient_{index}') * {name}" for index, name in enumerate(features, 1)] + ) + formula = str(payload.get("formula") or best_formula or baseline).strip() + result = ValidateEvaluatorTool(context=test_context)( + evaluator_file=None, + f=formula, + fit=True, + show_diagnostics=False, + ) + if not result.ok: + raise ValueError(result.result_str) + return {"formula": formula, "result": json_value(result.result)} + + def assist_evaluator(self, payload): + """Let a restricted agent construct, exercise, and repair an evaluator.""" + if not self.evaluator_editable(): + raise ValueError( + "Pause the search and wait for a safe boundary before using EvaluatorConstructionAgent" + ) + instruction = str(payload.get("message", "")).strip() + if not instruction: + raise ValueError("Evaluator construction instruction must not be empty") + instruction = ( + instruction + + "\n\nKeep evaluator scripts inside context.evaluator/ and validate the final file. " + "The directory may not exist yet; create it with a workspace tool only when you are " + "ready to write the first evaluator script." + ) + + settings = self.evaluator_agent_settings.copy() + enabled_tools = settings.get("tools") or [] + classes = {tool_cls.metadata.name: tool_cls for tool_cls in BaseTool.load_tool_classes()} + tools = [classes[name](context=self.context) for name in enabled_tools] + previous_skills = getattr(self.context.args, "enabled_skills", None) + self.context.args.enabled_skills = settings.get("skills") or [] + try: + with self.evaluator_agent_lock: + agent = EvaluatorConstructionAgent( + llm_provider=settings["llm_provider"], + llm_model=settings["llm_model"], + context=self.context, + tools=tools, + tool_parser=settings["tool_parser"], + llm_max_tokens=settings["llm_max_tokens"], + interaction_manager=self.evaluator_interaction_manager, + ) + with self.lock: + self.evaluator_agent = agent + try: + result = agent.run(instruction) + finally: + with self.lock: + if self.evaluator_agent is agent: + self.evaluator_agent = None + finally: + if previous_skills is None: + delattr(self.context.args, "enabled_skills") + else: + self.context.args.enabled_skills = previous_skills + files = sorted(self._custom_evaluator_files(), key=lambda path: path.lstat().st_mtime_ns) + if not files: + raise ValueError( + "EvaluatorConstructionAgent did not create a Python file under context.evaluator/" + ) + result_file = files[-1] + with self.workspace_manager.safe_open(result_file, "r", encoding="utf-8") as stream: + result_source = stream.read() + return { + **result, + "source": result_source, + "selected": f"custom:{result_file.name}", + "custom_file": str(result_file), + "provider": settings["llm_provider"], + "model": settings["llm_model"], + } + + def start_evaluator_assistance(self, payload): + """Start evaluator construction in a cancellable background thread.""" + with self.lock: + instruction = str(payload.get("message", "")).strip() + if not instruction: + raise ValueError("Evaluator construction instruction must not be empty") + if self.evaluator_interaction_manager.state in MESSAGE_ACCEPTING_INTERACTION_STATES: + self.evaluator_interaction_manager.command("message", instruction) + self.evaluator_agent_state = "running" + return self.snapshot() + self.evaluator_interaction_manager.command("message", instruction) + self.evaluator_agent_state = "running" + self.evaluator_agent_result = None + self.evaluator_agent_thread = threading.Thread( + target=self._run_evaluator_assistance, + args=(dict(payload),), + daemon=True, + ) + self.evaluator_agent_thread.start() + return self.snapshot() + + def stop_evaluator_assistance(self): + """Request cancellation of the active evaluator-construction turn.""" + with self.lock: + interaction_state = self.evaluator_interaction_manager.state + if interaction_state not in {"running", "pausing"}: + raise ValueError("EvaluatorConstructionAgent is not running") + force = interaction_state == "pausing" + control = self.evaluator_interaction_manager.command( + "force_pause" if force else "pause" + ) + self.evaluator_agent_state = "stopping" + snapshot = self.snapshot() + if control.get("cancellation_error"): + snapshot["cancellation_error"] = control["cancellation_error"] + return snapshot + + def _run_evaluator_assistance(self, payload) -> None: + try: + queued = self.evaluator_interaction_manager.start_agent_execution() + if queued: + payload["message"] = queued[-1].content + result = self.assist_evaluator(payload) + state = "completed" + except InterruptedError as exc: + result = {"status": "stopped", "message": str(exc)} + state = "stopped" + except Exception as exc: + _logger.exception("Evaluator construction Agent failed") + result = {"status": "failed", "error": str(exc)} + state = "failed" + with self.lock: + self.evaluator_agent_result = result + self.evaluator_agent_state = state + self.evaluator_interaction_manager.publish_event( + "execution_completed" if state == "completed" else "execution_failed", + {**json_value(result), "status": state}, + ) + if self.evaluator_interaction_manager.state != "paused": + self.evaluator_interaction_manager.finish_agent_execution() + + def configure_evaluator_agent(self, payload): + """Validate and persist evaluator-construction agent model settings.""" + self._ensure_settings_editable() + settings = self.validate_evaluator_agent_settings(payload) + self.validate_capabilities(settings, agent="evaluator") + with self.lock: + if "proxy" in settings: + self.set_proxy(settings["proxy"]) + self.evaluator_agent_settings = {**self.evaluator_agent_settings, **settings} + if "proxy" in settings: + self.data_agent_settings["proxy"] = settings["proxy"] + if self.evaluator_agent is not None: + self.evaluator_agent.queue_runtime_settings(settings) + return self.snapshot() + + def test_evaluator_agent_model(self, payload): + """Test evaluator-construction agent model settings without applying them.""" + updates = self.validate_evaluator_agent_settings(payload) + self.validate_capabilities(updates, agent="evaluator") + settings = {**self.evaluator_agent_settings, **updates} + return self._test_model(settings, proxy=settings.get("proxy", "")) + + def capabilities(self, agent: str = "search"): + """Describe configurable tools and user-facing skills for the Web UI. + + Args: + agent: The agent value. + """ + if agent not in {"search", "data", "evaluator"}: + raise ValueError(f"Unsupported agent capability scope: {agent}") + tools = [ + { + "name": tool_cls.metadata.name, + "description": tool_cls.metadata.description, + } + for tool_cls in BaseTool.load_tool_classes() + if tool_cls.metadata.name not in HIDDEN_CAPABILITY_TOOLS + ] + skills = [ + {"name": skill.name, "description": skill.description} + for skill in self._capability_skill_manager.load_skills().values() + ] + tool_names = [tool["name"] for tool in tools] + if agent == "data": + default_tools = list(DataPreparationAgent.DEFAULT_TOOLS) + default_skills = [ + skill["name"] + for skill in skills + if skill["name"] not in DataPreparationAgent.DEFAULT_EXCLUDED_SKILLS + ] + elif agent == "evaluator": + default_tools = list(EVALUATOR_DEFAULT_TOOLS) + default_skills = [ + skill["name"] for skill in skills if skill["name"] != "discover-symbolic-laws" + ] + else: + default_tools = [ + name for name in SRAgentInteractive.DEFAULT_TOOLS if name in tool_names + ] + default_skills = [skill["name"] for skill in skills] + return { + "tools": tools, + "skills": skills, + "default_tools": default_tools, + "default_skills": default_skills, + } + + def validate_capabilities(self, settings, agent: str = "search"): + """Validate capabilities. + + Args: + settings: Runtime settings to validate or apply. + agent: The agent value. + """ + catalog = self.capabilities(agent) + for key, catalog_key in (("tools", "tools"), ("skills", "skills")): + if key not in settings: + continue + available = {item["name"] for item in catalog[catalog_key]} + if unknown := set(settings[key]) - available: + raise ValueError(f"Unknown {key}: {', '.join(sorted(unknown))}") + if ( + agent == "data" + and "tools" in settings + and "validate_context_data" not in settings["tools"] + ): + raise ValueError("The data-preparation agent requires the validate_context_data tool") + if ( + agent == "evaluator" + and settings.get("skills") + and "read_skill" not in settings.get("tools", self.evaluator_agent_settings["tools"]) + ): + raise ValueError("Evaluator-agent skills require the read_skill tool") + + def provider_credential(self, provider: str): + """Report credential availability without exposing the secret value. + + Args: + provider: The provider value. + """ + provider = str(provider).strip().lower() + try: + variable = PROVIDER_API_KEY_VARIABLES[provider] + except KeyError as exc: + raise ValueError(f"Unsupported web model provider: {provider}") from exc + file_value = self.context.args.api_environment.get(variable) + configured = bool(file_value or os.environ.get(variable)) + return { + "provider": provider, + "env_var": variable, + "configured": configured, + "stored_in_env_file": bool(file_value), + } + + def set_provider_credential(self, provider: str, api_key: str): + """Atomically update this conversation's private dotenv file. + + Args: + provider: The provider value. + api_key: The api key value. + """ + status = self.provider_credential(provider) + if not isinstance(api_key, str) or not api_key.strip(): + raise ValueError("api_key must be a non-empty string") + api_key = api_key.strip() + if len(api_key) > 16_384 or any(character in api_key for character in "\r\n\0"): + raise ValueError("api_key contains unsupported characters") + with self.lock: + self.env_path.parent.mkdir(parents=True, exist_ok=True) + if not self.env_path.exists(): + self.env_path.touch(mode=0o600) + set_key( + self.env_path, + status["env_var"], + api_key, + quote_mode="always", + ) + self.context.args.api_environment[status["env_var"]] = api_key + return self.provider_credential(provider) + + def set_proxy(self, proxy: str) -> None: + """Persist the optional model proxy and update this server process. + + Args: + proxy: Proxy URL, or an empty string to clear the configured proxy. + """ + proxy = self.validate_proxy(proxy) + self.env_path.parent.mkdir(parents=True, exist_ok=True) + if not self.env_path.exists(): + self.env_path.touch(mode=0o600) + if proxy: + set_key(self.env_path, "HTTP_PROXY", proxy, quote_mode="always") + set_key(self.env_path, "HTTPS_PROXY", proxy, quote_mode="always") + else: + unset_key(self.env_path, "HTTP_PROXY") + unset_key(self.env_path, "HTTPS_PROXY") + updated_environment = proxy_environment( + self.context.args.api_environment, + user_proxy=proxy, + egress_proxy=self.egress_proxy, + ) + self.context.args.api_environment.clear() + self.context.args.api_environment.update(updated_environment) + + @staticmethod + def validate_proxy(proxy: str) -> str: + """Validate and normalize an optional HTTP or SOCKS proxy URL. + + Args: + proxy: Proxy URL supplied by the Web UI. + + Returns: + The stripped URL, or an empty string when proxying is disabled. + """ + if not isinstance(proxy, str): + raise ValueError("proxy must be a string") + proxy = proxy.strip() + if not proxy: + return "" + if len(proxy) > 4096 or any(character in proxy for character in "\r\n\0"): + raise ValueError("proxy contains unsupported characters") + parsed = urlparse(proxy) + if parsed.scheme not in {"http", "https", "socks5", "socks5h"} or not parsed.netloc: + raise ValueError("proxy must be an HTTP, HTTPS, SOCKS5, or SOCKS5H URL") + return proxy + + @staticmethod + def validate_setting_dependencies(settings): + """Validate setting dependencies. + + Args: + settings: Runtime settings to validate or apply. + """ + if ( + settings.get("stop_guard_mode") == "metric_threshold" + and settings.get("stop_guard_threshold") is None + ): + raise ValueError(f"{settings['stop_guard_mode']} requires stop_guard_threshold") + if not settings.get("force_initial_diagnostics"): + return + tools = settings.get("tools") + required = {"statistics_analysis", "relationship_analysis", "read_skill"} + if tools is not None and (missing := required - set(tools)): + raise ValueError( + "force_initial_diagnostics requires enabled tools: " + ", ".join(sorted(missing)) + ) + skills = settings.get("skills") + if skills is not None and "discover-symbolic-laws" not in skills: + raise ValueError("force_initial_diagnostics requires the discover-symbolic-laws skill") + + def start(self, payload): + """Run the ``start`` operation. + + Args: + payload: Serializable event payload. + """ + with self.lock: + idempotency_key = payload.get("idempotency_key") + if idempotency_key is not None: + if ( + not isinstance(idempotency_key, str) + or not idempotency_key.strip() + or len(idempotency_key) > 200 + ): + raise ValueError( + "idempotency_key must be a non-empty string up to 200 characters" + ) + idempotency_key = idempotency_key.strip() + if self.state != "idle": + if idempotency_key is not None and idempotency_key == self.start_idempotency_key: + return self.snapshot() + raise ValueError("This server already owns a run. Restart it to begin a new task.") + if self.data_interaction_manager.state in {"running", "pausing", "interrupting"}: + raise ValueError("Wait for the data-preparation agent to finish before starting") + if "dataset" in payload: + raise ValueError( + "The dataset start option is no longer supported; prepare context.data first" + ) + manifest_path = self.workspace / "context.data" / "manifest.json" + if not self.context.data or not manifest_path.is_file(): + raise ValueError("Create and load a valid context.data dataset before starting") + options = self.validate_settings(payload, initial=True) + self.validate_capabilities(options) + updated_settings = {**self.settings, **options} + self.validate_setting_dependencies(updated_settings) + self.settings = updated_settings + description = str( + payload.get( + "problem_description", + payload.get("prompt", "Find an interpretable formula explaining the data."), + ) + ) + self.prompt_overrides = { + role: ( + SRAgentInteractive.normalize_system_prompt(str(payload[key])) + if role == "system" + else str(payload[key]) + ) + for role, key in (("system", "system_prompt"), ("user", "user_prompt")) + if key in payload + } + self.variable_descriptions = self.validate_variable_descriptions(payload) + self._sync_manifest_descriptions(strict=True) + target = str(payload.get("target") or self.context.target) + features = payload.get("features") or list(self.context.feature_names()) + X, y = self._select_context_columns(target, features) + descriptions = dict(self.context.variable_descriptions) + descriptions.update(self.variable_descriptions) + self.context.variable_descriptions = { + name: descriptions.get(name, "") for name in self.context.data + } + self.variable_descriptions = dict(self.context.variable_descriptions) + self.state = "starting" + self.start_idempotency_key = idempotency_key + try: + response = self.snapshot() + self.thread = threading.Thread( + target=self._run, + args=(X, y, description), + daemon=True, + ) + self.thread.start() + except Exception as exc: + thread = self.thread + started = bool(thread is not None and thread.ident is not None) + failure_stage = "start_response" if started else "start_preflight" + if started and thread.is_alive(): + self.interrupt_active_work() + thread.join(timeout=2) + self.result = { + "status": "failed", + "error": str(exc), + "failure_stage": failure_stage, + } + self.state = "failed" if started else "idle" + conversation = self.conversation_id or self.workspace.name + thread_alive = bool(thread and thread.is_alive()) + _logger.exception( + f"Failed to start conversation={conversation} run={self.run_id} " + f"thread_alive={thread_alive} stage={failure_stage}" + ) + raise SessionStartError( + str(exc), + run_id=self.run_id, + started=started, + ) from exc + return response + + def prepare_data(self, instruction: str): + """Continue the persistent data-agent conversation in the background. + + Args: + instruction: Natural-language instruction for the agent. + """ + with self.lock: + instruction = instruction.strip() + if not instruction: + raise ValueError("Data-preparation instruction must not be empty") + if self.data_interaction_manager.state in MESSAGE_ACCEPTING_INTERACTION_STATES: + self.data_interaction_manager.command("message", instruction) + self.data_state = "running" + return self.snapshot() + if self.state == "starting": + raise ValueError("Wait for symbolic regression to reach a controllable boundary") + control_status = self.sr_interaction_manager.status() + if self.state == "running" and not (control_status["interaction_state"] == "paused"): + raise ValueError( + "Pause symbolic regression and wait for the safe-boundary acknowledgement " + "before changing its data" + ) + settings = self.data_agent_settings.copy() + if self.data_agent is None: + self.data_agent = DataPreparationAgent( + llm_provider=settings["llm_provider"], + llm_model=settings["llm_model"], + context=self.context, + tools=settings["tools"], + tool_parser=settings["tool_parser"], + llm_max_tokens=settings["llm_max_tokens"], + skills=settings["skills"], + interaction_manager=self.data_interaction_manager, + ) + if self._restored_data_agent_buffer: + self.data_agent.buffer = list(self._restored_data_agent_buffer) + self._restored_data_agent_buffer = None + else: + self.data_agent.llm_provider = settings["llm_provider"] + self.data_agent.llm_model = settings["llm_model"] + self.data_agent.tool_parser = settings["tool_parser"] + self.data_agent.llm_max_tokens = settings["llm_max_tokens"] + self.data_agent.skills = settings["skills"] + self.data_agent.tool_cls_list = BaseTool.load_tool_classes(settings["tools"]) + self.data_agent.initialize_with_context(self.context) + self.data_interaction_manager.command("message", instruction) + self.data_state = "running" + self.data_result = None + self.data_thread = threading.Thread( + target=self._prepare_data, + args=(instruction,), + daemon=True, + ) + self.data_thread.start() + return self.snapshot() + + def stop_data_preparation(self): + """Request cancellation of the active data-preparation turn. + + Returns: + Updated session state showing that cancellation is pending. + """ + with self.lock: + interaction_state = self.data_interaction_manager.state + if interaction_state not in {"running", "pausing"}: + raise ValueError("The data-preparation agent is not running") + force = interaction_state == "pausing" + self.data_state = "stopping" + control = self.data_interaction_manager.command("force_pause" if force else "pause") + snapshot = self.snapshot() + if control.get("cancellation_error"): + snapshot["cancellation_error"] = control["cancellation_error"] + return snapshot + + def _prepare_data(self, instruction: str) -> None: + data_directory = self.workspace / "context.data" + + def directory_revision(): + resolved_directory = self.workspace_manager.resolve("context.data") + if resolved_directory is None or not resolved_directory.is_dir(): + return None + revision = [] + for current, directory_names, file_names in os.walk( + resolved_directory, followlinks=False + ): + current_path = Path(current) + directory_names[:] = [ + name for name in directory_names if not (current_path / name).is_symlink() + ] + for name in file_names: + path = current_path / name + metadata = path.lstat() + if stat.S_ISREG(metadata.st_mode): + revision.append( + ( + str(path.relative_to(resolved_directory)), + metadata.st_size, + metadata.st_mtime_ns, + ) + ) + return tuple(sorted(revision)) + + previous_revision = directory_revision() + try: + queued = self.data_interaction_manager.start_agent_execution() + result = self.data_agent.run(queued[-1].content if queued else instruction) + if ( + directory_revision() != previous_revision + and (data_directory / "manifest.json").is_file() + ): + self.context.commit_context_data( + load_context_data( + data_directory, + workspace=self.workspace_manager, + ) + ) + result = {**result, "context": self.context.schema()} + state = "completed" + except InterruptedError as exc: + result = { + "status": "stopped", + "message": str(exc), + "context": self.context.schema(), + } + state = "stopped" + self.data_interaction_manager.publish_event("execution_failed", result) + except Exception as exc: + _logger.exception("Data preparation Agent failed") + public_error = {"error": str(exc)} + result = {**public_error, "context": self.context.schema()} + state = "failed" + self.data_interaction_manager.publish_event("execution_failed", public_error) + with self.lock: + self.data_result = json_value(result) + self.data_state = state + if self.data_interaction_manager.state != "paused": + self.data_interaction_manager.finish_agent_execution() + + def preview_initial_prompts(self, payload): + """Run the ``preview initial prompts`` operation. + + Args: + payload: Serializable event payload. + """ + description = str( + payload.get( + "problem_description", + self.initial_prompt + or "Find an interpretable formula explaining the selected target from the selected features.", + ) + ) + if self.context.data: + target = str(payload.get("target") or self.context.target or "") + features = payload.get("features") or list(self.context.feature_names()) + X, y = self._select_context_columns(target, features) + else: + X, y = {"x": np.empty(1)}, {"y": np.empty(1)} + settings = self.settings + preview_agent = object.__new__(SRAgentInteractive) + preview_agent.model_router = ModelRouter( + enabled=bool(settings.get("auto_routing", False)), + base_provider=settings["llm_provider"], + base_model=settings["llm_model"], + strong_provider=settings.get("strong_llm_provider"), + strong_model=settings.get("strong_llm_model"), + ) + preview_agent.max_refinement_depth = settings["max_refinement_depth"] + preview_agent.use_workspace = True + preview_agent.interaction_manager = InteractionManager() + preview_agent.variable_descriptions = self.validate_variable_descriptions(payload) + preview_agent.prompt_overrides = {} + preview_agent.ranking_metric = settings.get("ranking_metric", "mse") + preview_agent.larger_is_better = bool(settings.get("larger_is_better", False)) + preview_agent.run_state = SimpleNamespace( + ranked_candidates=lambda: [], pareto_indices=lambda records: [] + ) + messages = preview_agent.create_initial_prompt_messages(description, X, y, []) + return { + "problem_description": description, + "system_prompt": next( + message["content"] for message in messages if message["role"] == "system" + ), + "user_prompt": next( + message["content"] for message in messages if message["role"] == "user" + ), + } + + def _select_context_columns( + self, + target: str, + features: Any, + ) -> tuple[dict[str, np.ndarray], dict[str, np.ndarray]]: + if not target or not isinstance(features, list) or not features or target in features: + raise ValueError("Select a target and at least one distinct feature") + + def array(name: str) -> np.ndarray | None: + return self.context.data.get(name) + + selected = {name: array(name) for name in [*features, target]} + missing = [name for name, value in selected.items() if value is None] + if missing: + raise ValueError(f"Selected variables or axes do not exist: {missing}") + arrays = {name: np.asarray(value) for name, value in selected.items()} + return ( + {name: arrays[name] for name in features}, + {target: arrays[target]}, + ) + + @staticmethod + def validate_variable_descriptions(payload): + """Validate variable descriptions. + + Args: + payload: Serializable event payload. + """ + descriptions = payload.get("variable_descriptions", {}) + if not isinstance(descriptions, dict) or any( + not isinstance(name, str) or not isinstance(value, str) + for name, value in descriptions.items() + ): + raise ValueError("variable_descriptions must map column names to text") + return {name: value.strip() for name, value in descriptions.items() if value.strip()} + + def create_demo(self, kind: str = "polynomial"): + """Create and load a manifest-backed sample dataset. + + Returns: + Path to the newly created ``context.data`` directory. + + Raises: + FileExistsError: If ``context.data`` already exists and is not empty. + """ + with self.lock: + path = self.workspace / "context.data" + if path.exists() or path.is_symlink(): + if path.is_symlink() or not path.is_dir() or any(path.iterdir()): + raise FileExistsError("context.data already exists and is not empty") + self.workspace_manager.remove("context.data") + arrays, manifest, target = build_demo(kind) + self.workspace_manager.create_directory("context.data") + try: + for name, value in arrays.items(): + with self.workspace_manager.open_for_write( + f"context.data/{name}.npy", "xb" + ) as stream: + np.save(stream, value) + for name, spec in manifest["variables"].items(): + spec["file"] = f"{name}.npy" + with self.workspace_manager.open_for_write( + "context.data/manifest.json", "x", encoding="utf-8" + ) as stream: + json.dump(manifest, stream, indent=2) + loaded = load_context_data(path, workspace=self.workspace_manager) + self.context.commit_context_data(loaded) + self.context.target = target + except Exception: + self.workspace_manager.remove("context.data", recursive=True, missing_ok=True) + raise + return path + + def reload_context_data(self): + """Reload ``context.data`` from the workspace into the shared context.""" + with self.lock: + if self.data_state in {"running", "stopping"}: + raise ValueError( + "Wait for the data-preparation agent to finish before reloading context.data" + ) + if self.state == "starting": + raise ValueError("Wait for symbolic regression to reach a controllable boundary") + control = self.sr_interaction_manager.status() + if self.state == "running" and not (control["interaction_state"] == "paused"): + raise ValueError( + "Pause symbolic regression and wait for the safe-boundary acknowledgement " + "before reloading context.data" + ) + directory = self.workspace / "context.data" + if not (directory / "manifest.json").is_file(): + raise ValueError("context.data/manifest.json does not exist") + change = self.context.commit_context_data( + load_context_data( + directory, + workspace=self.workspace_manager, + ) + ) + self.variable_descriptions = dict(self.context.variable_descriptions) + return {**change, "context": self.context.schema()} + + def _run(self, X, y, description): + self.context.args.sr_active = True + try: + options = dict(self.settings) + save_path = options.pop("save_path", str(self.run_dir)) + options.update( + save_path=save_path, + run_id=self.run_id, + use_workspace=True, + ) + manager = self.sr_interaction_manager + agent = SRAgentInteractive( + interaction_manager=manager, + context=self.context, + skill_manager=self._capability_skill_manager, + **options, + ) + agent.prompt_overrides = self.prompt_overrides.copy() + agent.variable_descriptions = self.variable_descriptions.copy() + agent.runtime_settings_supplier = self._take_pending_settings + agent.runtime_settings_committer = self._commit_runtime_settings + self.sr_agent = agent + self.run_state = agent.run_state + with self.lock: + self.state = "running" + agent.initial_messages = manager.start_agent_execution() + result = agent.run(X, y, description) + except KeyboardInterrupt as exc: + result = getattr(exc, "partial_result", {}) | {"status": "interrupted"} + except Exception as exc: + _logger.exception("Symbolic-regression Agent failed") + result = getattr(exc, "partial_result", {}) | { + "status": "failed", + "error": str(exc), + } + with self.lock: + self.result = json_value(result) + self.state = result.get("status", "completed") + self.context.args.sr_active = False + manager.publish_event( + "execution_completed" if self.state != "failed" else "execution_failed", + { + "status": self.state, + "result": self.result, + }, + ) + if manager.state != "paused": + manager.finish_agent_execution() + + def _take_pending_settings(self) -> dict[str, Any] | None: + with self.lock: + settings = self.pending_settings + self.pending_settings = None + return settings + + def _commit_runtime_settings(self, settings: dict[str, Any]) -> None: + with self.lock: + self.settings.update(settings) + + @staticmethod + def validate_settings(payload, initial=False): + """Validate settings. + + Args: + payload: Serializable event payload. + initial: Optional initial parameter values. + """ + allowed = set(RUNTIME_SETTING_NAMES) + bounded_integers = { + "max_refinement_depth", + "local_sample_size", + "global_width", + "max_restart_loop", + "restart_top_k", + } + nonnegative_integers = {"max_workers"} + result = {k: v for k, v in payload.items() if k in allowed} + for k, v in result.items(): + if k in bounded_integers: + if isinstance(v, bool) or not isinstance(v, int) or not 1 <= v <= 1000: + raise ValueError(f"{k} must be an integer between 1 and 1000") + elif k == "llm_max_tokens": + if isinstance(v, bool) or not isinstance(v, int) or not 1 <= v <= 1_000_000: + raise ValueError("llm_max_tokens must be an integer between 1 and 1000000") + elif k in nonnegative_integers or k == "tool_free_stop_review_rounds": + if isinstance(v, bool) or not isinstance(v, int) or not 0 <= v <= 1000: + raise ValueError(f"{k} must be an integer between 0 and 1000") + elif k == "split_random_state": + if isinstance(v, bool) or not isinstance(v, int): + raise ValueError("split_random_state must be an integer") + elif k == "validation_fraction": + if isinstance(v, bool) or not isinstance(v, (int, float)) or not 0 <= v < 1: + raise ValueError("validation_fraction must be in [0, 1)") + elif k in { + "auto_routing", + "larger_is_better", + "force_initial_diagnostics", + "pause_on_truncated_response", + "stop_guard_larger_is_better", + }: + if not isinstance(v, bool): + raise ValueError(f"{k} must be a boolean") + elif k in {"tools", "skills"}: + if ( + not isinstance(v, list) + or any(not isinstance(item, str) or not item.strip() for item in v) + or len(v) != len(set(v)) + ): + raise ValueError(f"{k} must be a list of unique non-empty names") + elif k in {"strong_llm_provider", "strong_llm_model"}: + if v is not None and (not isinstance(v, str) or not v.strip()): + raise ValueError(f"{k} must be null or a non-empty string") + elif k == "split_ood_variable": + if v is not None and (not isinstance(v, str) or not v.strip()): + raise ValueError(f"{k} must be null or a non-empty string") + elif k == "stop_guard_metric": + if v is not None and (not isinstance(v, str) or not v.strip()): + raise ValueError("stop_guard_metric must be null or a non-empty string") + elif k == "stop_guard_threshold": + if v is not None and ( + isinstance(v, bool) + or not isinstance(v, (int, float)) + or not np.isfinite(float(v)) + ): + raise ValueError("stop_guard_threshold must be null or a finite number") + elif not isinstance(v, str) or not v.strip(): + raise ValueError(f"{k} must be non-empty") + if "llm_provider" in result and result["llm_provider"] not in { + "openrouter", + "openai", + "deepseek", + "siliconflow", + "gemini", + "lmstudio", + }: + raise ValueError("Unsupported web model provider") + if "tool_parser" in result and result["tool_parser"] not in { + "openai", + "text", + "json", + "xml", + }: + raise ValueError("Unsupported tool parser") + if "split_by" in result and result["split_by"] not in {"random", "ood"}: + raise ValueError("Unsupported validation split strategy") + if "stop_guard_mode" in result and result["stop_guard_mode"] not in { + "none", + "best_in_topk", + "metric_threshold", + "budget_exhausted", + }: + raise ValueError("Unsupported stop guard mode") + if "stop_guard_split" in result and result["stop_guard_split"] not in { + "train", + "validation", + }: + raise ValueError("Unsupported stop guard split") + return result + + @staticmethod + def validate_data_agent_settings(payload): + """Validate data agent settings. + + Args: + payload: Serializable event payload. + """ + result = {key: value for key, value in payload.items() if key in DATA_AGENT_SETTING_NAMES} + for key, value in result.items(): + if key == "llm_max_tokens": + upper = 1_000_000 + if isinstance(value, bool) or not isinstance(value, int) or not 1 <= value <= upper: + raise ValueError(f"{key} must be an integer between 1 and {upper}") + elif key in {"tools", "skills"}: + if ( + not isinstance(value, list) + or any(not isinstance(item, str) or not item.strip() for item in value) + or len(value) != len(set(value)) + ): + raise ValueError(f"{key} must be a list of unique non-empty names") + elif key == "proxy": + result[key] = InteractiveSession.validate_proxy(value) + elif not isinstance(value, str) or not value.strip(): + raise ValueError(f"{key} must be non-empty") + if "llm_provider" in result and result["llm_provider"] not in PROVIDER_API_KEY_VARIABLES: + raise ValueError("Unsupported web model provider") + if "tool_parser" in result and result["tool_parser"] not in { + "openai", + "text", + "json", + "xml", + }: + raise ValueError("Unsupported tool parser") + return result + + @staticmethod + def validate_evaluator_agent_settings(payload): + """Validate the restricted evaluator-agent model settings.""" + allowed = { + "llm_provider", + "llm_model", + "tool_parser", + "llm_max_tokens", + "proxy", + "tools", + "skills", + } + unknown = set(payload) - allowed + if unknown: + raise ValueError(f"Unsupported evaluator-agent settings: {', '.join(sorted(unknown))}") + return InteractiveSession.validate_data_agent_settings(payload) + + def configure_data_agent(self, payload): + """Run the ``configure data agent`` operation. + + Args: + payload: Serializable event payload. + """ + self._ensure_settings_editable() + with self.lock: + settings = self.validate_data_agent_settings(payload) + self.validate_capabilities(settings, agent="data") + if "proxy" in settings: + self.set_proxy(settings["proxy"]) + self.data_agent_settings = {**self.data_agent_settings, **settings} + if "proxy" in settings: + self.evaluator_agent_settings["proxy"] = settings["proxy"] + if self.data_agent is not None: + self.data_agent.queue_runtime_settings(settings) + return self.snapshot() + + def test_data_agent_model(self, payload): + """Test plain completion and tool-call support without changing agent history. + + Args: + payload: Data-agent settings currently entered in the Web UI. + + Returns: + Connectivity and parsed tool-call diagnostics. + """ + updates = self.validate_data_agent_settings(payload) + self.validate_capabilities(updates, agent="data") + settings = {**self.data_agent_settings, **updates} + return self._test_model(settings, proxy=settings.get("proxy", "")) + + def test_model(self, payload): + """Test the symbolic-regression model settings without applying them. + + Args: + payload: Runtime settings currently entered in the Web UI. + + Returns: + Connectivity and parsed tool-call diagnostics. + """ + updates = self.validate_settings(payload, initial=self.state == "idle") + self.validate_capabilities(updates) + settings = {**self.settings, **updates} + self.validate_setting_dependencies(settings) + return self._test_model(settings) + + def _test_model(self, settings, *, proxy=None): + """Run the shared plain-response and tool-call model probes.""" + probe_tool = ModelTestTool(context=self.context) + user_proxy = str(self.data_agent_settings.get("proxy", "")) if proxy is None else proxy + environment = proxy_environment( + self.context.args.api_environment, + user_proxy=user_proxy, + egress_proxy=self.egress_proxy, + ) + with self.model_test_lock: + tool_box = BaseParser.create(settings["tool_parser"], tool_list=[probe_tool]) + api = BaseAPI.create( + settings["llm_provider"], + model=settings["llm_model"], + tool_box=tool_box, + environment=environment, + ) + plain_rows = list( + api( + "Reply with exactly SRHARNESS_OK.", + n=1, + max_tokens=min(settings["llm_max_tokens"], 64), + ) + ) + tool_rows = list( + api( + "Call report_model_test with answer set to SRHARNESS_TOOL_OK. " + "Use the tool instead of answering in plain text.", + n=1, + max_tokens=min(settings["llm_max_tokens"], 128), + ) + ) + plain_response = plain_rows[0].content if plain_rows else "" + calls = [call for row in tool_rows for call in row.tool_calls] + expected_call = next( + ( + call + for call in calls + if call.name == "report_model_test" + and call.params.get("answer") == "SRHARNESS_TOOL_OK" + ), + None, + ) + accessible = bool(plain_rows) + tool_call_supported = expected_call is not None + return { + "ok": accessible and tool_call_supported, + "accessible": accessible, + "plain_response": plain_response, + "tool_call_supported": tool_call_supported, + "called_tools": [call.name for call in calls], + } + + def configure(self, payload): + """Run the ``configure`` operation. + + Args: + payload: Serializable event payload. + """ + self._ensure_settings_editable() + with self.lock: + settings = self.validate_settings(payload, initial=self.state == "idle") + self.validate_capabilities(settings) + if self.state == "idle": + updated = {**self.settings, **settings} + self.validate_setting_dependencies(updated) + self.settings = updated + for name in EVALUATOR_CONTEXT_SETTING_NAMES: + if name in settings: + setattr(self.context.args, name, settings[name]) + if set(settings) & { + "validation_fraction", + "split_random_state", + "split_by", + "split_ood_variable", + }: + self.context.invalidate_splits() + else: + current = {**self.settings, **(self.pending_settings or {})} + pending = {key: current.get(key) for key in RUNTIME_SETTING_NAMES} + pending.update(settings) + self.validate_setting_dependencies(pending) + self.pending_settings = pending + return self.snapshot() + + def _ensure_settings_editable(self) -> None: + """Reject setting changes after the search has reached a terminal state.""" + with self.lock: + if self.state not in {"idle", "starting", "running"}: + raise ValueError("Run has finished") + + def resolve(self, path, *, access: str = "read"): + """Resolve . + + Args: + path: Filesystem path. + access: Intended workspace operation. + + Returns: + The resolved readable or writable path. + """ + candidate = self.workspace_manager.resolve(str(path), access=access) + if candidate is None: + raise ValueError("Path must stay inside the workspace") + return candidate diff --git a/src/sr_harness/web/static/brands/anthropic.svg b/src/sr_harness/web/static/brands/anthropic.svg new file mode 100644 index 0000000000000000000000000000000000000000..88dc7450b144f0d94d955733d214c82205b68845 --- /dev/null +++ b/src/sr_harness/web/static/brands/anthropic.svg @@ -0,0 +1 @@ +Anthropic \ No newline at end of file diff --git a/src/sr_harness/web/static/brands/deepseek.svg b/src/sr_harness/web/static/brands/deepseek.svg new file mode 100644 index 0000000000000000000000000000000000000000..185c108b458cbba411cb0004e3eaaf86bc693894 --- /dev/null +++ b/src/sr_harness/web/static/brands/deepseek.svg @@ -0,0 +1 @@ +DeepSeek \ No newline at end of file diff --git a/src/sr_harness/web/static/brands/gemini.svg b/src/sr_harness/web/static/brands/gemini.svg new file mode 100644 index 0000000000000000000000000000000000000000..e15e53ce01fecd30937474f51dcb55a32b186e1b --- /dev/null +++ b/src/sr_harness/web/static/brands/gemini.svg @@ -0,0 +1 @@ +Google Gemini \ No newline at end of file diff --git a/src/sr_harness/web/static/brands/kimi.svg b/src/sr_harness/web/static/brands/kimi.svg new file mode 100644 index 0000000000000000000000000000000000000000..ca8f8c712e854dcb77bb7d47a705e0785fdc10b3 --- /dev/null +++ b/src/sr_harness/web/static/brands/kimi.svg @@ -0,0 +1 @@ +KIMI \ No newline at end of file diff --git a/src/sr_harness/web/static/brands/lmstudio.svg b/src/sr_harness/web/static/brands/lmstudio.svg new file mode 100644 index 0000000000000000000000000000000000000000..a8da16decc89fd8e24ef3d32d18fa1fc746499a3 --- /dev/null +++ b/src/sr_harness/web/static/brands/lmstudio.svg @@ -0,0 +1 @@ +LM Studio \ No newline at end of file diff --git a/src/sr_harness/web/static/brands/meta.svg b/src/sr_harness/web/static/brands/meta.svg new file mode 100644 index 0000000000000000000000000000000000000000..385fb0a1bd3df9fcc16121e30be8604fc494735f --- /dev/null +++ b/src/sr_harness/web/static/brands/meta.svg @@ -0,0 +1 @@ +Meta \ No newline at end of file diff --git a/src/sr_harness/web/static/brands/minimax.svg b/src/sr_harness/web/static/brands/minimax.svg new file mode 100644 index 0000000000000000000000000000000000000000..b1b0a6a2dfda4ffdb10eb03d41a2e6de5b293d51 --- /dev/null +++ b/src/sr_harness/web/static/brands/minimax.svg @@ -0,0 +1 @@ +MiniMax \ No newline at end of file diff --git a/src/sr_harness/web/static/brands/mistral.svg b/src/sr_harness/web/static/brands/mistral.svg new file mode 100644 index 0000000000000000000000000000000000000000..00ee1b9e51f0f2e614a25ab62e501e10d5dfb8d8 --- /dev/null +++ b/src/sr_harness/web/static/brands/mistral.svg @@ -0,0 +1 @@ +Mistral AI \ No newline at end of file diff --git a/src/sr_harness/web/static/brands/openai.svg b/src/sr_harness/web/static/brands/openai.svg new file mode 100644 index 0000000000000000000000000000000000000000..d80bf65332f8e25ae1151e18ce4d3d0c72f1543b --- /dev/null +++ b/src/sr_harness/web/static/brands/openai.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/src/sr_harness/web/static/brands/openrouter.svg b/src/sr_harness/web/static/brands/openrouter.svg new file mode 100644 index 0000000000000000000000000000000000000000..c3ce7aab31efc7b4f0f185a0a6fd0131137d1fc8 --- /dev/null +++ b/src/sr_harness/web/static/brands/openrouter.svg @@ -0,0 +1 @@ +OpenRouter \ No newline at end of file diff --git a/src/sr_harness/web/static/brands/qwen.svg b/src/sr_harness/web/static/brands/qwen.svg new file mode 100644 index 0000000000000000000000000000000000000000..351c2d9315ec5859778c43689134f7bf9c4b0d75 --- /dev/null +++ b/src/sr_harness/web/static/brands/qwen.svg @@ -0,0 +1 @@ +QWen \ No newline at end of file diff --git a/src/sr_harness/web/static/brands/siliconflow.png b/src/sr_harness/web/static/brands/siliconflow.png new file mode 100644 index 0000000000000000000000000000000000000000..697fbb202eeb687efbc7d294d77765fda27ff78f Binary files /dev/null and b/src/sr_harness/web/static/brands/siliconflow.png differ diff --git a/src/sr_harness/web/static/brands/zhipu.svg b/src/sr_harness/web/static/brands/zhipu.svg new file mode 100644 index 0000000000000000000000000000000000000000..4f511bd72fd817a95ff18668a06df3b13f7b84c3 --- /dev/null +++ b/src/sr_harness/web/static/brands/zhipu.svg @@ -0,0 +1,219 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/src/sr_harness/web/static/favicon.svg b/src/sr_harness/web/static/favicon.svg new file mode 100644 index 0000000000000000000000000000000000000000..a17abfb9e5e24e75df00def51cd3570314abf41a --- /dev/null +++ b/src/sr_harness/web/static/favicon.svg @@ -0,0 +1,4 @@ + + + SR + diff --git a/src/sr_harness/web/static/index.html b/src/sr_harness/web/static/index.html new file mode 100644 index 0000000000000000000000000000000000000000..d5ecf5ee591e75c82baf65e14ce67479a2325ea0 --- /dev/null +++ b/src/sr_harness/web/static/index.html @@ -0,0 +1,2977 @@ + + + + + + SRHarness Search Viewer + + + + + + +
+

SRHarness Search Viewer

+ + + +
+ + + + + agent: running +
+
+
+ +
+
+ + +
+
+
+
+ Legend +
+
Node: one local sample from the agent.
+
Solid edge: strong context inheritance.
+
Dashed edge: weak parent, partial tool-call context.
+
Color: selected metric is mapped from red to green; error metrics use lower-is-better.
+
+
+ +
+
+ +
+ + + diff --git a/src/sr_harness/web/static/platform.html b/src/sr_harness/web/static/platform.html new file mode 100644 index 0000000000000000000000000000000000000000..005b7d9eb9448785bed175ac0db85d548797abc2 --- /dev/null +++ b/src/sr_harness/web/static/platform.html @@ -0,0 +1,1588 @@ + + +SRHarness · 交互工作台 + + + + +
正在连接连接中
+
+ +

数据准备

上传或生成数据,并让 Agent 将原始资料整理成可复用的数组。

添加数据

拖放数据文件,也可以从样例数据开始。

将文件拖到此处

用自然语言指导 Agent 检查、清洗或补充数据。结果保存在 context.data/ 目录:manifest.json 记录变量与轴信息;网络或超图数据还会记录 num_nodes 和关系变量。<name>.npy 保存取值

(详情)
准备就绪
确认问题描述根据任务配置自动生成,可在发送前直接编辑。清空以根据任务配置重新生成
+ +

选择样例数据

生成后将作为当前 context.data 加载。

+ diff --git a/src/sr_harness_engine/README.zh.md b/src/sr_harness_engine/README.zh.md new file mode 100644 index 0000000000000000000000000000000000000000..6a676f7218d9f13465610285a013cdcbfa1555af --- /dev/null +++ b/src/sr_harness_engine/README.zh.md @@ -0,0 +1,284 @@ +# SRHarness Engine 符号模型语言规范 + +> 网页版长文档(含快速开始、完整示例和自动生成的 API Reference):[`docs/engine.md`](../../docs/engine.md) + +`sr_harness_engine` 是 SRHarness 的底层符号模型引擎。它负责用结构化表达式描述数学模型,提供安全解析、规范渲染、数值求值和参数优化,并为后续的复杂度、EIC、TopK、Pareto Front、等价判断和模型变换提供统一的表达式树。 + +本引擎描述模型的右端项(RHS)。`y = f(x)`、`dx/dt = f(x)`、节点动力学或轨迹积分等左端项和实验含义由 SRHarness 的问题定义与评估器负责。评估器同时负责数据划分、参数拟合协议、积分方式和评价指标。 + +## 设计原则 + +1. 正式候选模型必须拥有结构化表达式,不能用任意 Python 代码代替。 +2. 表层语法应接近人类书写的数学表达式,底层节点必须具有明确且可检查的语义。 +3. 网络、超图和更高阶关系共用“指标绑定与缩并”机制,不分别引入互不兼容的专用语言。 +4. 变量、待拟合参数和字面数值是不同节点。引擎不会把拼错或缺失的变量自动解释成参数。 +5. 字符串解析只接受本规范列出的语法,不调用 `eval`,也不执行任意 Python 代码。 +6. 表达式的输出形状由自由指标和输入值共同决定;被 `sum[...]` 消去的指标不再出现在结果中。 + +## Python API + +```python +import numpy as np +import sr_harness_engine as engine + +expression = engine.parse( + "param('alpha', value=0.3) * x1 / (1 - param('alpha')) + param('beta')" +) +fit = expression.fit( + {"x1": np.arange(10, dtype=float)}, + 2 * np.arange(10, dtype=float) + 1, +) + +print(expression) # 规范化字符串 +print(fit.parameters) # 命名参数及其拟合值 +prediction = fit.predict({"x1": np.array([10.0, 11.0])}) +``` + +也可以直接构造表达式: + +```python +x1 = engine.Symbol("x1") +x2 = engine.Symbol("x2") +expression = 2.0 * engine.sin(x1) + x2 +``` + +`Symbol` 可以携带默认值,但通常推荐在 `evaluate()` 时显式传入数据: + +```python +x = engine.Symbol("x", value=np.array([1.0, 2.0])) +assert np.allclose((x + 1).evaluate(), [2.0, 3.0]) +``` + +## 标量、变量与非线性函数 + +普通算术表达式使用 Python 风格的 `+`、`-`、`*`、`/` 和 `**`: + +```text +x1 + x2 +2.0 * sin(x1) +x1 ** 2 + exp(-x2) +``` + +当前支持以下逐元素函数: + +```text +abs sin cos tan tanh exp log log10 log2 sqrt sigmoid +``` + +其中 `log`(别名 `ln`)为自然对数,`log10`(别名 `lg`)为十进制对数,`log2` 为二进制对数。反三角函数支持 `arcsin`/`asin`、`arccos`/`acos` 和 `arctan`/`atan`,并在解析时规范化为 `arc*` 名称。 + +字面数字是固定常数,不参与参数优化。 + +解析器会折叠不依赖变量或待拟合参数的加、减、乘法子表达式,但不会调整符号项的顺序。除法、幂和函数调用保留原结构,以免 `2 / 3`、`4 / 3` 或 `sqrt(2)` 这类精确且有意义的常量退化为浮点小数: + +```python +expression = engine.parse("y + (2 * 3) * x") +assert str(expression) == "y + 6 * x" +``` + +## 命名参数 + +待拟合参数必须用 `param` 显式声明: + +```text +param('alpha', value=0.3) * x1 / (1 - param('alpha')) + param('beta') +``` + +同名 `param` 表示同一个参数。任意一次声明可以提供 `value` 作为求值默认值和优化初值;同一表达式中不能为同名参数提供冲突的初值。没有值的参数在拟合前不能求值,拟合时默认以 `1.0` 初始化,也可以通过 `initial` 指定: + +```python +fit = expression.fit(data, target, initial={"beta": 0.0}) +value = fit.expression.evaluate(data) +``` + +拟合目前以均方误差为目标,并通过 `scipy.optimize.minimize` 优化。`fit()` 返回 `FitResult`,不会修改原表达式;其中的 `fit.expression` 已绑定全部拟合参数,可直接求值。如果上下文包含 `data`、`target` 和可选的 `num_nodes`,也可以直接写 `expression.fit(context).expression` 与 `expression.evaluate(context)`。 + +`expression.count_parameters(data)` 返回模型中独立待拟合数值的数量。同名 `param` 只计一次,固定数值不计入;`grouped_param` 在类别数据可用时按不同类别的数量计数。 + +## 分组参数 + +类别字段可以决定参数取值: + +```text +grouped_param(s) * x +grouped_param(s, name='slope', default=0.0) * x +grouped_param(s, name='slope', value={'A': 1.0, 'B': 2.0}) * x +``` + +同一类别的样本共享一个参数,不同类别分别优化。未指定名称时,简单分组变量 `s` 对应的参数键为 `grouped:s`。没有已知值或 `default` 的分组参数必须先拟合才能求值。 + +## 网络与超图的显式指标语法 + +关系使用整数表表示。`A.shape == (E, 2)` 表示二元关系,各列依次为 `(target, source)`;`T.shape == (H, 3)` 表示三元关系,各列依次为 `(target, source1, source2)`。表达式中的指标按照关系表的列顺序绑定: + +```text +x[i] + sum[j](A[i, j], x[i] * x[j]) +``` + +含有指标的表达式必须显式传入 `num_nodes`,它不会从关系表的最大编号推断,因此孤立节点也会被保留: + +```python +prediction = expression.evaluate(data, num_nodes=10) +``` + +求值过程为: + +1. `A[i, j]` 将目标指标 `i`、源指标 `j` 绑定到 `A` 的第 0、1 列; +2. `x[i]` 和 `x[j]` 根据相应列收集节点值; +3. `sum[j]` 对 `j` 缩并,按仍然自由的 `i` 聚合; +4. 输出重新排列为节点轴,孤立节点位置保留为零; +5. 外部的 `x[i]` 是具有自由节点指标的完整节点数组。 + +变量的最后一维是结构维。节点变量为 `(..., N)`,边字段为 `(..., E)`,超边字段为 `(..., H)`,其余前导维使用 NumPy 广播。所有非单例结构变量都必须显式写出指标;例如,含有 `x[i]` 的公式不能同时使用未索引的 `x`。 + +最终表达式可以保留多个自由指标。自由指标按首次出现顺序成为结果末尾的稠密结构轴:`x[i] + x[j]` 返回 `(..., N, N)`,`x[i] * x[j] * x[k]` 返回 `(..., N, N, N)`。这类结果需要枚举全部 `N^r` 个指标组合。 + +`sum` 的第一个参数在数学上是稀疏数值因子,第二个参数是被求和的表达式。`sum[j](A[i, j], eq)` 等价于 `sum[j](A[i, j] * eq)`,但前一种写法允许求值器只请求关系坐标覆盖的 `eq` 分量。更高阶关系采用相同规则: + +```text +x[i] ++ sum[j](A[i, j], x[i] * x[j]) ++ sum[j, k](T[i, j, k], x[i] * x[j] * x[k]) +``` + +求和指标不必来自当前关系。下面的内层 `sum[k]` 对 `x` 的完整节点轴做全局求和,然后将结果广播到外层边关系: + +```text +x[i] + sum[j](A[i, j], x[i] * sum[k](x[k]) * x[j]) +``` + +关系参数可以进行普通代数运算,例如 `A1[i, j] + A2[i, j]` 在重叠边处取值 2,而 `A1[i, j] * A2[i, j]` 表示交集。`A[i, j] + 1` 和 `exp(A[i, j])` 也保持稀疏表示:求值器保存一个非零 `fill_value` 以及偏离它的坐标,不会据此构造稠密的 `N × N` 数组。 + +同一关系表中的重复坐标按二元关系的集合语义去重,不会把一条重复记录解释成权重 2。若需要重边强度,应使用单独的边字段。 + +### `gather` 与关系条目字段 + +`gather` 将结构表达式在关系的非零坐标上取值,并乘以对应的关系值: + +```text +gather(A[i, j], x[i] + x[j]) +gather(T[i, j, k], x[i] * x[j] * x[k]) +``` + +若 `A.shape == (E, 2)`,第一个结果为 `(..., E)`;若 `T.shape == (H, 3)`,第二个结果为 `(..., H)`。操作数可以只使用关系指标的子集,因此 `gather(A[i, j], x[i])` 会沿 `j` 自然广播。直接关系保留坐标表的行顺序;复合关系按坐标字典序输出其非零元素。 + +`gather` 的结果像普通关系字段一样支持算术和函数: + +```text +2 * gather(A[i, j], x[i] + x[j]) +sin(gather(A[i, j], x[i] + x[j])) +gather(A[i, j], x[i] + x[j]) + w +``` + +也可以重新附加完整的关系指标,将条目字段提升回结构表达式: + +```text +sum[i](A[i, j], gather(A[i, j], x[i] + x[j])[i, j] * x[i] * x[j]) +``` + +关系表达式具有非零 `fill_value` 时,其非零支持可能覆盖全部 `N^r` 个坐标;此时 `gather` 的输出也相应变成稠密条目轴。 + +## `aggr/targ/sour` 便捷语法 + +为了表达常见的有向边消息传递,引擎保留与 nd2py 接近的写法: + +```text +aggr(A * targ(x) * sour(x)) +aggr(A, targ(A, x) * sour(A, x)) +aggr(A, targ(x) * sour(x)) +``` + +`aggr(A * expression)` 是推荐写法;双参数形式作为等价便捷写法保留。在这套语法中,`targ` 收集第 0 列目标节点,`sour` 收集第 1 列源节点,`aggr` 按目标节点求和。省略 `targ/sour` 中的关系时,它们继承最近一层 `aggr` 的关系。解析后这些节点立即编译成统一的指标表达式,例如: + +```text +aggr(A * targ(x) * sour(x)) + -> sum[j](A[i, j], x[i] * x[j]) +``` + +因此,字符串渲染只会输出指标表达式,不保留原始的 `aggr/targ/sour` 拼写。 + +### 关系字段与权重 + +在关系缩并内部,带有完整关系指标的普通 Symbol 表示按关系行对齐的字段: + +```text +sum[j](A[i, j], w[i, j] * x[i] * x[j]) +``` + +若 `A.shape == (E, 2)`,则 `w.shape == (E,)` 表示每条边一个权重;`w.shape == (..., E)` 表示前导样本或通道上的每条边权重。关系字段的最后一维必须与 `E` 相等。只有一个同元数、同长度关系时,引擎可以自动推断它;存在歧义时使用 `RelationField(w, relation="A")` 明确关联。这里不要求构造形状为“节点数 × 节点数”的稠密权重矩阵。 + +显式写出的嵌套求和不能重复绑定尚未退出作用域的指标;`sum[j](... sum[j](...) ...)` 会报错,应将内层改为 `sum[k]`。嵌套 `aggr` 会在编译语法糖时自动生成互不冲突的指标名。 + +引擎按指标从左到右绑定关系表各列;本规范约定目标指标在前、源指标在后。新模型应优先使用显式指标语法;便捷语法适合简短的二元消息传递表达式。 + +## 时延 + +```text +x + delay(x, delta) +``` + +`delay(value, delta)` 表示在当前采样时刻读取 `value(t - delta)`。默认求值器沿数组首轴进行线性插值;`delta` 可以是标量,也可以与时间轴等长。超出已有历史范围的位置返回 `NaN`: + +```python +expression.evaluate( + {"x": x, "delta": delta}, + time=np.asarray(time), +) +``` + +ODE/DDE 评估器可以通过 `delay_resolver` 提供自己的历史缓冲和插值策略: + +```python +expression.evaluate(data, delay_resolver=my_history_lookup) +``` + +时延节点只描述 RHS 中的历史引用,不决定积分器、初始历史函数或轨迹损失。 + +## 字符串往返与安全边界 + +`parse(str(expression))` 应生成结构等价的表达式。渲染器会补充保证运算优先级所需的括号,并保留参数的名字和初值。 + +解析器拒绝属性访问、下标切片、推导式、lambda、任意函数调用和非字面关键字参数。例如以下内容都不属于符号模型语言: + +```text +np.sin(x) +__import__('os') +x[0:10] +custom_python_function(x) +``` + +这些限制既提供安全边界,也保证每个模型都能被遍历、渲染、比较和诊断。 + +## 尚未实现的规范部分 + +当前版本已经实现本文件中的解析、渲染、NumPy 求值、命名参数拟合、分组参数拟合、二元关系便捷语法、任意元关系的显式指标缩并以及基础时延插值。以下能力需要在稳定核心语义后继续添加: + +- 维度、单位和输出签名的静态类型检查; +- 多关系连接与关系权重的专用节点; +- 表达式规范化、结构哈希和代数等价判断; +- 可配置且带版本的结构复杂度; +- 子表达式替换和 EIC 接口; +- 多个 RHS 组成的具名模型文档; +- JAX、PyTorch 或其他可微后端; +- 参数边界、约束、鲁棒损失和多种优化器; +- 由 ODE、DDE、网络系统评估器提供的积分与拟合协议。 + +任意代码求值工具属于 SRHarness 的实验与诊断层,不属于本符号语言,也不应默认产生可进入 TopK 或 Pareto Front 的正式候选模型。 + +## SRHarness 评估器接口 + +符号引擎负责表达式,`DefaultEvaluator` 提供普通 `(N,)` 数据的默认实验协议。用户可以继承它,按需改写候选公式的拟合和评价方法: + +```python +from sr_harness import DefaultEvaluator + + +class MyEvaluator(DefaultEvaluator): + @classmethod + def evaluate_candidate(cls, f, context): + metrics = super().evaluate_candidate(f, context) + metrics["custom_metric"] = 0.0 + return metrics +``` + +`fit/evaluate` 处理一般的 `y = f` 等式,`fit_candidate/evaluate_candidate` 只处理可提交的目标公式。Evaluator 返回仅含数值的扁平指标字典;复杂度、诊断和格式化由工具层统一添加。 diff --git a/src/sr_harness_engine/__init__.py b/src/sr_harness_engine/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..196570faaafa1590cf7010dbaa481c1bc3f372fd --- /dev/null +++ b/src/sr_harness_engine/__init__.py @@ -0,0 +1,113 @@ +"""SRHarness Engine: structured symbolic models for scientific discovery.""" + +from __future__ import annotations + +from typing import Any, Callable + +from .expression import ( + Aggregate, + Binary, + Expression, + Function, + Gather, + GroupedParameter, + Index, + Indexed, + Number, + Parameter, + Reduction, + RelationLift, + Symbol, + Variable, + aggr, + function, + gather, + grouped_param, + param, + reduction, + sour, + targ, +) +from .analysis import count_parameters, fold_constants, parameter_values, unbound_parameters +from .desugar import desugar +from .evaluation import evaluate +from .optimize import FitResult, bind_parameters, fit +from .indexed_evaluation import RelationField +from .parser import parse +from .render import render + + +def _unary(name: str) -> Callable[[Any], Expression]: + def constructor(value: Any) -> Expression: + """Create a unary symbolic function expression. + + Args: + value: Symbolic expression or value to wrap. + + Returns: + A symbolic unary function call. + """ + return function(name, value) + + constructor.__name__ = name + constructor.__qualname__ = name + return constructor + + +sin = _unary("sin") +cos = _unary("cos") +tan = _unary("tan") +tanh = _unary("tanh") +sinh = _unary("sinh") +cosh = _unary("cosh") +arcsin = _unary("arcsin") +arccos = _unary("arccos") +arctan = _unary("arctan") +asin = arcsin +acos = arccos +atan = arctan +exp = _unary("exp") +log = _unary("log") +log10 = _unary("log10") +log2 = _unary("log2") +ln = log +lg = log10 +sqrt = _unary("sqrt") +abs = _unary("abs") +sigmoid = _unary("sigmoid") +sign = _unary("sign") +sec = _unary("sec") +sech = _unary("sech") +csc = _unary("csc") +cot = _unary("cot") +inv = _unary("inv") + + +def delay(value: Any, delta: Any) -> Expression: + """Create a delayed-value expression. + + Args: + value: Time-dependent expression to sample from the past. + delta: Scalar or sample-aligned delay interval. + + Returns: + A symbolic ``delay(value, delta)`` call. + """ + return function("delay", value, delta) + + +__all__ = [ + "Aggregate", "Binary", "Expression", "FitResult", "Function", "Gather", + "GroupedParameter", + "Index", "Indexed", "Number", "Parameter", "Reduction", "RelationField", + "RelationLift", "Symbol", + "Variable", "abs", "acos", "aggr", "arccos", "arcsin", "arctan", "asin", "atan", + "cos", "cosh", + "bind_parameters", "cot", "count_parameters", "csc", "delay", "desugar", + "evaluate", "exp", "fit", + "fold_constants", "function", "gather", "grouped_param", "inv", "lg", "ln", "log", + "log10", "log2", + "param", "parameter_values", "parse", "reduction", "render", "sec", "sech", + "sigmoid", "sign", "sin", + "sinh", "sour", "sqrt", "tan", "tanh", "targ", "unbound_parameters", +] diff --git a/src/sr_harness_engine/analysis.py b/src/sr_harness_engine/analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..ebe56430dbffd7b8ecbfda0c87fb71c38b2f661e --- /dev/null +++ b/src/sr_harness_engine/analysis.py @@ -0,0 +1,127 @@ +"""Expression simplification and structural analysis.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import numpy as np + +from .evaluation import grouped_parameter_key +from .expression import Binary, Expression, Function, GroupedParameter, Number, Parameter, Unary +from .tree import iter_preorder, transform + + +def fold_constants(expression: Expression) -> Expression: + """Evaluate closed numerical subexpressions without reordering terms. + + Args: + expression: Symbolic expression to process. + + Returns: + A simplified expression with constant-only branches evaluated. + """ + + def fold(node: Expression) -> Expression: + if isinstance(node, Unary) and isinstance(node.operand, Number): + return Number(-node.operand.value) + if ( + isinstance(node, Binary) + and isinstance(node.left, Number) + and isinstance(node.right, Number) + ): + operations = { + "+": lambda left, right: left + right, + "-": lambda left, right: left - right, + "*": lambda left, right: left * right, + } + if node.operator not in operations: + return node + try: + value = operations[node.operator](node.left.value, node.right.value) + except (ArithmeticError, OverflowError, ValueError): + return node + return Number(value) if _finite_scalar(value) else node + return node + + return transform(expression, fold) + + +def count_parameters( + expression: Expression, + values: Mapping[str, Any] | None = None, + *, + parameters: Mapping[str, Any] | None = None, +) -> int: + """Count independent fitted values represented by an expression. + + Repeated named parameters count once. A grouped parameter counts once per + known category. When categories are unavailable, it counts as one + unresolved parameter family. + + Args: + expression: Symbolic expression to process. + values: Values keyed by symbol name. + parameters: Fitted parameter values keyed by parameter name. + + Returns: + The number of independent scalar parameter values. + """ + values = dict(values or {}) + parameters = dict(parameters or {}) + named: set[str] = set() + grouped: dict[str, GroupedParameter] = {} + for node in iter_preorder(expression): + if isinstance(node, Parameter): + named.add(node.name) + elif isinstance(node, GroupedParameter): + grouped.setdefault(grouped_parameter_key(node), node) + + count = len(named) + for key, node in grouped.items(): + if isinstance(parameters.get(key), Mapping): + count += len(parameters[key]) + continue + try: + labels = np.asarray(node.by.evaluate(values), dtype=object).reshape(-1) + except (KeyError, ValueError): + count += len(node.value) if isinstance(node.value, Mapping) else 1 + else: + count += len({_hashable_label(label) for label in labels}) + return count + + +def parameter_values(expression: Expression) -> dict[str, Any]: + """Collect parameter values already bound into an expression.""" + values: dict[str, Any] = {} + for node in iter_preorder(expression): + if isinstance(node, Parameter) and node.value is not None: + values[node.name] = float(node.value) + elif isinstance(node, GroupedParameter) and node.value is not None: + values[grouped_parameter_key(node)] = dict(node.value) + return values + + +def unbound_parameters(expression: Expression) -> list[str]: + """Return stable names for parameter nodes that have no fitted value.""" + names = [] + for node in iter_preorder(expression): + if isinstance(node, Parameter) and node.value is None: + names.append(node.name) + elif isinstance(node, GroupedParameter) and node.value is None: + names.append(grouped_parameter_key(node)) + return list(dict.fromkeys(names)) + + +def _finite_scalar(value: Any) -> bool: + array = np.asarray(value) + return array.ndim == 0 and bool(np.isfinite(array)) + + +def _hashable_label(value: Any) -> Any: + value = value.item() if isinstance(value, np.generic) else value + try: + hash(value) + except TypeError: + return repr(value) + return value diff --git a/src/sr_harness_engine/context.py b/src/sr_harness_engine/context.py new file mode 100644 index 0000000000000000000000000000000000000000..b832f86b9ea13310a1b4fe3a5cbd1b4e8258ec8a --- /dev/null +++ b/src/sr_harness_engine/context.py @@ -0,0 +1,37 @@ +"""Resolve expression inputs from value mappings or context objects.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + + +def resolve_context( + context: Mapping[str, Any] | Any | None, + target: Any = None, + num_nodes: int | None = None, +) -> tuple[Mapping[str, Any], Any, int | None]: + """Resolve values, target observations, and node metadata from a context. + + A mapping is always interpreted directly as symbol values. Context objects + must expose a mapping-valued ``data`` field and may expose ``target`` and + ``num_nodes`` metadata. + """ + if context is None: + values: Mapping[str, Any] = {} + elif isinstance(context, Mapping): + values = context + else: + candidate = getattr(context, "data", None) + if not isinstance(candidate, Mapping): + raise TypeError("context must expose mapping-valued data") + values = candidate + + if num_nodes is None: + num_nodes = getattr(context, "num_nodes", None) + + if target is None: + target = getattr(context, "target", None) + if isinstance(target, str) and target in values: + target = values[target] + return values, target, num_nodes diff --git a/src/sr_harness_engine/desugar.py b/src/sr_harness_engine/desugar.py new file mode 100644 index 0000000000000000000000000000000000000000..cf9aadae9669bf4705dd538a423ca07e0779a62c --- /dev/null +++ b/src/sr_harness_engine/desugar.py @@ -0,0 +1,90 @@ +"""Lower convenience syntax to the engine's canonical indexed language.""" + +from __future__ import annotations + +from .expression import Aggregate, Expression, Index, Indexed, Reduction, RelationLift +from .tree import children, iter_preorder, with_children + + +def desugar(expression: Expression) -> Expression: + """Compile ``aggr/targ/sour`` nodes into indexed reductions. + + Edge lists use ``(target, source)`` column order. A convenience aggregation + therefore becomes ``sum[j](A[i, j], ...)``: ``j`` is the source index + being reduced and ``i`` is the surviving target index. + + Args: + expression: Symbolic expression to process. + + Returns: + The equivalent expression using indexed reductions. + """ + used = _index_names(expression) + result = _desugar(expression, used) + dangling = next( + (node for node in iter_preorder(result) if isinstance(node, RelationLift)), + None, + ) + if dangling is not None: + name = "targ" if dangling.role == "target" else "sour" + raise ValueError(f"{name}(...) must appear inside aggr(...).") + return result + + +def _desugar(node: Expression, used: set[str]) -> Expression: + if isinstance(node, Aggregate): + relation = _desugar(node.relation, used) + target = _fresh_index("i", used) + source = _fresh_index("j", used) + operand = _lower_lifts(node.operand, relation, target, source, used) + relation_binding = Indexed(relation, (target, source)) + return Reduction((source,), operand, relation_binding) + if isinstance(node, RelationLift): + return node + return with_children(node, tuple(_desugar(child, used) for child in children(node))) + + +def _lower_lifts( + node: Expression, + relation: Expression, + target: Index, + source: Index, + used: set[str], +) -> Expression: + if isinstance(node, Aggregate): + return _desugar(node, used) + if isinstance(node, RelationLift): + if node.relation is not None: + explicit_relation = _desugar(node.relation, used) + if explicit_relation != relation: + raise ValueError("targ/sour relation must match its enclosing aggr relation.") + operand = _desugar(node.operand, used) + index = target if node.role == "target" else source + return Indexed(operand, (index,)) + return with_children( + node, + tuple( + _lower_lifts(child, relation, target, source, used) + for child in children(node) + ), + ) + + +def _index_names(expression: Expression) -> set[str]: + names = set() + for node in iter_preorder(expression): + if isinstance(node, (Indexed, Reduction)): + names.update(index.name for index in node.indices) + return names + + +def _fresh_index(preferred: str, used: set[str]) -> Index: + if preferred not in used: + used.add(preferred) + return Index(preferred) + suffix = 1 + while f"{preferred}{suffix}" in used: + suffix += 1 + name = f"{preferred}{suffix}" + used.add(name) + return Index(name) diff --git a/src/sr_harness_engine/evaluation.py b/src/sr_harness_engine/evaluation.py new file mode 100644 index 0000000000000000000000000000000000000000..697d053c7790d50ec4759bcbdce5da385c0c8742 --- /dev/null +++ b/src/sr_harness_engine/evaluation.py @@ -0,0 +1,423 @@ +"""NumPy evaluator for symbolic expressions.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Callable, Mapping + +import numpy as np + +from .expression import ( + Aggregate, + Binary, + Expression, + Function, + GroupedParameter, + Indexed, + Number, + Parameter, + Reduction, + RelationLift, + Symbol, + Unary, +) +from .tree import children, iter_preorder + + +@dataclass(slots=True) +class _RelationScope: + name: str + table: np.ndarray + indices: tuple[str, ...] + + @property + def bindings(self) -> dict[str, np.ndarray]: + return {name: self.table[:, column] for column, name in enumerate(self.indices)} + + +class _ExpressionEvaluator: + """NumPy expression-tree evaluator.""" + def __init__( + self, + values: Mapping[str, Any] | None, + parameters: Mapping[str, Any] | None, + time: Any, + delay_resolver: Callable[..., Any] | None, + expression: Expression, + num_nodes: int | None = None, + ): + self.values = dict(values or {}) + self.parameters = dict(parameters or {}) + self.time = None if time is None else np.asarray(time, dtype=float) + self.delay_resolver = delay_resolver + self.parameter_defaults = self._parameter_defaults(expression) + self.num_nodes = num_nodes + + def __call__(self, expression: Expression) -> Any: + if any(isinstance(node, Indexed) for node in walk(expression)): + from .indexed_evaluation import IndexedEvaluator + + return IndexedEvaluator( + self.values, + self.parameters, + self.parameter_defaults, + self.num_nodes, + self.time, + self.delay_resolver, + )(expression) + return self._eval(expression, None) + + def _eval(self, node: Expression, scope: _RelationScope | None) -> Any: + if isinstance(node, Number): + return np.asarray(node.value) + if isinstance(node, Symbol): + if node.name in self.values: + return np.asarray(self.values[node.name]) + if node.value is not None: + return np.asarray(node.value) + raise KeyError(f"No value was provided for symbol {node.name!r}.") + if isinstance(node, Parameter): + value = self.parameters.get(node.name, self.parameter_defaults.get(node.name)) + if value is None: + raise ValueError( + f"Parameter {node.name!r} has no value. Fit it or provide " + f"parameters[{node.name!r}]." + ) + return np.asarray(value, dtype=float) + if isinstance(node, GroupedParameter): + labels = np.asarray(self._eval(node.by, scope), dtype=object) + key = grouped_parameter_key(node) + fitted = self.parameters.get(key, node.value) + fitted = {} if fitted is None else dict(fitted) + default = node.default + missing = [label for label in _unique(labels) if label not in fitted] + if missing and default is None: + raise ValueError( + f"Grouped parameter {key!r} has no values for categories " + f"{missing!r}. Fit it first." + ) + result = np.asarray( + [fitted.get(label, default) for label in labels.reshape(-1)], dtype=float + ) + return result.reshape(labels.shape) + if isinstance(node, Unary): + value = self._eval(node.operand, scope) + return -value + if isinstance(node, Binary): + left, right = _align(self._eval(node.left, scope), self._eval(node.right, scope)) + with np.errstate(all="ignore"): + return { + "+": np.add, + "-": np.subtract, + "*": np.multiply, + "/": np.divide, + "**": np.power, + }[node.operator](left, right) + if isinstance(node, Function): + return self._function(node, scope) + if isinstance(node, Indexed): + return self._indexed(node, scope) + if isinstance(node, Reduction): + return self._reduction(node) + if isinstance(node, Aggregate): + return self._aggregate(node) + if isinstance(node, RelationLift): + return self._relation_lift(node, scope) + raise TypeError(f"Cannot evaluate {type(node).__name__}.") + + def _function(self, node: Function, scope: _RelationScope | None) -> Any: + arguments = [self._eval(argument, scope) for argument in node.arguments] + if node.name == "delay": + return self._delay(arguments[0], arguments[1]) + functions = { + "abs": np.abs, + "arccos": np.arccos, + "arcsin": np.arcsin, + "arctan": np.arctan, + "cos": np.cos, + "cosh": np.cosh, + "cot": lambda value: 1.0 / np.tan(value), + "csc": lambda value: 1.0 / np.sin(value), + "exp": np.exp, + "inv": lambda value: 1.0 / value, + "log": np.log, + "log10": np.log10, + "log2": np.log2, + "max": np.maximum, + "min": np.minimum, + "pow2": lambda value: value**2, + "pow3": lambda value: value**3, + "sec": lambda value: 1.0 / np.cos(value), + "sech": lambda value: 1.0 / np.cosh(value), + "sin": np.sin, + "sinh": np.sinh, + "sign": np.sign, + "sqrt": np.sqrt, + "tan": np.tan, + "tanh": np.tanh, + "sigmoid": lambda value: 1.0 / (1.0 + np.exp(-value)), + } + with np.errstate(all="ignore"): + return functions[node.name](*arguments) + + def _indexed(self, node: Indexed, scope: _RelationScope | None) -> Any: + value = np.asarray(self._eval(node.base, None)) + names = tuple(index.name for index in node.indices) + if scope is not None and len(names) > 1: + if names != scope.indices: + raise ValueError( + f"Relation fields must use bound indices {scope.indices}, not {names}." + ) + if isinstance(node.base, Symbol) and node.base.name == scope.name: + return np.ones(len(scope.table), dtype=float) + edge_count = len(scope.table) + if value.ndim == 1 and value.shape[0] == edge_count: + return value + if value.ndim > 1 and value.shape[-1] == edge_count: + return np.moveaxis(value, -1, 0) + raise ValueError( + f"Relation field {node.base!s} must have an edge axis of length " + f"{edge_count} in its last dimension." + ) + if scope is not None and len(names) == 1 and names[0] in scope.bindings: + return value[scope.bindings[names[0]]] + if len(names) > value.ndim: + raise ValueError( + f"{len(names)} symbolic indices were applied to a {value.ndim}-dimensional value." + ) + # A free index names an existing leading axis; it does not slice it. + return value + + def _reduction(self, node: Reduction) -> Any: + scope = self._relation_scope(node.relation) if node.relation is not None else None + value = np.asarray(self._eval(node.operand, scope)) + reduced = {index.name for index in node.indices} + if scope is None: + if self._find_relation_scope(node.operand) is not None: + raise ValueError( + "Pass the relation separately, for example " + "sum[j](A[i, j], expression)." + ) + return np.sum(value, axis=tuple(range(min(len(reduced), value.ndim)))) + + unknown = reduced - set(scope.indices) + if unknown: + raise ValueError( + f"Indices {sorted(unknown)!r} are not bound by relation {scope.name!r}." + ) + free = [name for name in scope.indices if name not in reduced] + if not free: + return np.sum(value, axis=0) + coordinates = tuple(scope.bindings[name] for name in free) + sizes = tuple( + self._index_size(node.operand, name, coordinate) + for name, coordinate in zip(free, coordinates) + ) + result = np.zeros(sizes + value.shape[1:], dtype=np.result_type(value, float)) + np.add.at(result, coordinates[0] if len(coordinates) == 1 else coordinates, value) + return result + + def _relation_scope(self, relation: Expression) -> _RelationScope: + if not isinstance(relation, Indexed) or not isinstance(relation.base, Symbol): + raise ValueError("A reduction relation must be indexed, such as A[i, j].") + name, table = self._relation(relation.base) + indices = tuple(index.name for index in relation.indices) + if table.shape[1] != len(indices): + raise ValueError( + f"Relation {name!r} has {table.shape[1]} columns but " + f"{len(indices)} indices were supplied." + ) + return _RelationScope(name, table, indices) + + def _aggregate(self, node: Aggregate) -> Any: + relation_name, table = self._relation(node.relation) + if table.shape[1] != 2: + raise ValueError("aggr currently expects a two-column edge list.") + scope = _RelationScope(relation_name, table, ("source", "target")) + value = np.asarray(self._eval(node.operand, scope)) + target = table[:, 1] + fallback = int(target.max()) + 1 if target.size else 0 + size = self._leading_size(node.operand, fallback=fallback) + result = np.zeros((size,) + value.shape[1:], dtype=np.result_type(value, float)) + np.add.at(result, target, value) + return result + + def _relation_lift(self, node: RelationLift, scope: _RelationScope | None) -> Any: + if node.relation is not None: + name, table = self._relation(node.relation) + scope = _RelationScope(name, table, ("source", "target")) + if scope is None: + raise ValueError(f"{node.role} requires a relation argument or an enclosing aggr(...).") + column = 1 if node.role == "target" else 0 + return np.asarray(self._eval(node.operand, None))[scope.table[:, column]] + + def _delay(self, value: Any, lag: Any) -> Any: + value = np.asarray(value, dtype=float) + lag = np.asarray(lag, dtype=float) + if self.delay_resolver is not None: + return np.asarray(self.delay_resolver(value, lag, self.time)) + if value.ndim == 0: + return value + time = np.arange(value.shape[0], dtype=float) if self.time is None else self.time + if time.shape != (value.shape[0],): + raise ValueError("time must be one-dimensional and match the leading data axis.") + query = time - lag + try: + query = np.broadcast_to(query, (value.shape[0],)) + except ValueError as error: + raise ValueError( + "delay delta must be scalar or match the leading data axis." + ) from error + flat = value.reshape(value.shape[0], -1) + delayed = np.column_stack([ + np.interp(query, time, column, left=np.nan, right=np.nan) for column in flat.T + ]) + return delayed.reshape(value.shape) + + def _find_relation_scope(self, node: Expression) -> _RelationScope | None: + relations: dict[str, tuple[np.ndarray, tuple[str, ...]]] = {} + for item in walk(node): + if not isinstance(item, Indexed) or not isinstance(item.base, Symbol): + continue + if item.base.name not in self.values: + continue + value = np.asarray(self.values[item.base.name]) + if value.ndim != 2 or value.shape[1] != len(item.indices) or len(item.indices) < 2: + continue + if value.dtype.kind not in "iu": + continue + relations[item.base.name] = ( + value.astype(int, copy=False), + tuple(index.name for index in item.indices), + ) + if not relations: + return None + if len(relations) > 1: + raise ValueError( + "One reduction cannot currently combine multiple relations: " + f"{sorted(relations)}." + ) + name, (table, indices) = next(iter(relations.items())) + if np.any(table < 0): + raise ValueError("Relation indices must be non-negative integers.") + return _RelationScope(name, table, indices) + + def _relation(self, node: Expression) -> tuple[str, np.ndarray]: + value = np.asarray(self._eval(node, None)) + if value.ndim != 2 or value.dtype.kind not in "iu" or value.shape[1] < 2: + raise ValueError("A relation must be an integer array shaped (relations, arity).") + name = node.name if isinstance(node, Symbol) else "" + return name, value.astype(int, copy=False) + + def _index_size(self, node: Expression, index: str, coordinate: np.ndarray) -> int: + sizes = [] + for item in walk(node): + if not isinstance(item, Indexed) or len(item.indices) != 1: + continue + if not isinstance(item.base, Symbol): + continue + if item.base.name in self.values: + value = np.asarray(self.values[item.base.name]) + # Every singly-indexed node field belongs to the same node domain + # inside one relation contraction, even when this particular free + # index does not occur on that field (for example A[i,j] with x[j]). + if value.ndim: + sizes.append(value.shape[0]) + fallback = int(coordinate.max()) + 1 if coordinate.size else 0 + return max(sizes, default=fallback) + + def _leading_size(self, node: Expression, fallback: int) -> int: + sizes = [] + for item in walk(node): + if isinstance(item, Symbol) and item.name in self.values: + value = np.asarray(self.values[item.name]) + is_edge_list = ( + value.ndim == 2 and value.dtype.kind in "iu" and value.shape[1] == 2 + ) + if value.ndim and not is_edge_list: + sizes.append(value.shape[0]) + return max(sizes, default=fallback) + + @staticmethod + def _parameter_defaults(expression: Expression) -> dict[str, float | None]: + defaults: dict[str, float | None] = {} + for node in walk(expression): + if not isinstance(node, Parameter): + continue + previous = defaults.get(node.name) + if previous is not None and node.value is not None and previous != node.value: + raise ValueError(f"Conflicting initial values for parameter {node.name!r}.") + if node.value is not None or node.name not in defaults: + defaults[node.name] = node.value + return defaults + + +def _align(left: Any, right: Any) -> tuple[np.ndarray, np.ndarray]: + left, right = np.asarray(left), np.asarray(right) + if left.ndim == 1 and right.ndim > 1 and left.shape[0] == right.shape[0]: + left = left.reshape((left.shape[0],) + (1,) * (right.ndim - 1)) + if right.ndim == 1 and left.ndim > 1 and right.shape[0] == left.shape[0]: + right = right.reshape((right.shape[0],) + (1,) * (left.ndim - 1)) + return left, right + + +def _unique(values: np.ndarray) -> list[Any]: + result = [] + for value in values.reshape(-1): + value = value.item() if isinstance(value, np.generic) else value + if value not in result: + result.append(value) + return result + + +def grouped_parameter_key(node: GroupedParameter) -> str: + """Return the storage key for a grouped parameter. + + Args: + node: Grouped parameter to identify. + + Returns: + Its explicit name or a stable name derived from the grouping symbol. + """ + if node.name: + return node.name + if isinstance(node.by, Symbol): + return f"grouped:{node.by.name}" + return f"grouped:{node.by}" + + +def walk(node: Expression): + """Iterate over an expression tree in preorder. + + Args: + node: Expression or syntax-tree node. + + Yields: + Expression nodes in parent-before-children order. + """ + yield from iter_preorder(node) + + +def evaluate( + expression: Expression, + values: Mapping[str, Any] | None = None, + *, + parameters: Mapping[str, Any] | None = None, + time: Any = None, + delay_resolver: Callable[..., Any] | None = None, + num_nodes: int | None = None, +) -> Any: + """Evaluate an expression without executing arbitrary Python code. + + Args: + expression: Symbolic expression to process. + values: Values keyed by symbol name. + parameters: Fitted parameter values keyed by parameter name. + time: Optional sample times. + delay_resolver: Optional callback that resolves delayed values. + num_nodes: Explicit node count for indexed expressions. + + Returns: + The evaluated scalar or NumPy array. + """ + return _ExpressionEvaluator(values, parameters, time, delay_resolver, expression, num_nodes)(expression) diff --git a/src/sr_harness_engine/expression.py b/src/sr_harness_engine/expression.py new file mode 100644 index 0000000000000000000000000000000000000000..5ea259067f4e6e86b613a5d07bac0d88d287bebc --- /dev/null +++ b/src/sr_harness_engine/expression.py @@ -0,0 +1,530 @@ +"""Expression nodes for the SRHarness symbolic engine.""" + +from __future__ import annotations + +from copy import deepcopy +from dataclasses import dataclass, field +from collections.abc import Iterator +from typing import TYPE_CHECKING, Any, Mapping + +if TYPE_CHECKING: + from .optimize import FitResult + + +class Expression: + """Base class of every symbolic expression node.""" + + def __add__(self, other: Any) -> Expression: + return Binary("+", self, as_expression(other)) + + def __radd__(self, other: Any) -> Expression: + return Binary("+", as_expression(other), self) + + def __sub__(self, other: Any) -> Expression: + return Binary("-", self, as_expression(other)) + + def __rsub__(self, other: Any) -> Expression: + return Binary("-", as_expression(other), self) + + def __mul__(self, other: Any) -> Expression: + return Binary("*", self, as_expression(other)) + + def __rmul__(self, other: Any) -> Expression: + return Binary("*", as_expression(other), self) + + def __truediv__(self, other: Any) -> Expression: + return Binary("/", self, as_expression(other)) + + def __rtruediv__(self, other: Any) -> Expression: + return Binary("/", as_expression(other), self) + + def __pow__(self, other: Any) -> Expression: + return Binary("**", self, as_expression(other)) + + def __rpow__(self, other: Any) -> Expression: + return Binary("**", as_expression(other), self) + + def __neg__(self) -> Expression: + return Unary("-", self) + + def __getitem__(self, index: Index | tuple[Index, ...] | str) -> Expression: + if isinstance(index, tuple): + indices = tuple(as_index(item) for item in index) + else: + indices = (as_index(index),) + return Indexed(self, indices) + + def evaluate( + self, + values: Mapping[str, Any] | None = None, + *, + parameters: Mapping[str, Any] | None = None, + time: Any = None, + delay_resolver: Any = None, + num_nodes: int | None = None, + ) -> Any: + """Evaluate this expression with NumPy values. + + Args: + values: Values keyed by symbol name, or a context exposing ``data`` + and optional ``num_nodes`` metadata. + parameters: Fitted parameter values keyed by parameter name. + time: Optional sample times. + delay_resolver: Optional callback that resolves delayed values. + num_nodes: Explicit node count for indexed expressions. + + Returns: + The evaluated scalar or array. + """ + from .context import resolve_context + from .evaluation import evaluate + + values, _, num_nodes = resolve_context(values, num_nodes=num_nodes) + + return evaluate( + self, + values=values, + parameters=parameters, + time=time, + delay_resolver=delay_resolver, + num_nodes=num_nodes, + ) + + eval = evaluate + + @property + def operands(self) -> tuple[Expression, ...]: + """Child expressions, exposed as an immutable tuple. + + Returns: + The direct child nodes in expression order. + """ + from .tree import children + + return children(self) + + def iter_preorder(self) -> Iterator[Expression]: + """Yield this node followed by its descendants. + + Yields: + Expression nodes in preorder. + """ + from .tree import iter_preorder + + yield from iter_preorder(self) + + def iter_postorder(self) -> Iterator[Expression]: + """Yield descendants followed by this node. + + Yields: + Expression nodes in postorder. + """ + from .tree import iter_postorder + + yield from iter_postorder(self) + + def copy(self) -> Expression: + """Return an independent copy. + + Returns: + A deep copy of this expression. + """ + return deepcopy(self) + + def replace(self, old: Expression, new: Expression) -> Expression: + """Return a tree in which the exact *old* node is replaced by *new*. + + Args: + old: Existing expression node to replace. + new: Replacement expression node. + + Returns: + A copied expression tree with matching nodes replaced. + """ + from .tree import replace + + return replace(self, old, new) + + def to_str( + self, + *, + latex: bool = False, + number_format: str = "", + ) -> str: + """Render the expression as plain text or LaTeX. + + Args: + latex: Whether to render LaTeX notation. + number_format: Format specification for numeric literals. + + Returns: + The rendered expression. + """ + from .render import render + + return render(self, latex=latex, number_format=number_format) + + def to_tree(self, *, number_format: str = "") -> str: + """Render a compact preorder tree for diagnostics. + + Args: + number_format: Format specification for numeric literals. + + Returns: + A multiline representation of the expression tree. + """ + from .tree import children + + lines = [self.to_str(number_format=number_format)] + + def visit(node: Expression, prefix: str, connector: str) -> None: + lines.append(f"{prefix}{connector}{node.to_str(number_format=number_format)}") + values = children(node) + continuation = " " if connector == "└ " else "│ " + for index, child in enumerate(values): + last = index == len(values) - 1 + visit(child, prefix + continuation, "└ " if last else "├ ") + + values = children(self) + for index, child in enumerate(values): + visit(child, "", "└ " if index == len(values) - 1 else "├ ") + return "\n".join(lines) + + def __len__(self) -> int: + return sum(1 for _ in self.iter_preorder()) + + def fit( + self, + values: Mapping[str, Any], + target: Any = None, + *, + initial: Mapping[str, Any] | None = None, + method: str = "BFGS", + options: Mapping[str, Any] | None = None, + num_nodes: int | None = None, + ) -> FitResult: + """Fit named and grouped parameters against a target array. + + Args: + values: Values keyed by symbol name, or a context exposing ``data``, + ``target``, and optional ``num_nodes`` metadata. + target: Target name or target values. Omit when supplied by context. + initial: Optional initial parameter values. + method: Optimization method name. + options: Optional optimizer settings. + num_nodes: Explicit node count for indexed expressions. + + Returns: + The fitted expression, parameter values, predictions, and loss. + """ + from .context import resolve_context + from .optimize import fit + + values, target, num_nodes = resolve_context(values, target, num_nodes) + if target is None: + raise ValueError("A target array or a context target is required for fitting.") + + return fit( + self, values, target, initial=initial, method=method, + options=options, num_nodes=num_nodes, + ) + + def fold_constants(self) -> Expression: + """Return a copy with closed numerical subexpressions evaluated. + + Returns: + A simplified expression with closed numeric branches folded. + """ + from .analysis import fold_constants + + return fold_constants(self) + + def count_parameters( + self, + values: Mapping[str, Any] | None = None, + *, + parameters: Mapping[str, Any] | None = None, + ) -> int: + """Count independent fitted values represented by this expression. + + Args: + values: Values keyed by symbol name. + parameters: Fitted parameter values keyed by parameter name. + + Returns: + The number of independent scalar parameter values. + """ + from .analysis import count_parameters + + return count_parameters(self, values, parameters=parameters) + + def __str__(self) -> str: + from .render import render + + return render(self) + + +@dataclass(frozen=True, slots=True) +class Number(Expression): + """Fixed numeric literal.""" + value: int | float + + +@dataclass(frozen=True, slots=True) +class Symbol(Expression): + """Named input symbol with an optional bound value.""" + name: str + value: Any = field(default=None, compare=False, repr=False) + + +@dataclass(frozen=True, slots=True) +class Parameter(Expression): + """Named scalar parameter optimized during fitting.""" + name: str + value: float | None = field(default=None, compare=False) + + +@dataclass(frozen=True, slots=True) +class GroupedParameter(Expression): + """Parameter with one fitted value per category.""" + by: Expression + name: str | None = None + value: Mapping[Any, float] | None = field(default=None, compare=False) + default: float | None = field(default=None, compare=False) + + +@dataclass(frozen=True, slots=True) +class Index: + """Symbolic relation index.""" + name: str + + def __str__(self) -> str: + return self.name + + +@dataclass(frozen=True, slots=True) +class Unary(Expression): + """Unary expression node.""" + operator: str + operand: Expression + + +@dataclass(frozen=True, slots=True) +class Binary(Expression): + """Binary expression node.""" + operator: str + left: Expression + right: Expression + + +@dataclass(frozen=True, slots=True) +class Function(Expression): + """Named function-call expression node.""" + name: str + arguments: tuple[Expression, ...] + + +@dataclass(frozen=True, slots=True) +class Indexed(Expression): + """Expression annotated with symbolic indices.""" + base: Expression + indices: tuple[Index, ...] + + +@dataclass(frozen=True, slots=True) +class Reduction(Expression): + """Sum reduction with an optional relation binder.""" + indices: tuple[Index, ...] + operand: Expression + relation: Expression | None = None + + +@dataclass(frozen=True, slots=True) +class Gather(Expression): + """Weighted collection of a structural expression on relation entries.""" + relation: Expression + operand: Expression + + +@dataclass(frozen=True, slots=True) +class Aggregate(Expression): + """Convenience aggregation node lowered to indexed syntax.""" + relation: Expression + operand: Expression + + +@dataclass(frozen=True, slots=True) +class RelationLift(Expression): + """Convenience source or target projection used inside an aggregation.""" + role: str + operand: Expression + relation: Expression | None = None + + +def as_expression(value: Any) -> Expression: + """Convert a numeric literal or expression into an expression node. + + Args: + value: Existing expression or numeric literal. + + Returns: + The corresponding expression node. + """ + if isinstance(value, Expression): + return value + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise TypeError(f"Expected an expression or number, got {type(value).__name__}.") + return Number(value) + + +Variable = Symbol + + +def as_index(value: Index | str) -> Index: + """Convert an index name into an index node. + + Args: + value: Existing index or valid Python identifier. + + Returns: + The corresponding symbolic index. + """ + if isinstance(value, Index): + return value + if isinstance(value, str) and value.isidentifier(): + return Index(value) + raise TypeError(f"Expected an index name, got {value!r}.") + + +def param(name: str, value: float | None = None) -> Parameter: + """Create a named scalar parameter. + + Args: + name: Parameter name shared by all matching occurrences. + value: Optional initial or fixed value. + + Returns: + A symbolic scalar parameter. + """ + return Parameter(name, value) + + +def grouped_param( + by: Expression, + *, + name: str | None = None, + value: Mapping[Any, float] | None = None, + default: float | None = None, +) -> GroupedParameter: + """Create a parameter with one fitted value per category. + + Args: + by: Symbol or expression containing category labels. + name: Optional parameter-map name. + value: Optional initial values keyed by category. + default: Value used for categories absent from ``value``. + + Returns: + A category-dependent parameter expression. + """ + return GroupedParameter(by, name=name, value=value, default=default) + + +def function(name: str, *arguments: Any) -> Function: + """Create a supported symbolic function call. + + Args: + name: Function name recognized by the evaluator. + *arguments: Function operands. + + Returns: + A symbolic function node. + """ + return Function(name, tuple(as_expression(argument) for argument in arguments)) + + +def reduction( + indices: Index | tuple[Index, ...], + operand: Any, + relation: Any = None, +) -> Reduction: + """Create an indexed sum reduction. + + Args: + indices: Symbolic indices. + operand: Expression being reduced or transformed. + relation: Relation expression that binds symbolic indices. + + Returns: + A symbolic reduction node. + """ + if not isinstance(indices, tuple): + indices = (indices,) + return Reduction( + tuple(as_index(index) for index in indices), + as_expression(operand), + None if relation is None else as_expression(relation), + ) + + +def gather(relation: Any, operand: Any) -> Gather: + """Collect structural values at the nonzero entries of a relation. + + Args: + relation: Indexed relation or relation-valued expression. + operand: Structural expression evaluated at relation coordinates. + + Returns: + A relation-aligned symbolic field. + """ + return Gather(as_expression(relation), as_expression(operand)) + + +def aggr(relation: Any, operand: Any = None) -> Expression: + """Build and lower target-wise graph aggregation syntax. + + Args: + relation: Edge relation, or a product containing it when ``operand`` is omitted. + operand: Message expression to aggregate by target node. + + Returns: + The equivalent canonical indexed reduction. + """ + from .desugar import desugar + from .parser import _split_aggregation + + if operand is None: + relation, operand = _split_aggregation(as_expression(relation)) + return desugar(Aggregate(as_expression(relation), as_expression(operand))) + + +def targ(*arguments: Any) -> RelationLift: + """Project node values onto relation targets inside ``aggr``. + + Args: + *arguments: Either ``value`` or ``relation, value``. + + Returns: + A target projection used by aggregation desugaring. + """ + if len(arguments) == 1: + return RelationLift("target", as_expression(arguments[0])) + if len(arguments) == 2: + return RelationLift("target", as_expression(arguments[1]), as_expression(arguments[0])) + raise TypeError("targ expects targ(value) or targ(relation, value).") + + +def sour(*arguments: Any) -> RelationLift: + """Project node values onto relation sources inside ``aggr``. + + Args: + *arguments: Either ``value`` or ``relation, value``. + + Returns: + A source projection used by aggregation desugaring. + """ + if len(arguments) == 1: + return RelationLift("source", as_expression(arguments[0])) + if len(arguments) == 2: + return RelationLift("source", as_expression(arguments[1]), as_expression(arguments[0])) + raise TypeError("sour expects sour(value) or sour(relation, value).") diff --git a/src/sr_harness_engine/indexed_evaluation.py b/src/sr_harness_engine/indexed_evaluation.py new file mode 100644 index 0000000000000000000000000000000000000000..2684460cc9e4272e8e428c5c49d80c754bb13237 --- /dev/null +++ b/src/sr_harness_engine/indexed_evaluation.py @@ -0,0 +1,839 @@ +"""Demand-driven evaluator for expressions with symbolic structural indices.""" + +from __future__ import annotations + +from dataclasses import dataclass +from itertools import product +from typing import Any, Callable, Mapping + +import numpy as np + +from .expression import ( + Binary, + Expression, + Function, + Gather, + GroupedParameter, + Index, + Indexed, + Number, + Parameter, + Reduction, + Symbol, + Unary, +) +from .tree import children + + +@dataclass(frozen=True, slots=True) +class RelationField: + """Values stored on the entries of a named relation. + + Args: + values: Array whose last dimension enumerates relation entries. + relation: Name of the coordinate-table symbol defining those entries. + """ + + values: Any + relation: str + + +@dataclass(slots=True) +class _Demand: + indices: tuple[str, ...] + coordinates: np.ndarray + + def project(self, indices: tuple[str, ...]) -> np.ndarray: + if not indices: + return np.empty((len(self.coordinates), 0), dtype=np.intp) + columns = [self.indices.index(index) for index in indices] + return self.coordinates[:, columns] + + +@dataclass(slots=True) +class _SparseTensor: + indices: tuple[str, ...] + coordinates: np.ndarray + values: np.ndarray + fill_value: float + num_nodes: int + + @property + def shape(self) -> tuple[int, ...]: + return (self.num_nodes,) * len(self.indices) + + +class IndexedEvaluator: + """Evaluate indexed expressions against a fixed structural demand.""" + + def __init__( + self, + values: Mapping[str, Any], + parameters: Mapping[str, Any], + parameter_defaults: Mapping[str, float | None], + num_nodes: int | None, + time: Any, + delay_resolver: Callable[..., Any] | None, + ): + if num_nodes is None: + raise ValueError("num_nodes must be provided when evaluating indexed expressions.") + if isinstance(num_nodes, bool) or int(num_nodes) != num_nodes or num_nodes <= 0: + raise ValueError("num_nodes must be a positive integer.") + self.num_nodes = int(num_nodes) + self.values = dict(values) + self.parameters = dict(parameters) + self.parameter_defaults = dict(parameter_defaults) + self.time = None if time is None else np.asarray(time, dtype=float) + self.delay_resolver = delay_resolver + self._free_cache: dict[int, tuple[str, ...]] = {} + self._relation_cache: dict[int, _SparseTensor] = {} + self._domain_cache: dict[int, Expression | None] = {} + + def __call__(self, expression: Expression) -> Any: + self._validate_scopes(expression) + self._validate_bare_symbols(expression) + free = self.free_indices(expression) + coordinates = self._root_coordinates(free) + result = self._eval_at(expression, _Demand(free, coordinates)) + if free: + result = np.asarray(result) + return result.reshape(result.shape[:-1] + (self.num_nodes,) * len(free)) + if self.relation_domain(expression) is not None: + return result + if np.ndim(result) and np.shape(result)[-1:] == (1,): + return np.asarray(result)[..., 0] + return result + + def _root_coordinates(self, indices: tuple[str, ...]) -> np.ndarray: + if not indices: + return np.empty((1, 0), dtype=np.intp) + return np.asarray( + list(product(range(self.num_nodes), repeat=len(indices))), dtype=np.intp + ).reshape(-1, len(indices)) + + def free_indices(self, node: Expression) -> tuple[str, ...]: + """Return free structural indices in stable expression order. + + Args: + node: Expression subtree to inspect. + + Returns: + Index names not bound by a reduction in this subtree. + """ + cached = self._free_cache.get(id(node)) + if cached is not None: + return cached + if isinstance(node, Gather): + result = () + elif isinstance(node, Indexed): + result = tuple(index.name for index in node.indices) + elif isinstance(node, Reduction): + inputs = self.free_indices(node.operand) + if node.relation is not None: + inputs = _ordered_union(inputs, self.free_indices(node.relation)) + reduced = {index.name for index in node.indices} + result = tuple(index for index in inputs if index not in reduced) + else: + result = () + for child in children(node): + result = _ordered_union(result, self.free_indices(child)) + self._free_cache[id(node)] = result + return result + + def relation_domain(self, node: Expression) -> Expression | None: + """Return the relation whose entry axis is carried by an expression. + + Args: + node: Expression subtree to inspect. + + Returns: + The relation expression defining the entry axis, if present. + """ + key = id(node) + if key in self._domain_cache: + return self._domain_cache[key] + if isinstance(node, Gather): + result = node.relation + elif isinstance(node, Unary): + result = self.relation_domain(node.operand) + elif isinstance(node, Function): + result = self._merge_domains( + tuple(self.relation_domain(argument) for argument in node.arguments) + ) + elif isinstance(node, Binary): + result = self._merge_domains( + (self.relation_domain(node.left), self.relation_domain(node.right)) + ) + else: + result = None + self._domain_cache[key] = result + return result + + @staticmethod + def _merge_domains(domains: tuple[Expression | None, ...]) -> Expression | None: + present = [domain for domain in domains if domain is not None] + if not present: + return None + first = present[0] + if any(domain != first for domain in present[1:]): + raise ValueError("One expression cannot combine fields from different relations.") + return first + + def _eval_at(self, node: Expression, demand: _Demand) -> np.ndarray: + if isinstance(node, Number): + return np.asarray(node.value) + if isinstance(node, Symbol): + value = self._symbol_value(node) + if isinstance(value, RelationField): + value = value.values + value = np.asarray(value) + if value.ndim == 0: + return value + if not demand.indices: + return value + if value.shape[-1] != 1: + raise ValueError( + f"Symbol {node.name!r} must be indexed in an indexed expression; " + "only a trailing singleton structural dimension may be unindexed." + ) + return value + if isinstance(node, Parameter): + return np.asarray(self._parameter_value(node), dtype=float) + if isinstance(node, GroupedParameter): + labels = np.asarray(self._eval_at(node.by, demand), dtype=object) + key = _grouped_parameter_key(node) + fitted = self.parameters.get(key, node.value) + fitted = {} if fitted is None else dict(fitted) + missing = [label for label in _unique(labels) if label not in fitted] + if missing and node.default is None: + raise ValueError(f"Grouped parameter {key!r} has no values for {missing!r}.") + flat = [fitted.get(label, node.default) for label in labels.reshape(-1)] + return np.asarray(flat, dtype=float).reshape(labels.shape) + if isinstance(node, Indexed): + return self._indexed_at(node, demand) + if isinstance(node, Gather): + return self._gather_at(node, demand) + if isinstance(node, Reduction): + return self._reduction_at(node, demand) + if isinstance(node, Unary): + return -self._eval_at(node.operand, demand) + if isinstance(node, Binary): + left = self._eval_at(node.left, demand) + right = self._eval_at(node.right, demand) + with np.errstate(all="ignore"): + return _binary(node.operator, left, right) + if isinstance(node, Function): + arguments = [self._eval_at(argument, demand) for argument in node.arguments] + return self._function(node.name, arguments) + raise TypeError(f"Cannot evaluate indexed node {type(node).__name__}.") + + def _indexed_at(self, node: Indexed, demand: _Demand) -> np.ndarray: + if not isinstance(node.base, Symbol): + domain = self.relation_domain(node.base) + if domain is not None: + return self._relation_field_at(node, domain, demand) + indices = tuple(index.name for index in node.indices) + base_indices = self.free_indices(node.base) + if len(indices) != 1 or len(base_indices) != 1: + raise ValueError( + "A computed expression can be reindexed only when it has one free " + "structural index." + ) + requested = demand.project(indices) + return self._eval_at(node.base, _Demand(base_indices, requested)) + name = node.base.name + indices = tuple(index.name for index in node.indices) + requested = demand.project(indices) + raw = self._symbol_value(node.base) + field = raw if isinstance(raw, RelationField) else None + value = np.asarray(field.values if field is not None else raw) + + if self._is_relation_table(value, len(indices)): + sparse = self._relation_from_table(name, value, indices) + return self._sparse_lookup(sparse, requested) + + if len(indices) == 1: + if value.ndim == 0 or value.shape[-1] != self.num_nodes: + raise ValueError( + f"Node variable {name!r} must have shape (..., num_nodes); " + f"got {value.shape}." + ) + return value[..., requested[:, 0]] + + relation_name = ( + field.relation + if field is not None + else self._infer_relation(name, value, len(indices)) + ) + relation = self._relation_table(relation_name, len(indices)) + if value.ndim == 0 or value.shape[-1] != len(relation): + raise ValueError( + f"Relation field {name!r} must have shape (..., {len(relation)}); " + f"got {value.shape}." + ) + positions = {_coordinate_key(row): position for position, row in enumerate(relation)} + output = np.zeros(value.shape[:-1] + (len(requested),), dtype=value.dtype) + selected = [ + (column, positions.get(_coordinate_key(row))) + for column, row in enumerate(requested) + ] + for column, position in selected: + if position is not None: + output[..., column] = value[..., position] + return output + + def _gather_at(self, node: Gather, demand: _Demand) -> np.ndarray: + if demand.indices: + raise ValueError( + "A gathered relation field must be explicitly indexed before it is " + "used in a structural expression." + ) + relation_indices, coordinates, weights = self._gather_entries(node.relation) + operand_indices = self.free_indices(node.operand) + unknown = set(operand_indices) - set(relation_indices) + if unknown: + raise ValueError( + f"gather operand uses indices absent from its relation: {sorted(unknown)!r}." + ) + values = self._eval_at(node.operand, _Demand(relation_indices, coordinates)) + return np.asarray(values) * weights + + def _relation_field_at( + self, node: Indexed, domain: Expression, demand: _Demand + ) -> np.ndarray: + indices = tuple(index.name for index in node.indices) + relation_indices, coordinates, _ = self._gather_entries(domain) + if len(indices) != len(relation_indices): + raise ValueError( + f"This relation field requires {len(relation_indices)} indices, " + f"but {len(indices)} were supplied." + ) + values = np.asarray( + self._eval_at(node.base, _Demand((), np.empty((1, 0), dtype=np.intp))) + ) + if values.ndim == 0 or values.shape[-1] != len(coordinates): + raise ValueError("A relation-domain expression must end with its entry axis.") + requested = demand.project(indices) + positions = { + _coordinate_key(row): position for position, row in enumerate(coordinates) + } + output = np.zeros(values.shape[:-1] + (len(requested),), dtype=values.dtype) + for column, row in enumerate(requested): + position = positions.get(_coordinate_key(row)) + if position is not None: + output[..., column] = values[..., position] + return output + + def _gather_entries( + self, relation: Expression + ) -> tuple[tuple[str, ...], np.ndarray, np.ndarray]: + if isinstance(relation, Indexed) and isinstance(relation.base, Symbol): + indices = tuple(index.name for index in relation.indices) + table = np.asarray(self._symbol_value(relation.base)) + self._relation_from_table(relation.base.name, table, indices) + return indices, table.astype(np.intp, copy=False), np.ones(len(table)) + + sparse = self._relation_tensor(relation) + if sparse.fill_value == 0: + nonzero = sparse.values != 0 + return ( + sparse.indices, + sparse.coordinates[nonzero], + sparse.values[nonzero], + ) + + coordinates = self._root_coordinates(sparse.indices) + values = self._sparse_lookup(sparse, coordinates) + nonzero = values != 0 + return sparse.indices, coordinates[nonzero], values[nonzero] + + def _reduction_at(self, node: Reduction, demand: _Demand) -> np.ndarray: + free = self.free_indices(node) + requested = demand.project(free) + unique, inverse = _unique_rows(requested) + local_demand = _Demand(free, unique) + if node.relation is None: + reduced = self._ordinary_reduction(node, local_demand) + else: + reduced = self._relation_reduction(node, local_demand) + return np.asarray(reduced)[..., inverse] + + def _ordinary_reduction(self, node: Reduction, demand: _Demand) -> np.ndarray: + reduced = tuple(index.name for index in node.indices) + operand_indices = self.free_indices(node.operand) + if set(reduced).isdisjoint(operand_indices): + return self._eval_at(node.operand, demand) * self.num_nodes ** len(reduced) + optimized = self._factor_reduction(node, demand, reduced) + if optimized is not None: + return optimized + return self._enumerated_sum(node.operand, demand, reduced) + + def _factor_reduction( + self, node: Reduction, demand: _Demand, reduced: tuple[str, ...] + ) -> np.ndarray | None: + operand = node.operand + if not isinstance(operand, Binary) or operand.operator not in {"+", "-", "*"}: + return None + left_indices = set(self.free_indices(operand.left)) + right_indices = set(self.free_indices(operand.right)) + reduced_set = set(reduced) + if operand.operator in {"+", "-"}: + left = self._reduction_at( + Reduction(tuple(Index(name) for name in reduced), operand.left), demand + ) + right = self._reduction_at( + Reduction(tuple(Index(name) for name in reduced), operand.right), demand + ) + return _binary(operand.operator, left, right) + if left_indices.isdisjoint(reduced_set): + factor = self._eval_at(operand.left, demand) + total = self._reduction_at( + Reduction(tuple(Index(name) for name in reduced), operand.right), demand + ) + return factor * total + if right_indices.isdisjoint(reduced_set): + factor = self._eval_at(operand.right, demand) + total = self._reduction_at( + Reduction(tuple(Index(name) for name in reduced), operand.left), demand + ) + return factor * total + return None + + def _relation_reduction(self, node: Reduction, demand: _Demand) -> np.ndarray: + relation = self._relation_tensor(node.relation) + reduced = tuple(index.name for index in node.indices) + operand_indices = self.free_indices(node.operand) + output_shape: tuple[int, ...] | None = None + result: np.ndarray | None = None + + if relation.fill_value != 0: + baseline = self._enumerated_sum( + node.operand, + demand, + reduced, + ) + result = relation.fill_value * baseline + output_shape = np.shape(result) + + correction = self._sparse_correction( + node.operand, + demand, + reduced, + operand_indices, + relation, + ) + if result is None: + result = correction + else: + result = result + correction + if output_shape is not None and np.shape(result) != output_shape: + result = np.broadcast_to(result, output_shape) + return result + + def _enumerated_sum( + self, + operand: Expression, + demand: _Demand, + reduced: tuple[str, ...], + ) -> np.ndarray: + dependent = tuple( + index for index in self.free_indices(operand) if index not in reduced + ) + requested = demand.project(dependent) + unique, inverse = _unique_rows(requested) + local_demand = _Demand(dependent, unique) + output_count = len(unique) + combinations = np.asarray( + list(product(range(self.num_nodes), repeat=len(reduced))), dtype=np.intp + ) + if not len(combinations): + combinations = np.empty((1, 0), dtype=np.intp) + rows: list[list[int]] = [] + full_indices = _ordered_union(local_demand.indices, reduced) + for output in local_demand.coordinates: + fixed = dict(zip(local_demand.indices, output)) + for combination in combinations: + bindings = fixed | dict(zip(reduced, combination)) + rows.append([bindings[index] for index in full_indices]) + values = self._eval_at(operand, _Demand(full_indices, np.asarray(rows, dtype=np.intp))) + values = np.asarray(values) + count = len(combinations) + result = values.reshape(values.shape[:-1] + (output_count, count)).sum(axis=-1) + return result[..., inverse] + + def _sparse_correction( + self, + operand: Expression, + demand: _Demand, + reduced: tuple[str, ...], + operand_indices: tuple[str, ...], + relation: _SparseTensor, + ) -> np.ndarray: + free_relation = tuple(index for index in relation.indices if index not in reduced) + extra_reduced = tuple(index for index in reduced if index not in relation.indices) + extra_combinations = list(product(range(self.num_nodes), repeat=len(extra_reduced))) or [()] + rows: list[list[int]] = [] + weights: list[float] = [] + groups: list[int] = [] + eval_indices = _ordered_union( + demand.indices, _ordered_union(relation.indices, extra_reduced) + ) + relation_positions = [relation.indices.index(index) for index in free_relation] + grouped_entries: dict[tuple[int, ...], list[tuple[np.ndarray, float]]] = {} + for relation_row, stored in zip(relation.coordinates, relation.values): + key = tuple(int(relation_row[position]) for position in relation_positions) + grouped_entries.setdefault(key, []).append((relation_row, float(stored))) + + for group, output in enumerate(demand.coordinates): + fixed = dict(zip(demand.indices, output)) + key = tuple(int(fixed[index]) for index in free_relation) + for relation_row, stored in grouped_entries.get(key, ()): + binding = dict(zip(relation.indices, relation_row)) + for extra in extra_combinations: + merged = fixed | binding | dict(zip(extra_reduced, extra)) + rows.append([merged[index] for index in eval_indices]) + weights.append(float(stored - relation.fill_value)) + groups.append(group) + + if not rows: + return np.zeros((len(demand.coordinates),), dtype=float) + values = np.asarray( + self._eval_at(operand, _Demand(eval_indices, np.asarray(rows, dtype=np.intp))) + ) + weighted = values * np.asarray(weights) + result = np.zeros( + values.shape[:-1] + (len(demand.coordinates),), + dtype=np.result_type(weighted, float), + ) + np.add.at(result, (..., np.asarray(groups, dtype=np.intp)), weighted) + return result + + def _relation_tensor(self, node: Expression) -> _SparseTensor: + cached = self._relation_cache.get(id(node)) + if cached is not None: + return cached + result = self._compile_relation(node) + self._relation_cache[id(node)] = result + return result + + def _compile_relation( + self, node: Expression, indices: tuple[str, ...] | None = None + ) -> _SparseTensor: + if isinstance(node, Indexed) and isinstance(node.base, Symbol): + names = tuple(index.name for index in node.indices) + value = np.asarray(self._symbol_value(node.base)) + return self._relation_from_table(node.base.name, value, names) + if isinstance(node, Number): + if indices is None: + return _SparseTensor( + (), np.empty((0, 0), dtype=np.intp), np.empty(0), + float(node.value), self.num_nodes, + ) + return _SparseTensor( + indices, + np.empty((0, len(indices)), dtype=np.intp), + np.empty(0), + float(node.value), + self.num_nodes, + ) + if isinstance(node, Parameter): + value = float(self._parameter_value(node)) + return _SparseTensor( + indices or (), + np.empty((0, len(indices or ())), dtype=np.intp), + np.empty(0), + value, + self.num_nodes, + ) + if isinstance(node, Unary): + operand = self._compile_relation(node.operand, indices) + return _SparseTensor( + operand.indices, operand.coordinates, -operand.values, + -operand.fill_value, operand.num_nodes, + ) + if isinstance(node, Function): + if len(node.arguments) != 1: + raise ValueError("Relation functions must be unary.") + operand = self._compile_relation(node.arguments[0], indices) + function = self._numpy_function(node.name) + with np.errstate(all="ignore"): + return _SparseTensor( + operand.indices, + operand.coordinates, + np.asarray(function(operand.values), dtype=float), + float(function(operand.fill_value)), + operand.num_nodes, + ) + if isinstance(node, Binary): + left = self._compile_relation(node.left, indices) + right = self._compile_relation(node.right, left.indices or indices) + if not left.indices: + left = _constant_sparse(left.fill_value, right.indices, self.num_nodes) + if not right.indices: + right = _constant_sparse(right.fill_value, left.indices, self.num_nodes) + if set(left.indices) != set(right.indices): + raise ValueError("Relation operands must use the same structural indices.") + right = _reorder_sparse(right, left.indices) + return _combine_sparse(left, right, node.operator) + raise ValueError( + "The first argument of an indexed sum must be an indexed relation " + "or algebra over indexed relations." + ) + + def _relation_from_table( + self, name: str, value: np.ndarray, indices: tuple[str, ...] + ) -> _SparseTensor: + if not self._is_relation_table(value, len(indices)): + raise ValueError( + f"Relation {name!r} must be an integer coordinate table shaped " + f"(entries, {len(indices)})." + ) + table = value.astype(np.intp, copy=False) + if np.any(table < 0) or np.any(table >= self.num_nodes): + raise ValueError( + f"Relation {name!r} contains an endpoint outside [0, {self.num_nodes})." + ) + coordinates = np.unique(table, axis=0) + return _SparseTensor( + indices, coordinates, np.ones(len(coordinates)), 0.0, self.num_nodes + ) + + def _sparse_lookup(self, sparse: _SparseTensor, requested: np.ndarray) -> np.ndarray: + entries = { + _coordinate_key(row): value + for row, value in zip(sparse.coordinates, sparse.values) + } + return np.asarray( + [entries.get(_coordinate_key(row), sparse.fill_value) for row in requested], + dtype=float, + ) + + def _infer_relation(self, field_name: str, value: np.ndarray, arity: int) -> str: + candidates = [] + for name, raw in self.values.items(): + raw = raw.values if isinstance(raw, RelationField) else raw + array = np.asarray(raw) + if ( + self._is_relation_table(array, arity) + and value.ndim + and value.shape[-1] == len(array) + ): + candidates.append(name) + if len(candidates) != 1: + raise ValueError( + f"Cannot infer the relation for field {field_name!r}; wrap it in " + "RelationField(values, relation='A')." + ) + return candidates[0] + + def _relation_table(self, name: str, arity: int) -> np.ndarray: + if name not in self.values: + raise KeyError(f"No value was provided for relation {name!r}.") + value = self.values[name] + value = value.values if isinstance(value, RelationField) else value + array = np.asarray(value) + if not self._is_relation_table(array, arity): + raise ValueError(f"{name!r} is not an integer relation table of arity {arity}.") + return array.astype(np.intp, copy=False) + + @staticmethod + def _is_relation_table(value: np.ndarray, arity: int) -> bool: + return ( + value.ndim == 2 + and value.shape[1] == arity + and arity >= 2 + and value.dtype.kind in "iu" + ) + + def _symbol_value(self, node: Symbol) -> Any: + if node.name in self.values: + return self.values[node.name] + if node.value is not None: + return node.value + raise KeyError(f"No value was provided for symbol {node.name!r}.") + + def _parameter_value(self, node: Parameter) -> Any: + value = self.parameters.get(node.name, self.parameter_defaults.get(node.name)) + if value is None: + raise ValueError(f"Parameter {node.name!r} has no value. Fit it or provide it.") + return value + + def _function(self, name: str, arguments: list[np.ndarray]) -> np.ndarray: + if name == "delay": + return self._delay(arguments[0], arguments[1]) + with np.errstate(all="ignore"): + return self._numpy_function(name)(*arguments) + + @staticmethod + def _numpy_function(name: str) -> Callable[..., Any]: + functions = { + "abs": np.abs, "arccos": np.arccos, "arcsin": np.arcsin, + "arctan": np.arctan, "cos": np.cos, "cosh": np.cosh, + "cot": lambda value: 1.0 / np.tan(value), + "csc": lambda value: 1.0 / np.sin(value), "exp": np.exp, + "inv": lambda value: 1.0 / value, "log": np.log, + "log10": np.log10, "log2": np.log2, + "max": np.maximum, "min": np.minimum, + "pow2": lambda value: value**2, "pow3": lambda value: value**3, + "sec": lambda value: 1.0 / np.cos(value), + "sech": lambda value: 1.0 / np.cosh(value), "sin": np.sin, + "sinh": np.sinh, "sign": np.sign, "sqrt": np.sqrt, + "tan": np.tan, "tanh": np.tanh, + "sigmoid": lambda value: 1.0 / (1.0 + np.exp(-value)), + } + return functions[name] + + def _delay(self, value: Any, lag: Any) -> np.ndarray: + value = np.asarray(value, dtype=float) + lag = np.asarray(lag, dtype=float) + if self.delay_resolver is not None: + return np.asarray(self.delay_resolver(value, lag, self.time)) + if value.ndim == 0: + return value + time = np.arange(value.shape[0], dtype=float) if self.time is None else self.time + if time.shape != (value.shape[0],): + raise ValueError("time must match the leading data axis.") + query = np.broadcast_to(time - lag, (value.shape[0],)) + flat = value.reshape(value.shape[0], -1) + delayed = np.column_stack([ + np.interp(query, time, column, left=np.nan, right=np.nan) for column in flat.T + ]) + return delayed.reshape(value.shape) + + def _validate_scopes(self, expression: Expression) -> None: + def visit(node: Expression, bound: frozenset[str]) -> None: + if isinstance(node, Reduction): + names = tuple(index.name for index in node.indices) + if len(set(names)) != len(names): + raise ValueError(f"A sum cannot bind an index more than once: {names}.") + reused = bound.intersection(names) + if reused: + raise ValueError( + "Nested sums cannot bind an index that is already active; " + f"rename {sorted(reused)!r}." + ) + if node.relation is not None: + visit(node.relation, bound) + visit(node.operand, bound.union(names)) + return + for child in children(node): + visit(child, bound) + + visit(expression, frozenset()) + + def _validate_bare_symbols(self, expression: Expression) -> None: + def visit(node: Expression, allow_relation_field: bool) -> None: + if isinstance(node, Symbol): + value = self._symbol_value(node) + value = value.values if isinstance(value, RelationField) else value + array = np.asarray(value) + if array.ndim and array.shape[-1] != 1 and not allow_relation_field: + raise ValueError( + f"Symbol {node.name!r} must be indexed because this expression " + "uses structural indices." + ) + return + if isinstance(node, Indexed): + if isinstance(node.base, Symbol): + return + visit(node.base, self.relation_domain(node.base) is not None) + return + if isinstance(node, Gather): + visit(node.relation, False) + visit(node.operand, False) + return + carries_relation = self.relation_domain(node) is not None + for child in children(node): + visit(child, allow_relation_field or carries_relation) + + visit(expression, self.relation_domain(expression) is not None) + + +def _ordered_union(left: tuple[str, ...], right: tuple[str, ...]) -> tuple[str, ...]: + return left + tuple(item for item in right if item not in left) + + +def _binary(operator: str, left: Any, right: Any) -> np.ndarray: + return {"+": np.add, "-": np.subtract, "*": np.multiply, "/": np.divide, "**": np.power}[ + operator + ](left, right) + + +def _unique_rows(rows: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + if rows.shape[1] == 0: + return rows[:1], np.zeros(len(rows), dtype=np.intp) + return np.unique(rows, axis=0, return_inverse=True) + + +def _coordinate_key(row: np.ndarray) -> tuple[int, ...]: + return tuple(int(value) for value in row) + + +def _constant_sparse( + value: float, indices: tuple[str, ...], num_nodes: int +) -> _SparseTensor: + return _SparseTensor( + indices, np.empty((0, len(indices)), dtype=np.intp), + np.empty(0), value, num_nodes, + ) + + +def _reorder_sparse(tensor: _SparseTensor, indices: tuple[str, ...]) -> _SparseTensor: + if tensor.indices == indices: + return tensor + columns = [tensor.indices.index(index) for index in indices] + return _SparseTensor( + indices, tensor.coordinates[:, columns], tensor.values, + tensor.fill_value, tensor.num_nodes, + ) + + +def _combine_sparse(left: _SparseTensor, right: _SparseTensor, operator: str) -> _SparseTensor: + function = {"+": np.add, "-": np.subtract, "*": np.multiply, "/": np.divide, "**": np.power}[ + operator + ] + with np.errstate(all="ignore"): + fill = float(function(left.fill_value, right.fill_value)) + left_values = {_coordinate_key(row): value for row, value in zip(left.coordinates, left.values)} + right_values = { + _coordinate_key(row): value + for row, value in zip(right.coordinates, right.values) + } + keys = sorted(set(left_values).union(right_values)) + coordinates = [] + values = [] + for key in keys: + with np.errstate(all="ignore"): + value = float( + function( + left_values.get(key, left.fill_value), + right_values.get(key, right.fill_value), + ) + ) + if not np.isclose(value, fill, equal_nan=True): + coordinates.append(key) + values.append(value) + return _SparseTensor( + left.indices, + np.asarray(coordinates, dtype=np.intp).reshape(-1, len(left.indices)), + np.asarray(values, dtype=float), + fill, + left.num_nodes, + ) + + +def _unique(values: np.ndarray) -> list[Any]: + result = [] + for value in values.reshape(-1): + value = value.item() if isinstance(value, np.generic) else value + if value not in result: + result.append(value) + return result + + +def _grouped_parameter_key(node: GroupedParameter) -> str: + if node.name: + return node.name + if isinstance(node.by, Symbol): + return f"grouped:{node.by.name}" + return f"grouped:{node.by}" diff --git a/src/sr_harness_engine/optimize.py b/src/sr_harness_engine/optimize.py new file mode 100644 index 0000000000000000000000000000000000000000..4edc4c927a96c186532e9e9e2b6c5e67cddf31c4 --- /dev/null +++ b/src/sr_harness_engine/optimize.py @@ -0,0 +1,185 @@ +"""Parameter optimization for symbolic expressions.""" + +from __future__ import annotations + +from dataclasses import dataclass, replace +from typing import Any, Mapping + +import numpy as np +from scipy.optimize import minimize + +from .evaluation import grouped_parameter_key, walk +from .expression import Expression, GroupedParameter, Parameter + + +def bind_parameters(expression: Expression, parameters: Mapping[str, Any]) -> Expression: + """Return an expression whose parameter nodes contain fitted values.""" + from .tree import transform + + def bind(node: Expression) -> Expression: + if isinstance(node, Parameter) and node.name in parameters: + return replace(node, value=float(parameters[node.name])) + if isinstance(node, GroupedParameter): + key = grouped_parameter_key(node) + if key in parameters: + return replace(node, value=dict(parameters[key])) + return node + + return transform(expression, bind) + + +@dataclass(frozen=True, slots=True) +class FitResult: + """Result of fitting an expression to target observations.""" + expression: Expression + parameters: dict[str, Any] + loss: float + success: bool + message: str + n_iter: int + + def evaluate( + self, values: Mapping[str, Any], *, time: Any = None, + delay_resolver: Any = None, num_nodes: int | None = None, + ) -> Any: + """Evaluate the supplied model or expression. + + Args: + values: Values keyed by symbol name or an evaluation context. + time: Optional sample times. + delay_resolver: Optional callback that resolves delayed values. + num_nodes: Explicit node count for indexed expressions. + + Returns: + Predictions from the fitted expression. + """ + return self.expression.evaluate( + values, parameters=self.parameters, time=time, + delay_resolver=delay_resolver, num_nodes=num_nodes, + ) + + predict = evaluate + + +def fit( + expression: Expression, + values: Mapping[str, Any], + target: Any, + *, + initial: Mapping[str, Any] | None = None, + method: str = "BFGS", + options: Mapping[str, Any] | None = None, + time: Any = None, + delay_resolver: Any = None, + num_nodes: int | None = None, +) -> FitResult: + """Minimize mean squared error and return fitted parameter values. + + Args: + expression: Symbolic expression to process. + values: Values keyed by symbol name. + target: Target name or target values. + initial: Optional initial parameter values. + method: Optimization method name. + options: Optional optimizer settings. + time: Optional sample times used by delayed expressions. + delay_resolver: Optional callback that resolves delayed values. + num_nodes: Explicit node count for indexed expressions. + + Returns: + Fitted parameters, expression, predictions, and loss. + """ + initial = dict(initial or {}) + target = np.asarray(target, dtype=float) + specs: list[tuple[str, Any | None]] = [] + named: dict[str, float | None] = {} + grouped: dict[str, tuple[GroupedParameter, list[Any]]] = {} + + for node in walk(expression): + if isinstance(node, Parameter): + previous = named.get(node.name) + if previous is not None and node.value is not None and previous != node.value: + raise ValueError(f"Conflicting initial values for parameter {node.name!r}.") + if node.name not in named or node.value is not None: + named[node.name] = node.value + elif isinstance(node, GroupedParameter): + key = grouped_parameter_key(node) + labels = np.asarray(node.by.evaluate(values), dtype=object).reshape(-1) + unique = [] + for label in labels: + label = label.item() if isinstance(label, np.generic) else label + if label not in unique: + unique.append(label) + grouped.setdefault(key, (node, unique)) + + vector = [] + for name, default in named.items(): + value = initial.get(name, default if default is not None else 1.0) + vector.append(float(value)) + specs.append((name, None)) + for key, (node, labels) in grouped.items(): + supplied = initial.get(key, node.value or {}) + if not isinstance(supplied, Mapping): + raise TypeError(f"Initial value for grouped parameter {key!r} must be a mapping.") + for label in labels: + default = node.default if node.default is not None else 1.0 + vector.append(float(supplied.get(label, default))) + specs.append((key, label)) + + if not specs: + prediction = np.asarray( + expression.evaluate( + values, time=time, delay_resolver=delay_resolver, num_nodes=num_nodes, + ), + dtype=float, + ) + finite = np.isfinite(prediction) & np.isfinite(target) + loss = float(np.mean((prediction[finite] - target[finite]) ** 2)) if np.any(finite) else float("inf") + return FitResult(expression, {}, loss, True, "No parameters to optimize.", 0) + + def unpack(raw: np.ndarray) -> dict[str, Any]: + parameters: dict[str, Any] = {} + for value, (name, label) in zip(raw, specs): + if label is None: + parameters[name] = float(value) + else: + parameters.setdefault(name, {})[label] = float(value) + return parameters + + def objective(raw: np.ndarray) -> float: + try: + prediction = np.asarray( + expression.evaluate( + values, + parameters=unpack(raw), + time=time, + delay_resolver=delay_resolver, + num_nodes=num_nodes, + ), + dtype=float, + ) + if prediction.shape != target.shape: + prediction = np.broadcast_to(prediction, target.shape) + finite = np.isfinite(prediction) & np.isfinite(target) + if not np.any(finite): + return 1e100 + loss = np.mean((prediction[finite] - target[finite]) ** 2) + return float(loss) if np.isfinite(loss) else 1e100 + except (FloatingPointError, OverflowError, ValueError): + return 1e100 + + result = minimize( + objective, + np.asarray(vector, dtype=float), + method=method, + options=dict(options or {}), + ) + parameters = unpack(result.x) + return FitResult( + expression=bind_parameters(expression, parameters), + parameters=parameters, + loss=float(result.fun), + success=bool(result.success), + message=str(result.message), + n_iter=int(getattr(result, "nit", 0)), + ) diff --git a/src/sr_harness_engine/parser.py b/src/sr_harness_engine/parser.py new file mode 100644 index 0000000000000000000000000000000000000000..090e88082dc136043ccce95e3a2b1e597fcec145 --- /dev/null +++ b/src/sr_harness_engine/parser.py @@ -0,0 +1,289 @@ +"""Safe parser for the SRHarness symbolic model language.""" + +from __future__ import annotations + +import ast +from collections.abc import Mapping +from typing import Any + +from .analysis import fold_constants +from .desugar import desugar +from .expression import ( + Aggregate, + Binary, + Expression, + Function, + Gather, + GroupedParameter, + Index, + Indexed, + Number, + Parameter, + Reduction, + RelationLift, + Symbol, + Unary, +) + + +FUNCTIONS = { + "abs", "arccos", "arcsin", "arctan", "cos", "cosh", "cot", "csc", "exp", "inv", + "log", "log10", "log2", "sec", "sech", "sigmoid", "sign", "sin", "sinh", "sqrt", "tan", + "tanh", "pow2", "pow3", +} +FUNCTION_ALIASES = { + "acos": "arccos", + "asin": "arcsin", + "atan": "arctan", + "lg": "log10", + "ln": "log", +} +BINARY_FUNCTIONS = {"max", "min"} + + +class ExpressionParser(ast.NodeVisitor): + """Convert a restricted Python expression AST into engine nodes.""" + + def __init__(self, symbols: Mapping[str, Any] | None = None): + self.symbols = {} + for name, value in (symbols or {}).items(): + if isinstance(value, Expression): + self.symbols[name] = value + elif isinstance(value, bool) or not isinstance(value, (int, float)): + raise TypeError(f"Symbol override {name!r} must be an expression or number.") + else: + self.symbols[name] = Number(value) + + def parse(self, source: str) -> Expression: + """Parse input into the canonical representation. + + Args: + source: Source text to parse. + + Returns: + The parsed, desugared, and constant-folded expression. + """ + try: + tree = ast.parse(source, mode="eval") + except SyntaxError as error: + raise SyntaxError(f"Invalid symbolic expression: {error.msg}.") from error + return fold_constants(desugar(self.visit(tree.body))) + + def generic_visit(self, node: ast.AST): + """Reject syntax that is outside the symbolic language. + + Args: + node: Expression or syntax-tree node. + """ + raise ValueError(f"Unsupported syntax: {type(node).__name__}.") + + def visit_Constant(self, node: ast.Constant) -> Expression: + """Convert a numeric literal into a number node. + + Args: + node: Expression or syntax-tree node. + + Returns: + A numeric expression node. + """ + if isinstance(node.value, bool) or not isinstance(node.value, (int, float)): + raise ValueError(f"Only numerical literals are expressions, got {node.value!r}.") + return Number(node.value) + + def visit_Name(self, node: ast.Name) -> Expression: + """Resolve a name to a supplied or newly created symbol. + + Args: + node: Expression or syntax-tree node. + + Returns: + The expression associated with the name. + """ + return self.symbols.setdefault(node.id, Symbol(node.id)) + + def visit_UnaryOp(self, node: ast.UnaryOp) -> Expression: + """Convert a supported unary operator. + + Args: + node: Expression or syntax-tree node. + + Returns: + The converted operand or unary expression. + """ + if isinstance(node.op, ast.USub): + return Unary("-", self.visit(node.operand)) + if isinstance(node.op, ast.UAdd): + return self.visit(node.operand) + raise ValueError(f"Unsupported unary operator: {type(node.op).__name__}.") + + def visit_BinOp(self, node: ast.BinOp) -> Expression: + """Convert a supported binary arithmetic operator. + + Args: + node: Expression or syntax-tree node. + + Returns: + A binary expression node. + """ + operators = { + ast.Add: "+", ast.Sub: "-", ast.Mult: "*", ast.Div: "/", ast.Pow: "**" + } + operator = operators.get(type(node.op)) + if operator is None: + raise ValueError(f"Unsupported binary operator: {type(node.op).__name__}.") + return Binary(operator, self.visit(node.left), self.visit(node.right)) + + def visit_Subscript(self, node: ast.Subscript) -> Expression: + """Convert symbolic indexing such as ``x[i]``. + + Args: + node: Expression or syntax-tree node. + + Returns: + An indexed expression node. + """ + base = self.visit(node.value) + return Indexed(base, self._indices(node.slice)) + + def visit_Call(self, node: ast.Call) -> Expression: + """Convert an approved symbolic function or reduction call. + + Args: + node: Expression or syntax-tree node. + + Returns: + The corresponding symbolic expression. + """ + if isinstance(node.func, ast.Subscript) and self._name(node.func.value) == "sum": + if node.keywords or len(node.args) not in {1, 2}: + raise ValueError( + "sum[index](...) expects an operand, optionally preceded by a relation." + ) + arguments = [self.visit(argument) for argument in node.args] + relation, operand = (None, arguments[0]) if len(arguments) == 1 else arguments + return Reduction(self._indices(node.func.slice), operand, relation) + + source_name = self._name(node.func) + name = FUNCTION_ALIASES.get(source_name, source_name) + if name in FUNCTIONS: + if node.keywords or len(node.args) != 1: + raise ValueError(f"{source_name}(...) expects exactly one positional argument.") + return Function(name, (self.visit(node.args[0]),)) + if name in BINARY_FUNCTIONS: + if node.keywords or len(node.args) != 2: + raise ValueError(f"{name}(...) expects exactly two positional arguments.") + return Function(name, tuple(self.visit(argument) for argument in node.args)) + if name == "delay": + if node.keywords or len(node.args) != 2: + raise ValueError("delay(value, delta) expects exactly two arguments.") + return Function(name, tuple(self.visit(argument) for argument in node.args)) + if name == "gather": + if node.keywords or len(node.args) != 2: + raise ValueError("gather(relation, expression) expects exactly two arguments.") + return Gather(self.visit(node.args[0]), self.visit(node.args[1])) + if name == "Number": + if node.keywords or len(node.args) != 1: + raise ValueError("Number(...) expects exactly one numerical literal.") + return self.visit(node.args[0]) + if name == "param": + return self._parameter(node) + if name == "grouped_param": + return self._grouped_parameter(node) + if name == "aggr": + if node.keywords or len(node.args) not in {1, 2}: + raise ValueError( + "aggr expects aggr(relation * expression) or " + "aggr(relation, expression)." + ) + if len(node.args) == 2: + return Aggregate(self.visit(node.args[0]), self.visit(node.args[1])) + relation, operand = _split_aggregation(self.visit(node.args[0])) + return Aggregate(relation, operand) + if name in {"targ", "sour"}: + if node.keywords or len(node.args) not in {1, 2}: + raise ValueError(f"{name} expects one value, optionally preceded by a relation.") + arguments = [self.visit(argument) for argument in node.args] + relation, operand = (None, arguments[0]) if len(arguments) == 1 else arguments + return RelationLift("target" if name == "targ" else "source", operand, relation) + raise ValueError(f"Unknown symbolic function: {name!r}.") + + def _parameter(self, node: ast.Call) -> Parameter: + if len(node.args) != 1 or not isinstance(node.args[0], ast.Constant): + raise ValueError("param(...) requires a literal string name.") + name = node.args[0].value + if not isinstance(name, str) or not name: + raise ValueError("Parameter names must be non-empty strings.") + keywords = self._literal_keywords(node, {"value"}) + value = keywords.get("value") + if value is not None and (isinstance(value, bool) or not isinstance(value, (int, float))): + raise ValueError("A parameter initial value must be numerical.") + return Parameter(name, value) + + def _grouped_parameter(self, node: ast.Call) -> GroupedParameter: + if len(node.args) != 1: + raise ValueError("grouped_param(...) requires one grouping expression.") + keywords = self._literal_keywords(node, {"name", "value", "default"}) + name = keywords.get("name") + if name is not None and (not isinstance(name, str) or not name): + raise ValueError("A grouped parameter name must be a non-empty string.") + value = keywords.get("value") + if value is not None and not isinstance(value, dict): + raise ValueError("grouped_param value must be a category-to-number dictionary.") + default = keywords.get("default") + return GroupedParameter(self.visit(node.args[0]), name=name, value=value, default=default) + + @staticmethod + def _name(node: ast.AST) -> str: + if not isinstance(node, ast.Name): + raise ValueError("Only direct symbolic function calls are allowed.") + return node.id + + @staticmethod + def _indices(node: ast.AST) -> tuple[Index, ...]: + nodes = node.elts if isinstance(node, ast.Tuple) else (node,) + if not nodes or not all(isinstance(item, ast.Name) for item in nodes): + raise ValueError("Indices must be identifiers such as i, j, or k.") + return tuple(Index(item.id) for item in nodes) + + @staticmethod + def _literal_keywords(node: ast.Call, allowed: set[str]) -> dict[str, Any]: + result = {} + for keyword in node.keywords: + if keyword.arg not in allowed: + raise ValueError(f"Unexpected keyword argument: {keyword.arg!r}.") + result[keyword.arg] = ast.literal_eval(keyword.value) + return result + + +def parse( + source: str, + symbols: Mapping[str, Any] | None = None, +) -> Expression: + """Parse *source* without using ``eval`` or executing user code. + + Args: + source: Source text to parse. + symbols: Optional predefined symbols or numeric constants. + + Returns: + The parsed canonical expression. + """ + return ExpressionParser(symbols).parse(source) + + +def _split_aggregation(expression: Expression) -> tuple[Expression, Expression]: + factors = _multiplication_factors(expression) + if len(factors) < 2 or not isinstance(factors[0], Symbol): + raise ValueError( + "aggr(relation * expression) requires the relation symbol as its first factor." + ) + operand = factors[1] + for factor in factors[2:]: + operand = Binary("*", operand, factor) + return factors[0], operand + + +def _multiplication_factors(expression: Expression) -> list[Expression]: + if isinstance(expression, Binary) and expression.operator == "*": + return _multiplication_factors(expression.left) + _multiplication_factors(expression.right) + return [expression] diff --git a/src/sr_harness_engine/render.py b/src/sr_harness_engine/render.py new file mode 100644 index 0000000000000000000000000000000000000000..995f9c3a0f80a0a110acaf0c44a5df93f32831bf --- /dev/null +++ b/src/sr_harness_engine/render.py @@ -0,0 +1,140 @@ +"""Canonical string renderer for symbolic expressions.""" + +from __future__ import annotations + +from .expression import ( + Aggregate, + Binary, + Expression, + Function, + Gather, + GroupedParameter, + Indexed, + Number, + Parameter, + Reduction, + RelationLift, + Symbol, + Unary, +) + + +PRECEDENCE = {"+": 10, "-": 10, "*": 20, "/": 20, "**": 30} + + +def render( + expression: Expression, + parent_precedence: int = 0, + right: bool = False, + *, + latex: bool = False, + number_format: str = "", +) -> str: + """Render an expression as canonical text. + + Args: + expression: Symbolic expression to process. + parent_precedence: Precedence required by the enclosing expression. + right: Whether the expression is the right operand of its parent. + latex: Whether to render LaTeX notation. + number_format: Format specification for numeric literals. + + Returns: + The rendered expression. + """ + if isinstance(expression, Number): + return format(expression.value, number_format) if number_format else repr(expression.value) + if isinstance(expression, Symbol): + return expression.name + if isinstance(expression, Parameter): + suffix = "" if expression.value is None else f", value={expression.value!r}" + return f"param({expression.name!r}{suffix})" + if isinstance(expression, GroupedParameter): + arguments = [render(expression.by)] + if expression.name is not None: + arguments.append(f"name={expression.name!r}") + if expression.value is not None: + arguments.append(f"value={dict(expression.value)!r}") + if expression.default is not None: + arguments.append(f"default={expression.default!r}") + return f"grouped_param({', '.join(arguments)})" + if isinstance(expression, Indexed): + indices = ", ".join(str(index) for index in expression.indices) + base = render(expression.base, 100, latex=latex, number_format=number_format) + return f"{base}[{indices}]" + if isinstance(expression, Unary): + operand = render(expression.operand, 40, latex=latex, number_format=number_format) + text = f"{expression.operator}{operand}" + return f"({text})" if parent_precedence > 40 else text + if isinstance(expression, Binary): + precedence = PRECEDENCE[expression.operator] + left = render(expression.left, precedence, latex=latex, number_format=number_format) + right_precedence = precedence + (0 if expression.operator == "**" else 1) + right_text = render( + expression.right, + right_precedence, + right=True, + latex=latex, + number_format=number_format, + ) + if latex and expression.operator == "/": + text = f"\\frac{{{left}}}{{{right_text}}}" + elif latex and expression.operator == "**": + text = f"{left}^{{{right_text}}}" + else: + operator = ( + r" \times " + if latex and expression.operator == "*" + else f" {expression.operator} " + ) + text = f"{left}{operator}{right_text}" + return f"({text})" if precedence < parent_precedence else text + if isinstance(expression, Function): + arguments = ", ".join( + render(arg, latex=latex, number_format=number_format) + for arg in expression.arguments + ) + if latex and expression.name == "sqrt": + return f"\\sqrt{{{arguments}}}" + if latex and expression.name == "abs": + return f"\\left|{arguments}\\right|" + if latex: + function_name = { + "arccos": r"\arccos", + "arcsin": r"\arcsin", + "arctan": r"\arctan", + "log": r"\ln", + "log10": r"\log_{10}", + "log2": r"\log_{2}", + }.get(expression.name, rf"\operatorname{{{expression.name}}}") + return f"{function_name}\\left({arguments}\\right)" + return f"{expression.name}({arguments})" + if isinstance(expression, Reduction): + indices = ", ".join(str(index) for index in expression.indices) + operand = render(expression.operand, latex=latex, number_format=number_format) + if expression.relation is None: + return f"\\sum_{{{indices}}} {operand}" if latex else f"sum[{indices}]({operand})" + relation = render(expression.relation, latex=latex, number_format=number_format) + if latex: + return f"\\sum_{{{indices}; {relation}}} {operand}" + return f"sum[{indices}]({relation}, {operand})" + if isinstance(expression, Gather): + relation = render(expression.relation, latex=latex, number_format=number_format) + operand = render(expression.operand, latex=latex, number_format=number_format) + if latex: + return f"\\operatorname{{gather}}\\left({relation}, {operand}\\right)" + return f"gather({relation}, {operand})" + if isinstance(expression, Aggregate): + from .desugar import desugar + + return render( + desugar(expression), + parent_precedence, + right, + latex=latex, + number_format=number_format, + ) + if isinstance(expression, RelationLift): + name = "targ" if expression.role == "target" else "sour" + raise ValueError(f"{name}(...) must appear inside aggr(...).") + raise TypeError(f"Cannot render {type(expression).__name__}.") diff --git a/src/sr_harness_engine/tree.py b/src/sr_harness_engine/tree.py new file mode 100644 index 0000000000000000000000000000000000000000..ec9d589cbeb4a9302d0f46fa7c840aeb25ebd38b --- /dev/null +++ b/src/sr_harness_engine/tree.py @@ -0,0 +1,162 @@ +"""Immutable expression-tree traversal and transformation helpers.""" + +from __future__ import annotations + +from dataclasses import replace as dataclass_replace + +from .expression import ( + Aggregate, + Binary, + Expression, + Function, + Gather, + GroupedParameter, + Indexed, + Reduction, + RelationLift, + Unary, +) + + +def children(node: Expression) -> tuple[Expression, ...]: + """Return the direct child expressions of a node. + + Args: + node: Expression or syntax-tree node. + + Returns: + The node's direct children in structural order. + """ + if isinstance(node, Unary): + return (node.operand,) + if isinstance(node, Binary): + return (node.left, node.right) + if isinstance(node, Function): + return node.arguments + if isinstance(node, Indexed): + return (node.base,) + if isinstance(node, Reduction): + return (node.operand,) if node.relation is None else (node.relation, node.operand) + if isinstance(node, Gather): + return (node.relation, node.operand) + if isinstance(node, Aggregate): + return (node.relation, node.operand) + if isinstance(node, RelationLift): + return (node.operand,) if node.relation is None else (node.relation, node.operand) + if isinstance(node, GroupedParameter): + return (node.by,) + return () + + +def with_children(node: Expression, values: tuple[Expression, ...]) -> Expression: + """Return a copy of a node with new direct children. + + Args: + node: Expression or syntax-tree node. + values: Replacement children in structural order. + + Returns: + The rebuilt expression node. + """ + if len(values) != len(children(node)): + raise ValueError(f"Expected {len(children(node))} children, got {len(values)}.") + if isinstance(node, Unary): + return dataclass_replace(node, operand=values[0]) + if isinstance(node, Binary): + return dataclass_replace(node, left=values[0], right=values[1]) + if isinstance(node, Function): + return dataclass_replace(node, arguments=values) + if isinstance(node, Indexed): + return dataclass_replace(node, base=values[0]) + if isinstance(node, Reduction): + if node.relation is None: + return dataclass_replace(node, operand=values[0]) + return dataclass_replace(node, relation=values[0], operand=values[1]) + if isinstance(node, Gather): + return dataclass_replace(node, relation=values[0], operand=values[1]) + if isinstance(node, Aggregate): + return dataclass_replace(node, relation=values[0], operand=values[1]) + if isinstance(node, RelationLift): + if node.relation is None: + return dataclass_replace(node, operand=values[0]) + return dataclass_replace(node, relation=values[0], operand=values[1]) + if isinstance(node, GroupedParameter): + return dataclass_replace(node, by=values[0]) + return node + + +def iter_preorder(node: Expression): + """Yield an expression tree in preorder. + + Args: + node: Expression or syntax-tree node. + + Yields: + The node followed recursively by its children. + """ + yield node + for child in children(node): + yield from iter_preorder(child) + + +def iter_postorder(node: Expression): + """Yield an expression tree in postorder. + + Args: + node: Expression or syntax-tree node. + + Yields: + Descendants followed by their parent node. + """ + for child in children(node): + yield from iter_postorder(child) + yield node + + +def transform(node: Expression, function) -> Expression: + """Apply a bottom-up transformation to an expression tree. + + Args: + node: Expression or syntax-tree node. + function: Transformation callback. + + Returns: + The transformed expression tree. + """ + transformed = with_children(node, tuple(transform(child, function) for child in children(node))) + return function(transformed) + + +def replace(node: Expression, old: Expression, new: Expression) -> Expression: + """Replace a node by object identity throughout a tree. + + Args: + node: Expression or syntax-tree node. + old: Existing expression node to replace. + new: Replacement expression node. + + Returns: + The rebuilt expression tree. + """ + if node is old: + return new + return with_children(node, tuple(replace(child, old, new) for child in children(node))) + + +def replace_at_path(node: Expression, path: tuple[int, ...], new: Expression) -> Expression: + """Replace the node at a tuple of child indices. + + Args: + node: Expression or syntax-tree node. + path: Child indices from the root to the target node. + new: Replacement expression node. + + Returns: + The rebuilt expression tree. + """ + if not path: + return new + values = list(children(node)) + index = path[0] + values[index] = replace_at_path(values[index], path[1:], new) + return with_children(node, tuple(values))