yuzihan@SIM1 commited on
Commit ·
d06fa57
1
Parent(s): 9a8532b
Deploy SRHarness Docker Space
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .dockerignoreAdded+16
- DockerfileAdded+57
- LICENSEAdded+7
- README.md+122-4
- deploy/huggingface/README.mdAdded+75
- pyproject.tomlAdded+108
- src/sr_harness/README.mdAdded+109
- src/sr_harness/__init__.pyAdded+31
- src/sr_harness/_vendor/README.zh.mdAdded+13
- src/sr_harness/_vendor/__init__.pyAdded
- src/sr_harness/_vendor/llmsr_bench/__init__.pyAdded+1
- src/sr_harness/_vendor/llmsr_bench/algorithms/__init__.pyAdded+32
- src/sr_harness/_vendor/llmsr_bench/algorithms/codex/__init__.pyAdded+747
- src/sr_harness/_vendor/llmsr_bench/algorithms/codex/call_tool_template.pyAdded+63
- src/sr_harness/_vendor/llmsr_bench/algorithms/codex/readme_template.mdAdded+83
- src/sr_harness/_vendor/llmsr_bench/algorithms/codex/utils.pyAdded+41
- src/sr_harness/_vendor/llmsr_bench/algorithms/functionevolve.pyAdded+288
- src/sr_harness/_vendor/llmsr_bench/algorithms/linear.pyAdded+37
- src/sr_harness/_vendor/llmsr_bench/algorithms/my_igsr.pyAdded+419
- src/sr_harness/_vendor/llmsr_bench/algorithms/my_pysr.pyAdded+104
- src/sr_harness/_vendor/llmsr_bench/algorithms/polynomial.pyAdded+59
- src/sr_harness/_vendor/llmsr_bench/algorithms/pysr.pyAdded+105
- src/sr_harness/_vendor/llmsr_bench/algorithms/sr_harness.pyAdded+212
- src/sr_harness/_vendor/llmsr_bench/algorithms/sr_scientist.pyAdded+425
- src/sr_harness/_vendor/llmsr_bench/core.pyAdded+81
- src/sr_harness/agents/__init__.pyAdded+14
- src/sr_harness/agents/agent.pyAdded+146
- src/sr_harness/agents/data_preparation_agent.pyAdded+370
- src/sr_harness/agents/evaluator_construction_agent.pyAdded+404
- src/sr_harness/agents/sr_agent.pyAdded+1428
- src/sr_harness/agents/sr_agent_interactive.pyAdded+1087
- src/sr_harness/api/__init__.pyAdded+22
- src/sr_harness/api/base_api.pyAdded+537
- src/sr_harness/api/deepseek_api.pyAdded+128
- src/sr_harness/api/error_filter.pyAdded+42
- src/sr_harness/api/gemini_api.pyAdded+162
- src/sr_harness/api/lmstudio_api.pyAdded+214
- src/sr_harness/api/manual_api.pyAdded+97
- src/sr_harness/api/openai_api.pyAdded+528
- src/sr_harness/api/openrouter_api.pyAdded+145
- src/sr_harness/api/siliconflow_api.pyAdded+341
- src/sr_harness/api/utils.pyAdded+67
- src/sr_harness/cli/README.zh.mdAdded+5
- src/sr_harness/cli/__init__.pyAdded+78
- src/sr_harness/cli/benchmark.pyAdded+705
- src/sr_harness/cli/run.pyAdded+195
- src/sr_harness/cli/synthetic.pyAdded+369
- src/sr_harness/cli/tool.pyAdded+194
- src/sr_harness/core/__init__.pyAdded+41
- src/sr_harness/core/api.pyAdded+97
12345678910111213141516.git.gitignore.env.venvvenv__pycache__*.py[cod]*.egg-info.pytest_cache.ruff_cache.mypy_cachebuilddistdocslogstests123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657FROM python:3.12-slim-bookworm
ARG APP_UID=1000ARG 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 subprocessimport sysimport tomllibfrom 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 srharnessWORKDIR /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"]1234567Copyright (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.12345678910---title: SRHarnessemoji: 📚colorFrom: redcolorTo: indigosdk: dockerpinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128---title: SRHarnessemoji: 🔬colorFrom: bluecolorTo: greensdk: dockerapp_port: 8000pinned: falselicense: mitshort_description: Agentic symbolic regression workbench---# SRHarness: A Harness for Agentic Symbolic Regression[English](README.md) | [简体中文](README.zh.md)[](https://github.com/yuzhTHU/SRHarness)[](https://pypi.org/project/sr-harness/)[](https://hub.docker.com/r/yumeoww/sr-harness)[](https://yuzhthu.github.io/SRHarness/)[](http://sim1.fiblab.tech:30000/)[](https://arxiv.org/abs/2609.35501)[](https://github.com/yuzhTHU/SRHarness/actions/workflows/docs.yml)[](https://pypi.org/project/sr-harness/)[](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.## ResultsThe [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.## InstallationSRHarness requires Python 3.12 or newer.```bashpip 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 SpacesThe 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:```bashsr-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:```bashsr-harness run \--host 127.0.0.1 \--port 8000 \--workspace-dir ./workspaces \--save-path ./logs/webui```Then open <http://127.0.0.1:8000/>. 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 <http://sim1.fiblab.tech:30000/>.## 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}}```## LicenseSRHarness is released under the [MIT License](LICENSE).
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475# 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` tellsHugging 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 whenthe deployment uses an owner-funded model API key. Then push this repository tothe Space repository:
```bashgit remote add huggingface https://huggingface.co/spaces/OWNER/SPACE_NAMEgit push huggingface HEAD:main```
The container starts the equivalent of:
```bashsr-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**. Supportedsecret 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 unrestrictedpublic use and its cost are intentional. SRHarness lets each browser sessionconfigure its own provider key in the WebUI, but `--isolate-users` iscookie-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. Symbolicregression workloads can be CPU- and memory-intensive, so larger hardware maybe needed for concurrent users, large datasets, or expensive local fittingtools. Optional GPU-backed tools require a GPU Space and their correspondingmodel assets.
## Local smoke test
```bashdocker build -t sr-harness-space .docker run --rm -p 8000:8000 sr-harness-spacecurl --fail http://127.0.0.1:8000/health```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108[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 = 100target-version = "py312"
[tool.ruff.lint]select = ["E", "F", "W"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109# 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/ # 通用工具函数```12345678910111213141516171819202122232425262728293031from .agents.agent import Agentfrom .agents.data_preparation_agent import DataPreparationAgentfrom .agents.evaluator_construction_agent import EvaluatorConstructionAgentfrom .agents.sr_agent import SRAgentfrom .agents.sr_agent_interactive import SRAgentInteractivefrom .core import AgentContext, ToolCallfrom .evaluator import DefaultEvaluator, DelayRolloutEvaluator, GraphEvaluatorfrom .runtime import InteractionManager, SRInteractionManagerfrom . import apifrom . import toolsfrom . import utilsfrom . import parser
__all__ = [ "Agent", "AgentContext", "DataPreparationAgent", "DefaultEvaluator", "DelayRolloutEvaluator", "EvaluatorConstructionAgent", "GraphEvaluator", "InteractionManager", "SRAgent", "SRAgentInteractive", "SRInteractionManager", "ToolCall", "api", "parser", "tools", "utils",]12345678910111213本目录用于存放被 `sr_harness` 私有化的第三方源码。
具体而言,sr_harness 需要利用第三方的代码和/或工具,尽管绝大多数工具可以通过 `pip install` 等方式安装,某些代码可能:1. 不存在合理的包结构、无法通过常规方式安装;2. 需要经过适当修改或包装以适应 SRHarness 的调用;我们将这类代码作为 `sr_harness` 的内部实现细节,安装到这一目录中。
这一目录中的依赖应使用 `sr_harness._vendor` 作为唯一导入入口,例如:```pythonimport sr_harness._vendor.vendor_package```对于可以安装的第三方库,优先使用正常依赖声明和/或 `pip install`,不要将它放入这一目录。不要让同一份源码同时支持 `import vendor_package` 和 `import sr_harness._vendor.vendor_package` 两种入口,否则 Python 会把它们加载成两套模块对象,可能导致 `isinstance`、类身份比较、注册表和缓存失效。1from .core import SEDTask, SRResult, Problem1234567891011121314151617181920212223242526272829303132"""符号回归算法集合"""
import importlibfrom 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License."""Codex CLI coding-agent algorithm for llmsr_bench."""from __future__ import annotationsimport osimport reimport sysimport timeimport signalimport jsonimport shleximport shutilimport loggingimport argparseimport selectorsimport subprocessimport sr_harness_engine as engineimport numpy as npfrom typing import Anyfrom pathlib import Pathfrom datetime import datetimefrom sr_harness.tools import BaseToolfrom sr_harness.utils import tag2ansifrom ...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]) + " <initial_prompt>" _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("<WORK_DIR>", str(problem_dir.absolute())) .replace("<PROBLEM_PATH>", str(problem_path.relative_to(problem_dir))) .replace("<MANIFEST_PATH>", str(manifest_path.relative_to(problem_dir))) .replace("<RESULT_PATH>", str(result_path.relative_to(problem_dir))) .replace("<CALL_TOOL_PATH>", str(call_tool_path.relative_to(problem_dir))) .replace("<CONTEXT_PATH>", str(context_path.relative_to(problem_dir))) .replace("<README_PATH>", str(readme_path.relative_to(problem_dir))) .replace("<TIMEOUT_SECONDS>", str(args.codex_timeout_seconds)) ), encoding="utf-8")
call_tool_path.write_text(( _CALL_TOOL_TEMPLATE_PATH.read_text(encoding="utf-8") .replace("<WORK_DIR>", str(problem_dir.absolute())) .replace("<CONTEXT_PATH>", str(context_path.relative_to(problem_dir))) .replace("<TOOL_CALL_LOG_PATH>", str(tool_call_log_path.relative_to(problem_dir))) .replace("<ENABLED_TOOLS>", ','.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": "<expr>", "status": "completed", "notes": "<short note>"}
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": "<expr>", "status": "completed", "notes": "<short note>"}
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]) + " <finalize_prompt>" _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"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License."""Problem-local tool wrapper for this Codex symbolic-regression run."""from __future__ import annotationsimport osimport sysimport jsonfrom pathlib import Pathfrom sr_harness.tools import BaseToolfrom sr_harness.cli.tool import load_context, load_params, setup_parserfrom sr_harness._vendor.llmsr_bench.algorithms.codex.utils import record_tool_call
WORK_DIR = Path("<WORK_DIR>")CONTEXT_PATH = Path("<CONTEXT_PATH>")TOOL_CALL_LOG_PATH = Path("<TOOL_CALL_LOG_PATH>")ENABLED_TOOLS = "<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)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283# 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 yourworking directory to the problem directory. Use only the files and tools listedbelow.
Your current working directory: <WORK_DIR>
## Hard Limits
- Finish within <TIMEOUT_SECONDS> seconds.- Do not read, write or create files outside this directory, except temporary analysis scripts in `/tmp`.- Do not modify files other than <RESULT_PATH>.- 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 <RESULT_PATH>. 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 <RESULT_PATH>, 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 <RESULT_PATH> 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 <RESULT_PATH>, 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:
- `<PROBLEM_PATH>`: Public problem description and variable metadata.- `<MANIFEST_PATH>`: Paths and metadata for this run.- `<RESULT_PATH>`: Write your expression here (see Submission Protocol above).- `<CALL_TOOL_PATH>`: Local tool wrapper for this problem.- `<CONTEXT_PATH>`: Tool context, relied by `<CALL_TOOL_PATH>`.- `<README_PATH>`: Readme file saving this information
## Expected Workflow
1. Inspect the Problem file `<PROBLEM_PATH>`. 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 `<CALL_TOOL_PATH>` wrapper:
```bashpython <CALL_TOOL_PATH> listpython <CALL_TOOL_PATH> schema statistics_analysispython <CALL_TOOL_PATH> schema evaluate_formulapython <CALL_TOOL_PATH> schema ...```
3. Use the `<CALL_TOOL_PATH>` wrapper to call tool for analysing or searching.
```bashpython <CALL_TOOL_PATH> call statistics_analysis --params '{"variables": ["x1", "x2"]}'python <CALL_TOOL_PATH> 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 `<RESULT_PATH>`. Preserve the existing fields and fill at least:
```json{ "discovered_expression": "sin(x1) + x2", "status": "in_progress", // or "completed" "notes": "short optional notes"}```1234567891011121314151617181920212223242526272829303132333435363738394041import sysimport jsonimport numpy as npfrom typing import Anyfrom pathlib import Pathfrom datetime import datetime, timezonefrom 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288"""Run the original FunctionEvolve search in an isolated subprocess.
Clone Phoinikas03/FunctionEvolve into baseline/repo/FunctionEvolve and installits 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 canset --functionevolve_max_steps 0 --functionevolve_n_seeds 3. OpenRouter reasoningis enabled by default. Defaults follow the upstream full/Qwen preset, with afixed training NMSE threshold (1e-11) rather than the unavailable GT baseline.
Only SEDTask training data and descriptions reach the upstream search. No GTbaseline, automatic GT threshold, or upstream symbolic verifier is invoked.Artifacts are saved under save_path/functionevolve/<task>-<unique suffix>."""from __future__ import annotations
import argparsefrom datetime import datetimeimport functoolsimport jsonimport osfrom pathlib import Pathimport reimport signalimport subprocessimport sysimport tempfilefrom 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()12345678910111213141516171819202122232425262728293031323334353637"""线性拟合符号回归方法"""from __future__ import annotations
import argparseimport numpy as npfrom numpy.linalg import lstsqfrom ..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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419"""LLM-SRBench adapter for the upstream IGSR implementation.
The upstream checkout is used without source changes. This module starts it inan isolated process, injects the benchmark training data as an IGSR DataBundle,and audits every LiteLLM call before returning control to IGSR. Per-call usageis flushed to ``usage.jsonl`` and relayed through ``_logger`` so completed callsremain accountable if a later search step fails."""from __future__ import annotations
import argparseimport astimport jsonimport loggingimport osfrom pathlib import Pathimport reimport signalimport subprocessimport sysimport tempfileimport threadingimport timeimport tracebackfrom 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, "<igsr-term>", "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") raise123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104"""PySR benchmark adapter with persistent, full precision artifacts."""from __future__ import annotations
import argparseimport jsonimport loggingimport osimport reimport timeimport tracebackfrom pathlib import Path
import numpy as np
from .pysr import best_expressionfrom ..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)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859"""多项式拟合符号回归方法"""
from __future__ import annotations
import argparseimport numpy as npimport sr_harness_engine as enginefrom sr_harness.core import AgentContextfrom sr_harness.tools import PolynomialFitToolfrom ..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"])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105"""PySR 符号回归方法"""from __future__ import annotationsimport osimport reimport shutilimport loggingimport argparseimport tempfileimport numpy as npfrom typing import Anyfrom ..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 expression123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212"""多项式拟合符号回归方法"""from __future__ import annotations
import jsonimport argparseimport numpy as npimport sr_harness_engine as enginefrom pathlib import Pathfrom logging import getLoggerfrom datetime import datetimefrom sr_harness import SRAgentfrom sr_harness.tools import BaseToolfrom sr_harness.utils import format_pareto_front, log_exception, tag2ansifrom ..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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425"""Raw SR-Scientist runner for llmsr_bench.
Unlike ``sr_scientist.py``, this module does not reimplement the SR-Scientistsearch 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 APIand 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 andtries to auto-start missing local SandboxFusion endpoints. SetSR_SCIENTIST_RAW_AUTO_SANDBOX=0 to disable auto-start, or setSR_SCIENTIST_RAW_SANDBOX_URLS to choose default URLs when command-line URLs arenot available yet."""from __future__ import annotations
import osimport reimport sysimport astimport jsonimport timeimport socketimport loggingimport asyncioimport subprocessimport tempfileimport numpy as npimport pandas as pdfrom pathlib import Pathfrom dotenv import load_dotenvfrom typing import Any, Dict, List, Tuplefrom urllib.parse import urlparsefrom ..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_batchexcept Exception as exc: run_inference_batch = None _IMPORT_ERROR = excelse: _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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081"""LLM-SRBench 核心数据结构"""from __future__ import annotations
import numpy as npimport sr_harness_engine as enginefrom dataclasses import dataclassfrom typing import Callable, Dict, List, Optional
__all__ = ["SEDTask", "SRResult", "Problem"]
@dataclassclass 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,)
@dataclassclass 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 等)
@dataclassclass 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], )1234567891011121314"""SRAgent implementations."""from .agent import Agentfrom .data_preparation_agent import DataPreparationAgentfrom .evaluator_construction_agent import EvaluatorConstructionAgentfrom .sr_agent import SRAgentfrom .sr_agent_interactive import SRAgentInteractive
__all__ = [ "Agent", "DataPreparationAgent", "EvaluatorConstructionAgent", "SRAgent", "SRAgentInteractive",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License."""Common runtime mechanics shared by SRHarness agents."""from __future__ import annotations
import loggingfrom abc import ABC, abstractmethodfrom copy import deepcopyfrom typing import Any
from joblib import Parallel, delayed
from ..api import BaseAPIfrom ..core import AgentContext, ToolCall, ToolCallResultfrom ..parser import BaseParserfrom ..tools import BaseToolfrom ..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]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License."""Persistent tool-using agent for preparing structured research data."""
from __future__ import annotations
import timeimport uuidfrom copy import deepcopyfrom typing import Any
from ..core import AgentContextfrom ..runtime import InteractionManagerfrom ..parser import BaseParserfrom ..skills import SkillManagerfrom ..tools import BaseToolfrom ..utils import ParallelTimerfrom .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 <name>.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 <variable>.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 <axis>.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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404"""Restricted agent for constructing and repairing custom evaluators."""
from __future__ import annotations
import jsonimport mathimport numbersimport timeimport uuidfrom typing import Any
from ..api import BaseAPIfrom ..core import AgentContext, json_valuefrom ..parser import BaseParserfrom ..runtime import InteractionManagerfrom ..tools import BaseToolfrom ..utils import ParallelTimerfrom .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" )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License."""基类 Agent 和 Buffer 的定义。
提供符号回归 Agent 的基础框架,包括主循环 Pipeline 和工具调用机制。"""from __future__ import annotationsimport jsonimport loggingimport numpy as npfrom pathlib import Pathfrom copy import deepcopyfrom itertools import islicefrom collections import defaultdictfrom contextlib import contextmanagerfrom typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, TypeAliasfrom ..api import BaseAPIfrom ..tools import BaseToolfrom ..parser import BaseParserfrom ..skills import SkillManagerfrom ..runtime import ModelRouterfrom ..utils import ParallelTimer, NamedTimer, Timerfrom ..utils import format_pareto_front, render_markdown, tag2ansi, setup_loggingfrom ..core import APICallSample, AgentContext, CandidateRecord, ParentLink, SearchRunState, ToolCall, ToolCallResultfrom .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()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License."""人机协同符号回归 Agent。
继承自 SRAgent,以 L(对话轮次)为搜索主体,支持人类实时干预和工作区文件操作。"""
from __future__ import annotationsimport jsonimport loggingimport mathimport tempfileimport timefrom contextlib import contextmanagerfrom pathlib import Pathfrom typing import Any, Callable, Iterator, List, Optional
from ..api import BaseAPIfrom ..core import APICallSample, AgentContext, CandidateRecord, ToolCall, ToolCallResultfrom ..runtime import PendingMessage, SRInteractionManagerfrom ..skills import SkillManagerfrom .sr_agent import Message, SRAgent, Usagefrom ..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"<unnamed:{index}>" 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." )12345678910111213141516171819202122# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License.from .base_api import BaseAPIfrom ..core import APICallSummaryfrom .manual_api import ManualAPIfrom .openai_api import OpenAIAPIfrom .gemini_api import GeminiAPIfrom .deepseek_api import DeepSeekAPIfrom .openrouter_api import OpenRouterAPIfrom .lmstudio_api import LMStudioAPIfrom .siliconflow_api import SiliconFlowAPI
__all__ = [ "APICallSummary", "BaseAPI", "DeepSeekAPI", "GeminiAPI", "LMStudioAPI", "ManualAPI", "OpenAIAPI", "OpenRouterAPI", "SiliconFlowAPI",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537# 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 jsonimport loggingimport timeimport threadingimport tracebackimport uuidfrom abc import ABC, abstractmethodfrom dataclasses import dataclass, fieldimport osfrom pathlib import Pathfrom typing import Any, Callable, Generator, Mappingfrom requests.utils import should_bypass_proxies
from ..core import APICallSample, APICallSummary, ToolCallfrom ..parser import BaseParserfrom ..utils import FactoryMixinfrom .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 None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License.import httpxfrom openai import DefaultHttpxClient, OpenAIfrom typing import Anyfrom .base_api import BaseAPI, ProgressCallback, ProviderSampleResultfrom .utils import RemoteModelCatalogfrom ..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, )123456789101112131415161718192021222324252627282930313233343536373839404142"""Temporary, weakly coupled screening for errors shown to frontend users."""
from __future__ import annotations
import osfrom 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)))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License.import httpxfrom typing import Any, Generator, List, Dictfrom google import genaifrom google.genai import typesfrom .base_api import BaseAPIfrom ..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]}, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License.from __future__ import annotations
import loggingfrom typing import Any, Dict, Generator, Listfrom urllib.parse import urlsplit, urlunsplit
import requestsfrom dotenv import load_dotenv
from .base_api import BaseAPIfrom ..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]}, }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License.import loggingimport tempfilefrom pathlib import Pathfrom typing import Any, Generator, List, Dictfrom .base_api import BaseAPIfrom ..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": {}, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License.import loggingfrom copy import deepcopyfrom openai import AzureOpenAI, DefaultHttpxClientfrom openai.types.responses import Responsefrom openai.types.chat import ChatCompletionfrom collections import defaultdictfrom typing import Any, Generator, List, Dictfrom .base_api import BaseAPI, ProgressCallbackfrom ..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 usage123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License.import httpxfrom openai import DefaultHttpxClient, OpenAIfrom dotenv import load_dotenvfrom typing import Anyfrom .base_api import BaseAPI, ProgressCallback, ProviderSampleResultfrom .utils import RemoteModelCatalogfrom ..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, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License.import httpximport loggingimport requestsfrom dotenv import load_dotenvfrom typing import Any, Callable, Dict, Generator, List
from .base_api import BaseAPI, ProgressCallback, ProviderSampleResultfrom .utils import RemoteModelCatalogfrom ..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)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667# Copyright (c) 2024-present, Yumeow. Licensed under the MIT License."""Small infrastructure helpers shared by API provider adapters."""
from __future__ import annotations
import timefrom 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)12345本目录提供面向用户的命令行脚本。每个脚本都应该实现 `setup_parser(parser)` 和 `main(args)`;前者负责配置命令行参数,后者执行已经解析的参数并返回退出码。
模型检查点的下载与上传属于开发维护操作,相关独立脚本位于仓库根目录的 `scripts/` 中。
> CLI 快速开始与完整参数入口:[`docs/index.md`](../../../docs/index.md)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778"""Unified command-line entry point for SRHarness."""from __future__ import annotationsimport argparseimport 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705"""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 reimport timeimport jsonimport h5pyimport shleximport dotenvimport loggingimport argparseimport datasetsimport numpy as npimport sr_harness_engine as enginefrom sr_harness_engine.tree import transformfrom pathlib import Pathfrom datetime import datetimefrom socket import gethostnamefrom typing import Callable, Dict, Listfrom scipy.stats import kendalltaufrom scipy.optimize import least_squaresfrom sklearn.metrics import mean_absolute_percentage_errorfrom 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, Problemfrom 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 presentSCRIPT_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/<name> 或 /lsr_synth/<domain>/<name> 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"(?<![A-Za-z_])(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?_[A-Za-z_]\w*", lambda m, c=iter(range(100)): f"__C{next(c)}", expression, )
# Physical Oscillation / Chemical Reaction 数据集中公式的常数未被正确设置,需要拟合后替换成数值 if dataset_name in {'phys_osc', 'chem_react'}: formula = engine.parse(expression) if unknowns := sorted({var.name for var in formula.iter_preorder() if isinstance(var, engine.Variable) and var.name not in entry['symbols']}): train, y = samples["train"], samples["train"][:, 0] base = {sym: train[:, i] for i, sym in enumerate(entry["symbols"])} def residual(c): data = base | {k: np.full(len(y), v) for k, v in zip(unknowns, c)} return formula.eval(data).flatten() - y starts = [np.full(len(unknowns), x) for x in (0.1, 0.5, 1.0, 2.0)] starts += [np.where(np.arange(len(unknowns)) == i, 0.01, 0.5) for i in range(len(unknowns))] rng = np.random.default_rng(0) starts += [np.exp(rng.uniform(np.log(0.01), np.log(2.0), len(unknowns))) for _ in range(4)] fits = [least_squares(residual, x0, bounds=(0, np.inf), max_nfev=5000).x for x0 in starts] values = min(fits, key=lambda c: np.mean(residual(c) ** 2)) for key, val in zip(unknowns, values): expression = re.sub(rf"\b{re.escape(key)}\b", repr(float(val)), expression)
gt_expression = engine.parse(expression)
# 确保没有未知变量 variables = {var.name for var in gt_expression.iter_preorder() if isinstance(var, engine.Variable)} if missing := set(variables) - set(entry['symbols']): _logger.warning(f"[{dataset_name}] {name} has unknown variables in expression: {missing}. This problem is SKIPPED.") continue
# 确保 gt_expression 足够准确 data = {sym: samples["train"][:, i] for i, sym in enumerate(entry["symbols"])} y_pred = gt_expression.eval(data) y_true = data[entry["symbols"][0]] metrics = { 'mae': float(np.mean(np.abs(y_true - y_pred))), 'mape': float(mean_absolute_percentage_error(y_true, y_pred)), 'rmse': float(np.sqrt(np.mean((y_true - y_pred) ** 2))), 'r2': float(1 - np.mean((y_true - y_pred) ** 2) / np.var(y_true)) if np.var(y_true) > 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="<None>", 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()))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195from __future__ import annotations
import argparseimport sysimport tempfilefrom datetime import datetimefrom pathlib import Pathfrom 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()))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369# 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 jsonimport shleximport loggingimport argparseimport numpy as npimport sr_harness_engine as enginefrom pathlib import Pathfrom datetime import datetimefrom socket import gethostnamefrom sr_harness import SRAgentfrom 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()))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License."""Command-line gateway for SRHarness tools."""from __future__ import annotations
import jsonimport argparseimport numpy as npimport sr_harness.toolsfrom pathlib import Pathfrom typing import Anyfrom sr_harness.core import AgentContextfrom 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()))1234567891011121314151617181920212223242526272829303132333435363738394041"""Dependency-light domain types and runtime state for SRHarness."""from .api import APICallSample, APICallSummaryfrom .context import AgentContextfrom .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",]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697# Copyright (c) 2026-present, Yumeow. Licensed under the MIT License.from __future__ import annotations
from dataclasses import dataclass, fieldfrom 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
@dataclassclass 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 {}).dockerignoreAdded+16
DockerfileAdded+57
LICENSEAdded+7
README.md+122-4
deploy/huggingface/README.mdAdded+75
pyproject.tomlAdded+108
src/sr_harness/README.mdAdded+109
src/sr_harness/__init__.pyAdded+31
src/sr_harness/_vendor/README.zh.mdAdded+13
src/sr_harness/_vendor/__init__.pyAdded
src/sr_harness/_vendor/llmsr_bench/__init__.pyAdded+1
src/sr_harness/_vendor/llmsr_bench/algorithms/__init__.pyAdded+32
src/sr_harness/_vendor/llmsr_bench/algorithms/codex/__init__.pyAdded+747
src/sr_harness/_vendor/llmsr_bench/algorithms/codex/call_tool_template.pyAdded+63
src/sr_harness/_vendor/llmsr_bench/algorithms/codex/readme_template.mdAdded+83
src/sr_harness/_vendor/llmsr_bench/algorithms/codex/utils.pyAdded+41
src/sr_harness/_vendor/llmsr_bench/algorithms/functionevolve.pyAdded+288
src/sr_harness/_vendor/llmsr_bench/algorithms/linear.pyAdded+37
src/sr_harness/_vendor/llmsr_bench/algorithms/my_igsr.pyAdded+419
src/sr_harness/_vendor/llmsr_bench/algorithms/my_pysr.pyAdded+104
src/sr_harness/_vendor/llmsr_bench/algorithms/polynomial.pyAdded+59
src/sr_harness/_vendor/llmsr_bench/algorithms/pysr.pyAdded+105
src/sr_harness/_vendor/llmsr_bench/algorithms/sr_harness.pyAdded+212
src/sr_harness/_vendor/llmsr_bench/algorithms/sr_scientist.pyAdded+425
src/sr_harness/_vendor/llmsr_bench/core.pyAdded+81
src/sr_harness/agents/__init__.pyAdded+14
src/sr_harness/agents/agent.pyAdded+146
src/sr_harness/agents/data_preparation_agent.pyAdded+370
src/sr_harness/agents/evaluator_construction_agent.pyAdded+404
src/sr_harness/agents/sr_agent.pyAdded+1428
src/sr_harness/agents/sr_agent_interactive.pyAdded+1087
src/sr_harness/api/__init__.pyAdded+22
src/sr_harness/api/base_api.pyAdded+537
src/sr_harness/api/deepseek_api.pyAdded+128
src/sr_harness/api/error_filter.pyAdded+42
src/sr_harness/api/gemini_api.pyAdded+162
src/sr_harness/api/lmstudio_api.pyAdded+214
src/sr_harness/api/manual_api.pyAdded+97
src/sr_harness/api/openai_api.pyAdded+528
src/sr_harness/api/openrouter_api.pyAdded+145
src/sr_harness/api/siliconflow_api.pyAdded+341
src/sr_harness/api/utils.pyAdded+67
src/sr_harness/cli/README.zh.mdAdded+5
src/sr_harness/cli/__init__.pyAdded+78
src/sr_harness/cli/benchmark.pyAdded+705
src/sr_harness/cli/run.pyAdded+195
src/sr_harness/cli/synthetic.pyAdded+369
src/sr_harness/cli/tool.pyAdded+194
src/sr_harness/core/__init__.pyAdded+41
src/sr_harness/core/api.pyAdded+97