跳转至

API Reference

This section is generated from SRHarness type signatures and Google-style docstrings.

The public API consists of objects exported by each package. Vendored modules, Web route handlers, and implementation details whose names start with an underscore are outside the compatibility contract.

Use the table of contents to jump between packages, classes, and methods. All sections below are generated from the current source tree during the MkDocs build.

Agents

sr_harness.agents

SRAgent implementations.

__all__ module-attribute

__all__ = [
    "Agent",
    "DataPreparationAgent",
    "EvaluatorConstructionAgent",
    "SRAgent",
    "SRAgentInteractive",
]

Agent

Bases: 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.

run abstractmethod

run(*args: Any, **kwargs: Any) -> Any

Run the agent's task loop.

参数:

名称 类型 描述 默认
*args Any

Positional inputs accepted by the concrete agent.

()
**kwargs Any

Keyword inputs accepted by the concrete agent.

{}

返回:

类型 描述
Any

The result defined by the concrete agent implementation.

initialize_tools

initialize_tools(context: AgentContext) -> None

Bind one shared context to every tool, parser, and API adapter.

参数:

名称 类型 描述 默认
context AgentContext

Shared agent and tool context.

必需

set_messages

set_messages(messages: list[dict[str, Any]]) -> None

Expose the current prompt through the shared tool context.

参数:

名称 类型 描述 默认
messages list[dict[str, Any]]

Conversation messages in provider-compatible order.

必需

execute_action

execute_action(
    actions: list[ToolCall],
) -> list[ToolCallResult]

Execute tool calls serially.

参数:

名称 类型 描述 默认
actions list[ToolCall]

Tool calls to execute.

必需

返回:

类型 描述
list[ToolCallResult]

Results in the same order as actions.

execute_action_parallel

execute_action_parallel(
    actions: list[ToolCall], max_workers: int
) -> list[ToolCallResult]

Execute independent tool calls in worker processes.

参数:

名称 类型 描述 默认
actions list[ToolCall]

Tool calls to execute.

必需
max_workers int

Maximum number of parallel workers.

必需

返回:

类型 描述
list[ToolCallResult]

Results in the same order as actions.

DataPreparationAgent

DataPreparationAgent(
    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,
)

Bases: Agent

Turn workspace and web evidence into the shared structured dataset.

queue_runtime_settings

queue_runtime_settings(settings: dict[str, Any]) -> None

Queue validated settings for the next safe iteration boundary.

initialize_tools

initialize_tools(context: AgentContext) -> None

Bind configured skills before constructing context-aware tools.

参数:

名称 类型 描述 默认
context AgentContext

Shared agent and tool context.

必需

run

run(instruction: str) -> dict[str, Any]

Continue the persistent preparation conversation until it yields control.

参数:

名称 类型 描述 默认
instruction str

Natural-language instruction for the agent.

必需

返回:

类型 描述
dict[str, Any]

dict[str, Any]: The operation result.

EvaluatorConstructionAgent

EvaluatorConstructionAgent(
    *,
    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,
)

Bases: Agent

Construct and validate evaluator scripts without mutating live context state.

queue_runtime_settings

queue_runtime_settings(settings: dict[str, Any]) -> None

Queue validated settings for the next safe iteration boundary.

run

run(instruction: str) -> dict[str, Any]

Construct or repair a custom evaluator for one user instruction.

参数:

名称 类型 描述 默认
instruction str

Natural-language evaluator requirements.

必需

返回:

类型 描述
dict[str, Any]

The final assistant response and tool-event records produced during

dict[str, Any]

construction.

引发:

类型 描述
ValueError

If instruction is empty.

SRAgent

SRAgent(
    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,
)

Bases: Agent

Agent that performs an R-C-L-K symbolic-regression search.

初始化 Agent。

参数:

名称 类型 描述 默认
llm_provider str

LLM 提供商名称(如 "openai", "siliconflow")。

必需
llm_model str

模型名称(如 "gpt-4o-mini")。

必需
tools list[str] | None

可用工具列表。None 表示使用 DEFAULT_TOOLS。

None
skills List[str] | None

可供 Agent 读取的 skill 名称。None 表示使用全部 skill。

None
verbose bool

是否启用详细日志(DEBUG 级别)。

False
tool_parser str | BaseParser

工具解析器,可以是字符串('text', 'json')或 BaseParser 实例。

'openai'
save_path Optional[str]

日志文件保存路径。None 表示不保存到文件。

None
run_id str | None

本次运行的全局唯一标识。None 表示自动生成。

None
local_sample_size int

每轮生成的候选解数量。

1
max_refinement_depth int

最大迭代次数。

20
global_width int

每个 restart turn 中独立对话分支数量。

1
max_restart_loop int

best-solution restarts 次数

1
restart_top_k int

下一轮 restart prompt 中保留的历史最佳结果数量。

1
llm_max_tokens int

每次 LLM 响应的最大 token 数。

4096
max_workers int

并行执行工具调用的最大工作进程数。0 表示不使用并行。

0
validation_fraction float

验证集比例;验证集结果会展示给 Agent。设为 0 可关闭。

0.2
split_by str

验证集划分方式。"random" 表示随机划分;"ood" 要求通过 split_ood_variable 显式指定排序变量。

'random'
split_ood_variable str | None

OOD 划分使用的变量名;随机划分时可留空。

None
split_random_state int

数据划分的随机种子。

42
ranking_metric str

候选公式排序所用的指标键;默认使用 mse。

'mse'
larger_is_better bool

排序指标是否越大越好;默认按越小越好排序。

False
force_initial_diagnostics bool

是否在每个对话分支的 L=1 请求 LLM 前,强制执行 statistics_analysis、relationship_analysis 和读取 discover-symbolic-laws skill。

False
auto_routing bool

是否根据任务复杂度在基础与强模型后端之间自动路由。

True
strong_llm_provider str | None

复杂任务使用的后端;默认沿用 llm_provider。

None
strong_llm_model str | None

复杂任务使用的模型。None 表示仅使用基础模型。

None
context AgentContext | None

与其它 Agent 共享的数据和工作区上下文。None 表示新建独立上下文。

None
skill_manager SkillManager | None

Skill 注册表。None 表示使用临时的自定义 skill 目录。

None

run

run(
    X: Dict[str, ndarray],
    y: Dict[str, ndarray] | ndarray,
    problem_description: str,
) -> Dict[str, Any]

Run the configured operation.

参数:

名称 类型 描述 默认
X Dict[str, ndarray]

Input feature arrays keyed by variable name.

必需
y Dict[str, ndarray] | ndarray

Target data or target expression.

必需
problem_description str

Natural-language description of the discovery task.

必需

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: The operation result.

prepare_tool_context

prepare_tool_context(
    tool_context: AgentContext,
) -> Iterator[AgentContext]

Prepare resources and context shared by initialized tools.

参数:

名称 类型 描述 默认
tool_context AgentContext

Shared context used to initialize tools.

必需

产生:

类型 描述
AgentContext

The context to bind to initialized tools.

search

search(
    X: Dict[str, ndarray],
    y: Dict[str, 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.

参数:

名称 类型 描述 默认
X Dict[str, ndarray]

Input feature arrays keyed by variable name.

必需
y Dict[str, ndarray]

Target data or target expression.

必需
problem_description str

Natural-language description of the discovery task.

必需

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: The operation result.

create_initial_buffer

create_initial_buffer(
    problem_description: str,
    X: dict[str, ndarray],
    y: dict[str, ndarray],
    restart_records: list[CandidateRecord],
) -> list[Message]

Combine initial prompts with the first progress message for a branch.

参数:

名称 类型 描述 默认
problem_description str

Natural-language description of the discovery task.

必需
X dict[str, ndarray]

Input feature arrays keyed by variable name.

必需
y dict[str, ndarray]

Target data or target expression.

必需
restart_records list[CandidateRecord]

Ranked candidates used to seed a restart.

必需

返回:

类型 描述
list[Message]

Initial branch buffer including the first progress message.

create_initial_prompt_messages

create_initial_prompt_messages(
    problem_description: str,
    X: dict[str, ndarray],
    y: dict[str, ndarray],
    restart_records: list[CandidateRecord],
) -> list[Message]

Create finalized system and user messages without buffer metadata.

参数:

名称 类型 描述 默认
problem_description str

Natural-language discovery task.

必需
X dict[str, ndarray]

Feature arrays keyed by variable name.

必需
y dict[str, ndarray]

Target arrays keyed by variable name.

必需
restart_records list[CandidateRecord]

Ranked candidates used to seed a restart.

必需

返回:

类型 描述
list[Message]

Finalized system and user messages.

create_initial_system_prompt

create_initial_system_prompt(
    restart_records: list[CandidateRecord],
) -> str

Create the initial system prompt independently of the branch buffer.

参数:

名称 类型 描述 默认
restart_records list[CandidateRecord]

Ranked candidates used to set the next objective.

必需

返回:

类型 描述
str

System-prompt text.

create_initial_user_prompt

create_initial_user_prompt(
    problem_description: str,
    X: dict[str, ndarray],
    y: dict[str, ndarray],
    restart_records: list[CandidateRecord],
) -> str

Create the initial user prompt independently of the branch buffer.

参数:

名称 类型 描述 默认
problem_description str

Natural-language discovery task.

必需
X dict[str, ndarray]

Feature arrays keyed by variable name.

必需
y dict[str, ndarray]

Target arrays keyed by variable name.

必需
restart_records list[CandidateRecord]

Ranked candidates included as restart evidence.

必需

返回:

类型 描述
str

User-prompt text.

customize_initial_prompts

customize_initial_prompts(
    messages: list[Message],
    *,
    X: dict[str, ndarray],
    y: dict[str, ndarray],
) -> list[Message]

Customize finalized initial prompts before buffer insertion.

参数:

名称 类型 描述 默认
messages list[Message]

Initial system and user messages.

必需
X dict[str, ndarray]

Feature arrays keyed by variable name.

必需
y dict[str, ndarray]

Target arrays keyed by variable name.

必需

返回:

类型 描述
list[Message]

Messages to insert into the branch buffer.

on_buffer_messages_added

on_buffer_messages_added(
    messages: list[Message], **coordinate: int
) -> None

Observe messages after they enter a conversation buffer.

参数:

名称 类型 描述 默认
messages list[Message]

Newly appended messages.

必需
**coordinate int

Optional R/C/L search coordinate.

{}

prepare_model_messages

prepare_model_messages(
    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.

参数:

名称 类型 描述 默认
buffer List[Dict[str, Any]]

Conversation history buffer.

必需
R int

One-based restart index.

必需
L int

One-based refinement-step index.

必需
C int

One-based conversation-branch index.

必需

返回:

类型 描述
List[Dict[str, Any]]

List[Dict[str, Any]]: The operation result.

prepare_iteration

prepare_iteration(
    buffer: List[Dict[str, Any]], R: int, L: int, C: int
) -> str | None

Apply mode-specific control changes before constructing this iteration's prompt.

参数:

名称 类型 描述 默认
buffer List[Dict[str, Any]]

Conversation history buffer.

必需
R int

One-based restart index.

必需
L int

One-based refinement-step index.

必需
C int

One-based conversation-branch index.

必需

返回:

类型 描述
str | None

str | None: The operation result.

refresh_data

refresh_data() -> dict[str, Any] | None

Apply a newly committed shared-data revision and describe the change.

finish_iteration

finish_iteration(
    buffer: List[Dict[str, Any]], R: int, L: int, C: int
) -> str | None

Return a terminal status when the current search should stop.

参数:

名称 类型 描述 默认
buffer List[Dict[str, Any]]

Conversation history buffer.

必需
R int

One-based restart index.

必需
L int

One-based refinement-step index.

必需
C int

One-based conversation-branch index.

必需

返回:

类型 描述
str | None

str | None: The operation result.

run_initial_diagnostics

run_initial_diagnostics(
    R: int, L: int, C: int
) -> Dict[str, str]

Run the mandatory branch-opening diagnostics and format them for the LLM.

参数:

名称 类型 描述 默认
R int

One-based restart index.

必需
L int

One-based refinement-step index.

必需
C int

One-based conversation-branch index.

必需

返回:

类型 描述
Dict[str, str]

Dict[str, str]: The operation result.

request_llm

request_llm(
    prompt: List[Dict[str, Any]],
    R: int,
    L: int,
    C: int,
    stream_callback: Callable[[dict[str, Any]], None]
    | None = None,
) -> tuple[list[ModelResponse], Usage | None]

Run the request llm operation.

参数:

名称 类型 描述 默认
prompt List[Dict[str, Any]]

Prompt messages sent to the model.

必需
R int

One-based restart index.

必需
L int

One-based refinement-step index.

必需
C int

One-based conversation-branch index.

必需
stream_callback Callable[[dict[str, Any]], None] | None

Optional callback invoked for streamed model updates.

None

返回:

类型 描述
tuple[list[ModelResponse], Usage | None]

Parsed model responses and recorded usage data.

execute_tool_calls

execute_tool_calls(
    response_list: list[ModelResponse],
    R: int,
    L: int,
    C: int,
) -> list[list[ToolCallResult]]

Execute tool calls from model responses and preserve sample grouping.

参数:

名称 类型 描述 默认
response_list list[ModelResponse]

Model responses for the current step.

必需
R int

One-based restart index.

必需
L int

One-based refinement-step index.

必需
C int

One-based conversation-branch index.

必需

返回:

类型 描述
list[list[ToolCallResult]]

Tool results grouped by local model sample.

record_tool_calls

record_tool_calls(
    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.

参数:

名称 类型 描述 默认
tool_calls List[ToolCall]

Tool calls returned by the model.

必需
results List[ToolCallResult]

Result records to process.

必需
R int

One-based restart index.

必需
L int

One-based refinement-step index.

必需
C int

One-based conversation-branch index.

必需
forced bool

The forced value.

False

update_conversation

update_conversation(
    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.

参数:

名称 类型 描述 默认
buffer List[Dict[str, Any]]

Conversation history buffer.

必需
response_list List[Tuple[str, List[ToolCall], Dict[str, Any]]]

Model responses for the current step.

必需
results_list List[List[ToolCallResult]]

Tool results aligned with model responses.

必需
node_parents Dict[str, str]

The node parents value.

必需
R int

One-based restart index.

必需
L int

One-based refinement-step index.

必需
C int

One-based conversation-branch index.

必需

返回:

类型 描述
tuple[list[Message], dict[str, str]]

Updated conversation buffer and parent-link mapping.

build_response_followup_messages

build_response_followup_messages(
    response_list: list[ModelResponse],
    results_list: list[list[ToolCallResult]],
    *,
    R: int,
    L: int,
    C: int,
) -> list[Message]

Return framework messages to append after one model response.

参数:

名称 类型 描述 默认
response_list list[ModelResponse]

Model responses for the current iteration.

必需
results_list list[list[ToolCallResult]]

Tool results aligned with the model responses.

必需
R int

One-based restart index.

必需
L int

One-based refinement-step index.

必需
C int

One-based conversation-branch index.

必需

返回:

类型 描述
list[Message]

Additional conversation messages, empty for the base agent.

build_progress_message

build_progress_message(L: int) -> dict[str, str]

Build process message.

参数:

名称 类型 描述 默认
L int

One-based refinement-step index.

必需

返回:

类型 描述
dict[str, str]

User-role message describing iteration state and the Pareto front.

push_candidate

push_candidate(record: CandidateRecord) -> None

Run the push candidate operation.

参数:

名称 类型 描述 默认
record CandidateRecord

Search or candidate record.

必需

collect_candidates

collect_candidates(
    response_list: list[ModelResponse],
    results_list: list[list[ToolCallResult]],
    R: int,
    L: int,
    C: int,
) -> list[CandidateRecord]

Validate candidate tool results and add them to the run state.

参数:

名称 类型 描述 默认
response_list list[ModelResponse]

Model responses for the current step.

必需
results_list list[list[ToolCallResult]]

Tool results aligned with model responses.

必需
R int

One-based restart index.

必需
L int

One-based refinement-step index.

必需
C int

One-based conversation-branch index.

必需

返回:

类型 描述
list[CandidateRecord]

Candidates ranked under the configured metric.

log_info

log_info(
    response_list: list[ModelResponse],
    R: int,
    L: int,
    C: int,
) -> None

Run the log info operation.

参数:

名称 类型 描述 默认
response_list list[ModelResponse]

Model responses for the current step.

必需
R int

One-based restart index.

必需
L int

One-based refinement-step index.

必需
C int

One-based conversation-branch index.

必需

record_llm_result

record_llm_result(
    llm_result: Any, R: int, L: int, C: int
) -> Dict[str, Any] | None

Record llm result.

参数:

名称 类型 描述 默认
llm_result Any

The llm result value.

必需
R int

One-based restart index.

必需
L int

One-based refinement-step index.

必需
C int

One-based conversation-branch index.

必需

返回:

类型 描述
Dict[str, Any] | None

Dict[str, Any] | None: The operation result.

record_search_iteration

record_search_iteration(
    response_list: list[ModelResponse],
    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.

参数:

名称 类型 描述 默认
response_list list[ModelResponse]

Model responses for the current step.

必需
results_list list[list[ToolCallResult]]

Tool results aligned with model responses.

必需
parent_nodes dict[str, str]

Parent search nodes by response.

必需
prompt list[Message]

Prompt messages sent to the model.

必需
usage Usage | None

Token and price usage information.

必需
R int

One-based restart index.

必需
L int

One-based refinement-step index.

必需
C int

One-based conversation-branch index.

必需

format_progress

format_progress(
    R: int | None, L: int | None, C: int | None
) -> str

Format progress.

参数:

名称 类型 描述 默认
R int | None

One-based restart index.

必需
L int | None

One-based refinement-step index.

必需
C int | None

One-based conversation-branch index.

必需

返回:

类型 描述
str

Human-readable R/C/L/K progress text.

get_ranking_metric

get_ranking_metric(
    record: CandidateRecord | dict[str, Any],
) -> tuple[str | None, float | int | None]

Return the configured ranking metric and its display label.

参数:

名称 类型 描述 默认
record CandidateRecord | dict[str, Any]

Search or candidate record.

必需

返回:

类型 描述
tuple[str | None, float | int | None]

Display label and metric value, or two None values when absent.

candidate_sort_key

candidate_sort_key(
    record: CandidateRecord | dict[str, Any],
) -> tuple[float, float] | None

Return the ranking key for a candidate-like record.

参数:

名称 类型 描述 默认
record CandidateRecord | dict[str, Any]

Search or candidate record.

必需

返回:

类型 描述
tuple[float, float] | None

Metric and complexity sorting key, or None for invalid metrics.

candidate_to_dict staticmethod

candidate_to_dict(
    record: CandidateRecord,
) -> dict[str, Any]

Adapt a candidate to utilities that consume split results at top level.

参数:

名称 类型 描述 默认
record CandidateRecord

Search or candidate record.

必需

返回:

类型 描述
dict[str, Any]

dict[str, Any]: The operation result.

best_candidate

best_candidate() -> CandidateRecord | None

Run the best candidate operation.

返回:

类型 描述
CandidateRecord | None

CandidateRecord | None: The operation result.

get_pareto_front

get_pareto_front() -> list[CandidateRecord]

Return candidates on the metric-complexity Pareto front.

返回:

类型 描述
list[CandidateRecord]

list[CandidateRecord]: The operation result.

build_search_result

build_search_result(
    status: str, R: int | None, L: int | None, C: int | None
) -> dict[str, Any]

Build a serializable search result for the current run state.

参数:

名称 类型 描述 默认
status str

Run completion status.

必需
R int | None

One-based restart index.

必需
L int | None

One-based refinement-step index.

必需
C int | None

One-based conversation-branch index.

必需

返回:

类型 描述
dict[str, Any]

Serializable run result including progress and ranked candidates.

SRAgentInteractive

SRAgentInteractive(
    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,
    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,
)

Bases: SRAgent

Interactive symbolic-regression agent controlled by an interaction manager.

初始化 SRAgentInteractive。

参数:

名称 类型 描述 默认
llm_provider str

LLM 提供商名称。

必需
llm_model str

模型名称。

必需
tools list[str] | None

可用工具名列表。None 表示使用 SRAgent.DEFAULT_TOOLS。

None
skills List[str] | None

可供 Agent 读取的 skill 名称。None 表示使用全部 skill。

None
verbose bool

是否启用详细日志。

False
tool_parser str | BaseParser

工具解析器类型。

'openai'
save_path Optional[str]

日志保存路径。

None
run_id str | None

本次运行的全局唯一标识。None 表示自动生成。

None
local_sample_size int

每轮 LLM 采样数量(K)。

1
max_refinement_depth int

最大对话轮次(L),也是搜索深度上限。

50
global_width int

独立分支数量(C)。

1
max_restart_loop int

重启次数(R)。

1
restart_top_k int

重启时注入历史最佳结果数量。

1
llm_max_tokens int

每次模型响应允许生成的最大 token 数。

4096
max_workers int

并行工作进程数(0 表示不并行)。

0
validation_fraction float

验证集比例。

0.2
split_by str

验证集划分方式,可选 "random" 或 "ood"。

'random'
split_ood_variable str | None

OOD 划分使用的变量名;随机划分时可留空。

None
split_random_state int

数据划分随机种子。

42
ranking_metric str

候选公式排序所用的指标键;默认使用 mse。

'mse'
larger_is_better bool

排序指标是否越大越好;默认按越小越好排序。

False
use_workspace bool

是否使用工作区。

False
workspace_files List[str | Path] | None

初始化到工作区的文件/目录路径列表。

None
interaction_manager SRInteractionManager

连接 Agent 与 Web、终端等交互界面的管理器。

必需
force_initial_diagnostics bool

是否在每个分支开始时强制执行初始诊断。

False
pause_on_truncated_response bool

模型输出因长度限制截断后是否在安全边界暂停。

True
auto_routing bool

是否根据任务复杂度在基础与强模型后端之间自动路由。

True
strong_llm_provider str | None

复杂任务使用的后端;默认沿用 llm_provider。

None
strong_llm_model str | None

复杂任务使用的模型。None 表示仅使用基础模型。

None
context AgentContext | None

与数据准备 Agent 共享的数据和工作区上下文。

None
skill_manager SkillManager | None

Skill 注册表。交互式会话应将其自定义目录放在工作区中。

None

on_buffer_messages_added

on_buffer_messages_added(
    messages: list[Message], **coordinate: int
) -> None

Publish each system or user message when it enters the buffer.

参数:

名称 类型 描述 默认
messages list[Message]

Newly appended messages.

必需
**coordinate int

Optional R/C/L search coordinate.

{}

initialize_tools

initialize_tools(context: AgentContext) -> None

Initialize tools and attach the active hard-interrupt event.

prepare_tool_context

prepare_tool_context(
    tool_context: AgentContext,
) -> Iterator[AgentContext]

Add interaction resources to the tool context for the duration of a run.

参数:

名称 类型 描述 默认
tool_context AgentContext

Shared context used to initialize tools.

必需

产生:

类型 描述
AgentContext

Context enriched with a temporary workspace manager when enabled.

prepare_iteration

prepare_iteration(
    buffer: list[Message], R: int, L: int, C: int
) -> str | None

Apply queued human guidance before the prompt is constructed.

参数:

名称 类型 描述 默认
buffer list[Message]

Conversation history buffer.

必需
R int

One-based restart index.

必需
L int

One-based refinement-step index.

必需
C int

One-based conversation-branch index.

必需

返回:

类型 描述
str | None

str | None: The operation result.

build_data_refresh_message staticmethod

build_data_refresh_message(
    change: dict[str, Any],
) -> dict[str, str]

Turn a structured data revision into guidance for the next model turn.

finish_iteration

finish_iteration(
    buffer: list[Message], R: int, L: int, C: int
) -> str | None

Keep interactive runs open and yield tool-free responses to the human.

参数:

名称 类型 描述 默认
buffer list[Message]

Conversation history buffer.

必需
R int

One-based restart index.

必需
L int

One-based refinement-step index.

必需
C int

One-based conversation-branch index.

必需

返回:

类型 描述
str | None

str | None: The operation result.

build_response_followup_messages

build_response_followup_messages(
    response_list: list[ModelResponse],
    results_list: list[list[ToolCallResult]],
    *,
    R: int,
    L: int,
    C: int,
) -> list[Message]

Consume notices generated while receiving the current response.

create_initial_system_prompt

create_initial_system_prompt(
    restart_records: list[CandidateRecord],
) -> str

Create the interactive system prompt with capability-safe tool guidance.

参数:

名称 类型 描述 默认
restart_records list[CandidateRecord]

Ranked candidates used to set the next objective.

必需

返回:

类型 描述
str

Interactive system-prompt text.

normalize_system_prompt classmethod

normalize_system_prompt(prompt: str) -> str

Remove obsolete generated guidance that advertises workspace-only tools.

参数:

名称 类型 描述 默认
prompt str

Stored or newly submitted system prompt.

必需

返回:

类型 描述
str

System prompt without legacy workspace guidance. Capability-neutral guidance is

str

appended when the removed paragraph came from an older generated prompt.

customize_initial_prompts

customize_initial_prompts(
    messages: list[Message],
    *,
    X: dict[str, Any],
    y: dict[str, Any],
) -> list[Message]

Apply UI-provided descriptions and prompt overrides.

参数:

名称 类型 描述 默认
messages list[Message]

Initial system and user messages.

必需
X dict[str, Any]

Feature arrays keyed by variable name.

必需
y dict[str, Any]

Target arrays keyed by variable name.

必需

返回:

类型 描述
list[Message]

Customized initial messages.

request_llm

request_llm(
    prompt: list[Message], R: int, L: int, C: int
) -> tuple[list[ModelResponse], Usage]

Request the model while publishing frontend-neutral progress events.

参数:

名称 类型 描述 默认
prompt list[Message]

Prompt messages sent to the model.

必需
R int

One-based restart index.

必需
L int

One-based refinement-step index.

必需
C int

One-based conversation-branch index.

必需

返回:

类型 描述
tuple[list[ModelResponse], Usage]

Parsed responses and usage, including partial responses after interruption.

tool_schema

tool_schema(name: str) -> dict[str, Any]

Return the schema exposed by one initialized tool.

参数:

名称 类型 描述 默认
name str

Registered name.

必需

返回:

类型 描述
dict[str, Any]

dict[str, Any]: The operation result.

execute_action

execute_action(
    actions: list[ToolCall],
) -> list[ToolCallResult]

Execute tools serially with safe control boundaries and UI events.

参数:

名称 类型 描述 默认
actions list[ToolCall]

Tool calls to execute.

必需

返回:

类型 描述
list[ToolCallResult]

Tool results in call order.

collect_candidates

collect_candidates(
    *args: Any, **kwargs: Any
) -> list[CandidateRecord]

Update scientific state and publish its current ranked view.

参数:

名称 类型 描述 默认
*args Any

Arguments forwarded to the base candidate collector.

()
**kwargs Any

Keyword arguments forwarded to the base candidate collector.

{}

返回:

类型 描述
list[CandidateRecord]

Candidates ranked under the configured metric.

record_tool_calls

record_tool_calls(
    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.

参数:

名称 类型 描述 默认
tool_calls list[ToolCall]

Tool calls returned by the model.

必需
results list[ToolCallResult]

Result records to process.

必需
R int

One-based restart index.

必需
L int

One-based refinement-step index.

必需
C int

One-based conversation-branch index.

必需
forced bool

Whether the framework, rather than the model, initiated the call.

False

execute_action_parallel

execute_action_parallel(
    actions: list[ToolCall], max_workers: int
) -> list[ToolCallResult]

Reject parallel execution in interactive mode.

参数:

名称 类型 描述 默认
actions list[ToolCall]

Tool calls to execute.

必需
max_workers int

Maximum number of parallel workers.

必需

引发:

类型 描述
NotImplementedError

Always, because interactive workspace tools are not guaranteed to be read-only.

Core Types

sr_harness.core

Dependency-light domain types and runtime state for SRHarness.

ParentRelation module-attribute

ParentRelation = Literal[
    "continuation", "restart_seed", "context_merge"
]

__all__ module-attribute

__all__ = [
    "APICallResult",
    "AgentContext",
    "CandidateRecord",
    "ContextManifestError",
    "ParentLink",
    "ParentRelation",
    "SearchCoordinate",
    "SearchNode",
    "SearchResult",
    "SearchRunState",
    "ToolCall",
    "ToolCallResult",
    "ToolMetadata",
    "inspect_context_data",
    "json_value",
    "load_context_data",
    "update_context_data_descriptions",
]

APICallResult

APICallResult(gen: Iterator, parser: BaseParser = None)

Wrapper for LLM generator that captures the return value.

Example

api = OpenAIAPI(model='gpt-4o-mini') result = api("Hello", n=3) # Returns APICallResult for content, tool_call in result: ... print(content, tool_call) # Stream generated content and tool calls print(result.usage) # Access via property print(result.contents) # List of generated contents

usage property

usage: dict

Token & Price usage statistics.

返回:

名称 类型 描述
dict dict

The operation result.

return_value property

return_value: dict

Alias for the generator return value.

返回:

名称 类型 描述
dict dict

The operation result.

contents property

contents: dict

Raw API contents.

返回:

名称 类型 描述
dict dict

The operation result.

tool_calls property

tool_calls: list

Tool calls returned by the provider.

返回:

名称 类型 描述
list list

The operation result.

AgentContext

AgentContext(
    *,
    args: Namespace | None = None,
    data: dict[str, Any] | None = None,
    target: str | None = None,
    variable_descriptions: dict[str, str] | None = None,
    variable_axes: dict[str, tuple[str, ...]] | None = None,
    variable_structures: dict[str, str] | None = None,
    relation_names: set[str] | None = None,
    num_nodes: int | None = None,
    evaluator: DefaultEvaluator
    | object = _DEFAULT_EVALUATOR,
    workspace: str | Path | Any | None = None,
)

One authoritative context containing data, metadata, and runtime arguments.

参数:

名称 类型 描述 默认
args Namespace | None

Runtime configuration shared by agents, evaluators, and tools.

None
data dict[str, Any] | None

Arrays keyed by variable or axis name.

None
target str | None

Name of the current target variable.

None
variable_descriptions dict[str, str] | None

Human-readable descriptions keyed by data name.

None
variable_axes dict[str, tuple[str, ...]] | None

Axis names for every non-axis variable.

None
variable_structures dict[str, str] | None

Relation variable used by each structured variable.

None
relation_names set[str] | None

Names of graph or hypergraph relation arrays.

None
num_nodes int | None

Number of nodes for graph or hypergraph data.

None
evaluator DefaultEvaluator | object

Evaluator instance used to fit, score, and split formulas.

_DEFAULT_EVALUATOR
workspace str | Path | Any | None

Workspace path or an object exposing a path attribute.

None

train_split property

train_split: AgentContext

Return the cached training context, computing both splits if needed.

validation_split property

validation_split: AgentContext

Return the cached validation context, computing both splits if needed.

invalidate_splits

invalidate_splits() -> None

Discard cached training and validation context views.

with_data

with_data(data: dict[str, ndarray]) -> AgentContext

Create a context view over data while preserving runtime configuration.

参数:

名称 类型 描述 默认
data dict[str, ndarray]

Data mapping for the new context view.

必需

返回:

类型 描述
AgentContext

A context sharing arguments and evaluator configuration with this context.

axis_names

axis_names() -> tuple[str, ...]

Return axis-variable names in first-occurrence order.

variable_names

variable_names() -> tuple[str, ...]

Return names of non-axis variables in manifest order.

feature_names

feature_names() -> tuple[str, ...]

Return selected non-axis variables other than the target.

commit_context_data

commit_context_data(
    loaded: dict[str, Any],
) -> dict[str, Any]

Replace live context data with a validated loader result.

参数:

名称 类型 描述 默认
loaded dict[str, Any]

Mapping returned by :func:load_context_data.

必需

返回:

类型 描述
dict[str, Any]

New data revision and loaded variable names.

commit_data

commit_data(
    data: dict[str, Any],
    *,
    target: str,
    features: list[str] | None = None,
    variable_descriptions: dict[str, str] | None = None,
) -> dict[str, Any]

Commit an ordinary aligned data selection to the live context.

参数:

名称 类型 描述 默认
data dict[str, Any]

Available arrays keyed by column name.

必需
target str

Target column to retain.

必需
features list[str] | None

Feature columns to retain. Defaults to no features.

None
variable_descriptions dict[str, str] | None

Optional descriptions for retained columns.

None

返回:

类型 描述
dict[str, Any]

A summary containing revision, selection, columns, and row count.

add_features

add_features(
    features: dict[str, Any],
    *,
    descriptions: dict[str, str] | None = None,
) -> dict[str, Any]

Add aligned feature arrays while preserving the current target.

参数:

名称 类型 描述 默认
features dict[str, Any]

New feature arrays keyed by name.

必需
descriptions dict[str, str] | None

Optional descriptions for the new features.

None

返回:

类型 描述
dict[str, Any]

The commit summary produced for the updated data.

引发:

类型 描述
ValueError

If the context has no configured target.

update_selection

update_selection(
    *,
    target: str,
    features: list[str],
    variable_descriptions: dict[str, str] | None = None,
) -> dict[str, Any]

Select the variables used by symbolic regression.

参数:

名称 类型 描述 默认
target str

Target variable name.

必需
features list[str]

Feature variable names.

必需
variable_descriptions dict[str, str] | None

Description updates to apply before selection.

None

返回:

类型 描述
dict[str, Any]

New revision and selected target and features.

schema

schema() -> dict[str, Any]

Return a serializable description of the active context data.

ContextManifestError

Bases: ValueError

Raised when a context-data manifest cannot be validated.

CandidateRecord dataclass

CandidateRecord(
    formula: str,
    node_id: str,
    details: dict[str, Any] = dict(),
)

Candidate formula and its evaluation details.

complexity property

complexity: Any

Run the complexity operation.

返回:

名称 类型 描述
Any Any

The operation result.

split_metrics

split_metrics(split: str) -> dict[str, Any]

Run the split metrics operation.

参数:

名称 类型 描述 默认
split str

Data split name.

必需

返回:

类型 描述
dict[str, Any]

dict[str, Any]: The operation result.

metric

metric(name: str, split: str) -> Any

Run the metric operation.

参数:

名称 类型 描述 默认
name str

Registered name.

必需
split str

Data split name.

必需

返回:

名称 类型 描述
Any Any

The operation result.

to_dict

to_dict() -> dict[str, Any]

Return a serializable dictionary representation.

返回:

类型 描述
dict[str, Any]

dict[str, Any]: The operation result.

display_dict

display_dict() -> dict[str, Any]

Return a flattened view for UI rendering without mutating the record.

返回:

类型 描述
dict[str, Any]

dict[str, Any]: The operation result.

ParentLink(parent_node_id: str, relation: ParentRelation)

Typed link to a parent search node.

to_dict

to_dict() -> dict[str, str]

Return a serializable dictionary representation.

返回:

类型 描述
dict[str, str]

dict[str, str]: The operation result.

SearchCoordinate dataclass

SearchCoordinate(R: int, C: int, L: int, K: int)

Coordinates of one R-C-L-K search sample.

SearchNode dataclass

SearchNode(
    run_id: str,
    node_id: str,
    node_label: str,
    coordinate: SearchCoordinate,
    parents: tuple[ParentLink, ...],
    created_at: str,
    core: dict[str, Any],
    detail: dict[str, Any],
)

Recorded state for one search-tree node.

to_dict

to_dict(*, include_detail: bool = True) -> dict[str, Any]

Return a serializable dictionary representation.

参数:

名称 类型 描述 默认
include_detail bool

Whether to include detailed payloads.

True

返回:

类型 描述
dict[str, Any]

dict[str, Any]: The operation result.

SearchResult dataclass

SearchResult(
    status: Literal[
        "completed",
        "early_stopped",
        "interrupted",
        "failed",
    ],
    progress: str,
    candidates: list[CandidateRecord],
    pareto_front: list[int],
    best_candidate: int | None,
)

Final snapshot of one symbolic-regression run.

to_dict

to_dict() -> dict[str, Any]

Return a serializable dictionary representation.

返回:

类型 描述
dict[str, Any]

dict[str, Any]: The operation result.

SearchRunState

SearchRunState(
    save_path: str | Path | None,
    ranking_metric: str,
    larger_is_better: bool,
    agent_metadata: dict[str, Any] | None = None,
    run_id: str | None = None,
)

Authoritative in-memory state for one run, with optional persistence.

node_count property

node_count: int

Run the node count operation.

返回:

名称 类型 描述
int int

The operation result.

latest_coordinate property

latest_coordinate: SearchCoordinate | None

Return the coordinate of the most recently recorded search node.

返回:

类型 描述
SearchCoordinate | None

SearchCoordinate | None: The operation result.

now staticmethod

now() -> str

Run the now operation.

返回:

名称 类型 描述
str str

The operation result.

node_label staticmethod

node_label(R: int, C: int, L: int, K: int) -> str

Run the node label operation.

参数:

名称 类型 描述 默认
R int

One-based restart index.

必需
C int

One-based conversation-branch index.

必需
L int

One-based refinement-step index.

必需
K int

One-based local-sample index.

必需

返回:

名称 类型 描述
str str

The operation result.

node_id

node_id(R: int, C: int, L: int, K: int) -> str

Run the node id operation.

参数:

名称 类型 描述 默认
R int

One-based restart index.

必需
C int

One-based conversation-branch index.

必需
L int

One-based refinement-step index.

必需
K int

One-based local-sample index.

必需

返回:

名称 类型 描述
str str

The operation result.

parent_link(
    parent_node_id: str, relation: ParentRelation
) -> ParentLink

Run the parent link operation.

参数:

名称 类型 描述 默认
parent_node_id str

The parent node id value.

必需
relation ParentRelation

Relation expression that binds symbolic indices.

必需

返回:

名称 类型 描述
ParentLink ParentLink

The operation result.

register_iteration

register_iteration(
    response_list: list,
    results_list: list,
    parents: tuple[ParentLink, ...],
    prompt: list[dict[str, Any]],
    usage: dict[str, Any],
    R: int,
    L: int,
    C: int,
) -> None

Register iteration.

参数:

名称 类型 描述 默认
response_list list

Model responses for the current step.

必需
results_list list

Tool results aligned with model responses.

必需
parents tuple[ParentLink, ...]

Parent links for the new search nodes.

必需
prompt list[dict[str, Any]]

Prompt messages sent to the model.

必需
usage dict[str, Any]

Token and price usage information.

必需
R int

One-based restart index.

必需
L int

One-based refinement-step index.

必需
C int

One-based conversation-branch index.

必需

push_candidate

push_candidate(candidate: CandidateRecord) -> bool

Run the push candidate operation.

参数:

名称 类型 描述 默认
candidate CandidateRecord

The candidate value.

必需

返回:

名称 类型 描述
bool bool

The operation result.

update_diagnostics

update_diagnostics(
    formula: str, diagnostics: dict[str, Any]
) -> None

Update diagnostics.

参数:

名称 类型 描述 默认
formula str

Symbolic formula string.

必需
diagnostics dict[str, Any]

Diagnostic values to store.

必需

ranked_candidates

ranked_candidates() -> list[CandidateRecord]

Run the ranked candidates operation.

返回:

类型 描述
list[CandidateRecord]

list[CandidateRecord]: The operation result.

pareto_indices

pareto_indices(
    candidates: list[CandidateRecord] | None = None,
) -> list[int]

Run the pareto indices operation.

参数:

名称 类型 描述 默认
candidates list[CandidateRecord] | None

The candidates value.

None

返回:

类型 描述
list[int]

list[int]: The operation result.

result

result(status: str, progress: str) -> SearchResult

Run the result operation.

参数:

名称 类型 描述 默认
status str

Run completion status.

必需
progress str

Human-readable search progress.

必需

返回:

名称 类型 描述
SearchResult SearchResult

The operation result.

records

records(
    *, include_detail: bool = False
) -> list[dict[str, Any]]

Run the records operation.

参数:

名称 类型 描述 默认
include_detail bool

Whether to include detailed payloads.

False

返回:

类型 描述
list[dict[str, Any]]

list[dict[str, Any]]: The operation result.

export_state

export_state() -> dict[str, Any]

Return enough durable state to rebuild this run after a restart.

from_state classmethod

from_state(
    snapshot: dict[str, Any],
    save_path: str | Path | None = None,
) -> "SearchRunState"

Rebuild a run from :meth:export_state without replaying work.

node_record

node_record(node_id: str) -> dict[str, Any] | None

Run the node record operation.

参数:

名称 类型 描述 默认
node_id str

The node id value.

必需

返回:

类型 描述
dict[str, Any] | None

dict[str, Any] | None: The operation result.

ToolCall dataclass

ToolCall(
    name: str,
    params: dict,
    id: str | None = None,
    raw: Any = None,
    raw_str: str | None = None,
)

Normalized tool call emitted by LLM APIs and parsers.

ToolCallResult dataclass

ToolCallResult(
    ok: bool,
    result: Dict[str, Any],
    result_str: str,
    meta_data: Dict[str, Any],
)

Structured result returned by the tool execution boundary.

result retains the complete machine-readable value, while result_str is the bounded representation returned to the model.

get

get(key: str, default: Any = None) -> Any

Run the get operation.

参数:

名称 类型 描述 默认
key str

The key value.

必需
default Any

Fallback value.

None

返回:

名称 类型 描述
Any Any

The operation result.

ToolMetadata dataclass

ToolMetadata(
    name: str,
    description: str | None = None,
    parameters: Dict[str, Any] | None = None,
)

Description and parameter schema exposed for a tool.

description and parameters may be omitted so BaseTool can infer them from the implementation's signature and docstring.

inspect_context_data

inspect_context_data(
    directory: str | Path,
) -> dict[str, Any]

Return validation diagnostics without raising for manifest errors.

load_context_data

load_context_data(directory: str | Path) -> dict[str, Any]

Validate and load one manifest-backed context.data directory.

update_context_data_descriptions

update_context_data_descriptions(
    directory: str | Path, descriptions: dict[str, str]
) -> dict[str, Any]

Update variable and axis descriptions in manifest.json.

The complete store is validated before the edit. An atomic replacement is used when the directory permits creating entries. If the directory is read-only but manifest.json itself is writable, the existing file is updated in place, matching normal POSIX file-permission semantics. Because only existing string-valued description fields are changed, structural validity is preserved. The returned mapping matches :func:load_context_data.

json_value

json_value(value: Any) -> Any

Convert runtime values to standards-compliant JSON values.

参数:

名称 类型 描述 默认
value Any

Input value.

必需

返回:

名称 类型 描述
Any Any

The operation result.

Evaluators

sr_harness.evaluator

Evaluator contracts, implementations, loading, and reusable utilities.

ContextSplits module-attribute

ContextSplits: TypeAlias = dict[
    Literal["train", "validation"], AgentContext
]

MetricDict module-attribute

MetricDict: TypeAlias = dict[str, MetricValue]

MetricValue module-attribute

MetricValue: TypeAlias = float | int

__all__ module-attribute

__all__ = [
    "ContextSplits",
    "DefaultEvaluator",
    "GraphEvaluator",
    "load_custom_evaluator",
    "MetricDict",
    "MetricValue",
    "utils",
]

DefaultEvaluator

Default implementation and extension point for formula evaluation.

split classmethod

split(context: AgentContext) -> ContextSplits

Split a context into training and validation views.

参数:

名称 类型 描述 默认
context AgentContext

Complete unsplit agent context.

必需

返回:

类型 描述
ContextSplits

Training and validation contexts keyed by split name.

fit classmethod

fit(
    f: Expression, y: Expression, context: AgentContext
) -> Expression

Fit parameters in a general expression equality.

参数:

名称 类型 描述 默认
f Expression

Expression whose parameters will be fitted.

必需
y Expression

Expression providing target values.

必需
context AgentContext

Training context containing all referenced variables.

必需

返回:

类型 描述
Expression

A copy of f with fitted parameter values.

evaluate classmethod

evaluate(
    f: Expression, y: Expression, context: AgentContext
) -> MetricDict

Evaluate a general expression equality.

参数:

名称 类型 描述 默认
f Expression

Fitted expression to evaluate.

必需
y Expression

Expression providing target values.

必需
context AgentContext

Context containing all referenced variables.

必需

返回:

类型 描述
MetricDict

Numeric regression and complexity metrics.

fit_candidate classmethod

fit_candidate(
    f: Expression, context: AgentContext
) -> Expression

Fit an eligible candidate against the configured target variable.

参数:

名称 类型 描述 默认
f Expression

Candidate expression whose parameters will be fitted.

必需
context AgentContext

Training context with a configured target.

必需

返回:

类型 描述
Expression

A copy of f with fitted parameter values.

evaluate_candidate classmethod

evaluate_candidate(
    f: Expression, context: AgentContext
) -> MetricDict

Evaluate an eligible candidate against the configured target.

参数:

名称 类型 描述 默认
f Expression

Fitted candidate expression.

必需
context AgentContext

Context with a configured target.

必需

返回:

类型 描述
MetricDict

Numeric regression and complexity metrics.

GraphEvaluator

Bases: DefaultEvaluator

Evaluate variables with (..., N/E/H) graph-aligned dimensions.

fit classmethod

fit(
    f: Expression, y: Expression, context: AgentContext
) -> Expression

Fit an equality using graph-aware broadcast evaluation.

参数:

名称 类型 描述 默认
f Expression

Expression whose parameters will be fitted.

必需
y Expression

Expression providing graph-aligned target values.

必需
context AgentContext

Training context containing relation metadata.

必需

返回:

类型 描述
Expression

A copy of f with fitted parameter values.

evaluate classmethod

evaluate(
    f: Expression, y: Expression, context: AgentContext
) -> MetricDict

Evaluate an equality using graph-aware broadcast evaluation.

参数:

名称 类型 描述 默认
f Expression

Fitted expression to evaluate.

必需
y Expression

Expression providing graph-aligned target values.

必需
context AgentContext

Context containing relation metadata.

必需

返回:

类型 描述
MetricDict

Numeric regression and complexity metrics.

split classmethod

split(context: AgentContext) -> ContextSplits

Split sample-aligned graph data without slicing relation arrays.

参数:

名称 类型 描述 默认
context AgentContext

Complete graph or hypergraph context.

必需

返回:

类型 描述
ContextSplits

Training and validation context views.

Evaluator Utilities

sr_harness.evaluator.utils

Reusable evaluator infrastructure kept outside evaluator contracts.

AgentContext

AgentContext(
    *,
    args: Namespace | None = None,
    data: dict[str, Any] | None = None,
    target: str | None = None,
    variable_descriptions: dict[str, str] | None = None,
    variable_axes: dict[str, tuple[str, ...]] | None = None,
    variable_structures: dict[str, str] | None = None,
    relation_names: set[str] | None = None,
    num_nodes: int | None = None,
    evaluator: DefaultEvaluator
    | object = _DEFAULT_EVALUATOR,
    workspace: str | Path | Any | None = None,
)

One authoritative context containing data, metadata, and runtime arguments.

参数:

名称 类型 描述 默认
args Namespace | None

Runtime configuration shared by agents, evaluators, and tools.

None
data dict[str, Any] | None

Arrays keyed by variable or axis name.

None
target str | None

Name of the current target variable.

None
variable_descriptions dict[str, str] | None

Human-readable descriptions keyed by data name.

None
variable_axes dict[str, tuple[str, ...]] | None

Axis names for every non-axis variable.

None
variable_structures dict[str, str] | None

Relation variable used by each structured variable.

None
relation_names set[str] | None

Names of graph or hypergraph relation arrays.

None
num_nodes int | None

Number of nodes for graph or hypergraph data.

None
evaluator DefaultEvaluator | object

Evaluator instance used to fit, score, and split formulas.

_DEFAULT_EVALUATOR
workspace str | Path | Any | None

Workspace path or an object exposing a path attribute.

None

train_split property

train_split: AgentContext

Return the cached training context, computing both splits if needed.

validation_split property

validation_split: AgentContext

Return the cached validation context, computing both splits if needed.

invalidate_splits

invalidate_splits() -> None

Discard cached training and validation context views.

with_data

with_data(data: dict[str, ndarray]) -> AgentContext

Create a context view over data while preserving runtime configuration.

参数:

名称 类型 描述 默认
data dict[str, ndarray]

Data mapping for the new context view.

必需

返回:

类型 描述
AgentContext

A context sharing arguments and evaluator configuration with this context.

axis_names

axis_names() -> tuple[str, ...]

Return axis-variable names in first-occurrence order.

variable_names

variable_names() -> tuple[str, ...]

Return names of non-axis variables in manifest order.

feature_names

feature_names() -> tuple[str, ...]

Return selected non-axis variables other than the target.

commit_context_data

commit_context_data(
    loaded: dict[str, Any],
) -> dict[str, Any]

Replace live context data with a validated loader result.

参数:

名称 类型 描述 默认
loaded dict[str, Any]

Mapping returned by :func:load_context_data.

必需

返回:

类型 描述
dict[str, Any]

New data revision and loaded variable names.

commit_data

commit_data(
    data: dict[str, Any],
    *,
    target: str,
    features: list[str] | None = None,
    variable_descriptions: dict[str, str] | None = None,
) -> dict[str, Any]

Commit an ordinary aligned data selection to the live context.

参数:

名称 类型 描述 默认
data dict[str, Any]

Available arrays keyed by column name.

必需
target str

Target column to retain.

必需
features list[str] | None

Feature columns to retain. Defaults to no features.

None
variable_descriptions dict[str, str] | None

Optional descriptions for retained columns.

None

返回:

类型 描述
dict[str, Any]

A summary containing revision, selection, columns, and row count.

add_features

add_features(
    features: dict[str, Any],
    *,
    descriptions: dict[str, str] | None = None,
) -> dict[str, Any]

Add aligned feature arrays while preserving the current target.

参数:

名称 类型 描述 默认
features dict[str, Any]

New feature arrays keyed by name.

必需
descriptions dict[str, str] | None

Optional descriptions for the new features.

None

返回:

类型 描述
dict[str, Any]

The commit summary produced for the updated data.

引发:

类型 描述
ValueError

If the context has no configured target.

update_selection

update_selection(
    *,
    target: str,
    features: list[str],
    variable_descriptions: dict[str, str] | None = None,
) -> dict[str, Any]

Select the variables used by symbolic regression.

参数:

名称 类型 描述 默认
target str

Target variable name.

必需
features list[str]

Feature variable names.

必需
variable_descriptions dict[str, str] | None

Description updates to apply before selection.

None

返回:

类型 描述
dict[str, Any]

New revision and selected target and features.

schema

schema() -> dict[str, Any]

Return a serializable description of the active context data.

_regression_arrays

_regression_arrays(
    y_true: Any, y_pred: Any
) -> tuple[ndarray, ndarray]

calc_MSE

calc_MSE(y_true: Any, y_pred: Any) -> float

Calculate mean squared error.

参数:

名称 类型 描述 默认
y_true Any

Target values.

必需
y_pred Any

Predicted values broadcastable to y_true.

必需

返回:

类型 描述
float

Mean squared error over flattened broadcast arrays.

calc_RMSE

calc_RMSE(y_true: Any, y_pred: Any) -> float

Calculate root mean squared error.

参数:

名称 类型 描述 默认
y_true Any

Target values.

必需
y_pred Any

Predicted values broadcastable to y_true.

必需

返回:

类型 描述
float

Root mean squared error.

calc_MAE

calc_MAE(y_true: Any, y_pred: Any) -> float

Calculate mean absolute error.

参数:

名称 类型 描述 默认
y_true Any

Target values.

必需
y_pred Any

Predicted values broadcastable to y_true.

必需

返回:

类型 描述
float

Mean absolute error.

calc_MAPE

calc_MAPE(y_true: Any, y_pred: Any) -> float

Calculate mean absolute percentage error over nonzero targets.

参数:

名称 类型 描述 默认
y_true Any

Target values.

必需
y_pred Any

Predicted values broadcastable to y_true.

必需

返回:

类型 描述
float

Mean absolute percentage error, or NaN when every target is zero.

calc_R2

calc_R2(y_true: Any, y_pred: Any) -> float

Calculate the coefficient of determination.

参数:

名称 类型 描述 默认
y_true Any

Target values.

必需
y_pred Any

Predicted values broadcastable to y_true.

必需

返回:

类型 描述
float

The R-squared score.

calc_AIC

calc_AIC(
    y_true: Any, y_pred: Any, num_parameters: int
) -> float

Calculate the Gaussian Akaike information criterion.

参数:

名称 类型 描述 默认
y_true Any

Target values.

必需
y_pred Any

Predicted values broadcastable to y_true.

必需
num_parameters int

Number of fitted parameters.

必需

返回:

类型 描述
float

AIC value, negative infinity for an exact fit, or NaN for invalid loss.

calc_BIC

calc_BIC(
    y_true: Any, y_pred: Any, num_parameters: int
) -> float

Calculate the Gaussian Bayesian information criterion.

参数:

名称 类型 描述 默认
y_true Any

Target values.

必需
y_pred Any

Predicted values broadcastable to y_true.

必需
num_parameters int

Number of fitted parameters.

必需

返回:

类型 描述
float

BIC value, negative infinity for an exact fit, or NaN for invalid loss.

calc_PearsonR

calc_PearsonR(y_true: Any, y_pred: Any) -> float

Calculate Pearson's correlation coefficient over finite pairs.

参数:

名称 类型 描述 默认
y_true Any

Target values.

必需
y_pred Any

Predicted values broadcastable to y_true.

必需

返回:

类型 描述
float

Pearson correlation, or NaN when fewer than two finite pairs exist.

calc_SpearmanR

calc_SpearmanR(y_true: Any, y_pred: Any) -> float

Calculate Spearman's rank correlation over finite pairs.

参数:

名称 类型 描述 默认
y_true Any

Target values.

必需
y_pred Any

Predicted values broadcastable to y_true.

必需

返回:

类型 描述
float

Spearman correlation, or NaN when fewer than two finite pairs exist.

calc_complexity

calc_complexity(expression: Expression) -> int

Count nodes in a symbolic expression.

参数:

名称 类型 描述 默认
expression Expression

Symbolic expression to inspect.

必需

返回:

类型 描述
int

Expression node count.

regression_metrics

regression_metrics(
    expression: Expression, y_true: Any, y_pred: Any
) -> dict[str, float | int]

Calculate the standard regression metric bundle.

参数:

名称 类型 描述 默认
expression Expression

Fitted expression used for complexity and parameter counts.

必需
y_true Any

Target values.

必需
y_pred Any

Predicted values.

必需

返回:

类型 描述
dict[str, float | int]

Numeric prediction, information-criterion, correlation, and complexity metrics.

select_random_indices

select_random_indices(
    *, seed: int, n_samples: int, n_train: int
) -> tuple[ndarray, ndarray]

Select reproducible random training and validation indices.

参数:

名称 类型 描述 默认
seed int

Random seed.

必需
n_samples int

Total sample count.

必需
n_train int

Number of training samples.

必需

返回:

类型 描述
tuple[ndarray, ndarray]

Training and validation index arrays.

select_OOD_indices

select_OOD_indices(
    *, seed: int, n_samples: int, n_train: int, value: Any
) -> tuple[ndarray, ndarray]

Select an ordered out-of-distribution split.

参数:

名称 类型 描述 默认
seed int

Seed used to break ties reproducibly.

必需
n_samples int

Total sample count.

必需
n_train int

Number of low-ranked training samples.

必需
value Any

One-dimensional ordering variable.

必需

返回:

类型 描述
tuple[ndarray, ndarray]

Training and validation index arrays.

split_indices

split_indices(
    context: AgentContext, *, chronological: bool = False
) -> tuple[ndarray, ndarray] | None

Select split indices according to evaluator arguments.

参数:

名称 类型 描述 默认
context AgentContext

Unsplit agent context.

必需
chronological bool

Whether to preserve input order rather than use configured random or OOD splitting.

False

返回:

类型 描述
tuple[ndarray, ndarray] | None

Training and validation indices, or None when splitting is disabled.

split_aligned_context

split_aligned_context(
    context: AgentContext, *, chronological: bool = False
) -> dict[str, AgentContext]

Split every aligned context array along its leading dimension.

参数:

名称 类型 描述 默认
context AgentContext

Unsplit agent context.

必需
chronological bool

Whether to preserve input order.

False

返回:

类型 描述
dict[str, AgentContext]

Training and validation context views.

integrate_ODE

integrate_ODE(
    f: Expression,
    context: AgentContext,
    *,
    time: str = "t",
    state: str = "x",
) -> ndarray

Integrate a one-dimensional ODE over observed sample times.

参数:

名称 类型 描述 默认
f Expression

Fitted derivative expression.

必需
context AgentContext

Context containing time and observed state arrays.

必需
time str

Time-variable name.

't'
state str

State-variable name.

'x'

返回:

类型 描述
ndarray

Integrated state values at the observed times.

calc_trajectory_rollout_RMSE

calc_trajectory_rollout_RMSE(
    f: Expression,
    context: AgentContext,
    *,
    time: str = "t",
    state: str = "x",
) -> float

Calculate trajectory RMSE after integrating a derivative expression.

参数:

名称 类型 描述 默认
f Expression

Fitted derivative expression.

必需
context AgentContext

Context containing time and observed state arrays.

必需
time str

Time-variable name.

't'
state str

State-variable name.

'x'

返回:

类型 描述
float

RMSE between observed and integrated state trajectories.

Interaction Runtime

sr_harness.runtime

Components that coordinate a live SRHarness run.

InteractionAction module-attribute

InteractionAction: TypeAlias = Literal[
    "message", "pause", "force_pause"
]

InteractionEventKind module-attribute

InteractionEventKind: TypeAlias = Literal[
    "prompt_added",
    "context",
    "assistant_started",
    "assistant_delta",
    "assistant_completed",
    "assistant_failed",
    "tool_started",
    "tool_completed",
    "settings_applied",
    "settings_failed",
    "workspace_changed",
    "execution_completed",
    "execution_failed",
    "command_received",
    "state_changed",
    "search_position_changed",
    "topk_updated",
]

InteractionState module-attribute

InteractionState: TypeAlias = Literal[
    "idle", "running", "pausing", "interrupting", "paused"
]

SRInteractionAction module-attribute

SRInteractionAction: TypeAlias = Literal[
    "message", "pause", "force_pause", "next_c", "next_r"
]

__all__ module-attribute

__all__ = [
    "InteractionAction",
    "InteractionEventKind",
    "InteractionManager",
    "InteractionState",
    "ModelRoute",
    "ModelRouter",
    "PendingMessage",
    "SRInteractionAction",
    "SRInteractionManager",
    "SandboxResult",
    "SandboxRunner",
    "get_sandbox_runner",
    "Workspace",
]

InteractionManager

InteractionManager(*, event_capacity: int = 1000)

Own the controls and observable event stream of exactly one agent.

参数:

名称 类型 描述 默认
event_capacity int

Maximum number of retained timeline events.

1000

state property

Return the authoritative execution state.

返回:

类型 描述
InteractionState

Current interaction state.

is_interrupting property

is_interrupting: bool

Return whether the active operation should abort promptly.

返回:

类型 描述
bool

Whether a force-pause request is interrupting active work.

cancellation_signal property

cancellation_signal: _CancellationSignal

Expose a read-only Event-like cancellation adapter to tools.

返回:

类型 描述
_CancellationSignal

Object exposing is_set() for cancellation-aware tools.

status

status() -> dict[str, Any]

Return a serializable control snapshot.

返回:

类型 描述
dict[str, Any]

Current state, pending-input counts, event cursor, and server time.

command

command(
    action: InteractionAction, message: str | None = None
) -> dict[str, Any]

Apply a user control command to this agent.

参数:

名称 类型 描述 默认
action InteractionAction

Message, pause, or force-pause command.

必需
message str | None

User guidance required by the message action.

None

返回:

类型 描述
dict[str, Any]

Control snapshot after applying the command.

引发:

类型 描述
ValueError

If the action is invalid or a message is empty.

request_pause

request_pause() -> None

Request a quiet pause, such as after a tool-free response.

start_agent_execution

start_agent_execution() -> list[PendingMessage]

Enter running state and consume messages that start this execution.

返回:

类型 描述
list[PendingMessage]

Messages queued before execution started.

引发:

类型 描述
RuntimeError

If the manager is not idle.

finish_agent_execution

finish_agent_execution() -> None

Mark a naturally completed agent execution as idle.

引发:

类型 描述
RuntimeError

If execution is paused at a boundary.

wait

wait() -> Iterator[list[PendingMessage]]

Wait at a safe boundary and yield queued messages.

产生:

类型 描述
list[PendingMessage]

Messages to insert before the next model request.

引发:

类型 描述
RuntimeError

If no agent execution is active.

cancellable

cancellable(cancel: Callable[[], None]) -> Iterator[None]

Register cancellation for the current blocking operation.

参数:

名称 类型 描述 默认
cancel Callable[[], None]

Callback that promptly interrupts the active operation.

必需

产生:

类型 描述
None

Control while the callback is registered.

引发:

类型 描述
RuntimeError

If another cancellable operation is already active.

publish_event

publish_event(
    kind: InteractionEventKind, payload: Mapping[str, Any]
) -> dict[str, Any]

Append one observable event to this agent's timeline.

参数:

名称 类型 描述 默认
kind InteractionEventKind

Supported event kind.

必需
payload Mapping[str, Any]

JSON-serializable event data.

必需

返回:

类型 描述
dict[str, Any]

Stored event with sequence, identifier, and timestamp.

引发:

类型 描述
ValueError

If kind is unsupported.

get_recent_events

get_recent_events(
    after_sequence: int = 0,
) -> dict[str, Any]

Return retained events newer than a consumer-owned sequence cursor.

参数:

名称 类型 描述 默认
after_sequence int

Last sequence already consumed by the caller.

0

返回:

类型 描述
dict[str, Any]

Event batch and cursor-reset or truncation metadata.

export_state

export_state() -> dict[str, Any]

Return the durable portion of this manager's state.

返回:

类型 描述
dict[str, Any]

Versioned interaction snapshot without runtime locks or callbacks.

restore_state

restore_state(snapshot: Mapping[str, Any]) -> bool

Restore durable state and interrupt work that died with the process.

Runtime callbacks and locks are deliberately never restored.

参数:

名称 类型 描述 默认
snapshot Mapping[str, Any]

State returned by :meth:export_state.

必需

返回:

类型 描述
bool

Whether in-flight work was converted into an interruption event.

PendingMessage dataclass

PendingMessage(content: str, created_at: float)

A user message waiting to be inserted at an agent boundary.

SRInteractionManager

SRInteractionManager(*, event_capacity: int = 1000)

Bases: InteractionManager

Interaction manager with symbolic-regression branch commands.

command

command(
    action: SRInteractionAction, message: str | None = None
) -> dict[str, Any]

Apply a common command or queue an SR branch transition.

参数:

名称 类型 描述 默认
action SRInteractionAction

Common interaction action or next_c/next_r.

必需
message str | None

User guidance for a message action.

None

返回:

类型 描述
dict[str, Any]

Control snapshot after applying the command.

consume_search_transition

consume_search_transition() -> (
    Literal["next_c", "next_r"] | None
)

Consume the newest queued branch transition.

返回:

类型 描述
Literal['next_c', 'next_r'] | None

Queued transition, or None when no transition is pending.

status

status() -> dict[str, Any]

Include the pending SR branch transition in the control snapshot.

返回:

类型 描述
dict[str, Any]

Common control snapshot with pending_transition.

export_state

export_state() -> dict[str, Any]

Include pending search transitions in the durable snapshot.

返回:

类型 描述
dict[str, Any]

Versioned interaction snapshot with symbolic-search transitions.

restore_state

restore_state(snapshot: Mapping[str, Any]) -> bool

Restore common state plus queued symbolic-search transitions.

参数:

名称 类型 描述 默认
snapshot Mapping[str, Any]

State returned by :meth:export_state.

必需

返回:

类型 描述
bool

Whether in-flight work was converted into an interruption event.

ModelRoute dataclass

ModelRoute(
    tier: str,
    provider: str,
    model: str,
    score: int,
    reason: str,
)

Selected provider/model route and its rationale.

ModelRouter

ModelRouter(
    *,
    enabled: bool,
    base_provider: str,
    base_model: str,
    strong_provider: str | None = None,
    strong_model: str | None = None,
)

Choose a cheap base model or an optional stronger model per request.

has_strong_backend property

has_strong_backend: bool

Run the has strong backend operation.

返回:

名称 类型 描述
bool bool

The operation result.

assess

assess(
    task: str, feature_count: int
) -> tuple[int, list[str]]

Run the assess operation.

参数:

名称 类型 描述 默认
task str

The task value.

必需
feature_count int

The feature count value.

必需

返回:

类型 描述
tuple[int, list[str]]

tuple[int, list[str]]: The operation result.

route

route(
    *,
    task_score: int,
    task_reasons: list[str],
    refinement_step: int,
) -> ModelRoute

Run the route operation.

参数:

名称 类型 描述 默认
task_score int

The task score value.

必需
task_reasons list[str]

The task reasons value.

必需
refinement_step int

The refinement step value.

必需

返回:

名称 类型 描述
ModelRoute ModelRoute

The operation result.

SandboxResult dataclass

SandboxResult(
    exit_code: int,
    stdout: str,
    stderr: str,
    duration_seconds: float,
    cpu_seconds: float,
    peak_memory_bytes: int,
)

Observable result of executing a Python program in the sandbox.

参数:

名称 类型 描述 默认
exit_code int

Program exit status; zero denotes successful execution.

必需
stdout str

Captured standard output.

必需
stderr str

Captured standard error.

必需
duration_seconds float

Wall-clock execution duration in seconds.

必需
cpu_seconds float

User and system CPU time consumed by the worker.

必需
peak_memory_bytes int

Peak resident set size reported by the worker.

必需

SandboxRunner

SandboxRunner()

Execute Python code with optional workspace access in the OS sandbox.

run

run(
    code: str,
    *,
    stdin: str = "",
    workspace: Workspace | str | Path | None = None,
    timeout_seconds: int = 30,
    memory_limit_mb: int = 1024,
    output_limit_bytes: int = 64 * 1024,
    interruption_event: Event | None = None,
) -> SandboxResult

Execute a Python program and capture its observable process result.

参数:

名称 类型 描述 默认
code str

Python source code to execute.

必需
stdin str

Text exposed as standard input.

''
workspace Workspace | str | Path | None

Optional working directory. When omitted, user code receives no persistent filesystem access. A managed workspace also enforces its mount and lock policies.

None
timeout_seconds int

Wall-clock timeout.

30
memory_limit_mb int

Address-space memory limit in MB.

1024
output_limit_bytes int

Per-stream capture limit for standard output and error.

64 * 1024
interruption_event Event | None

Optional signal requesting prompt interruption.

None

返回:

类型 描述
SandboxResult

Captured process output and resource usage.

Workspace

Workspace(path: str | Path)

Manage a writable workspace with explicitly registered read-only inputs.

Create or open a workspace.

参数:

名称 类型 描述 默认
path str | Path

Existing or new workspace root. The caller owns the directory and decides where it is created and when it is removed.

必需

path property

path: Path

Return the workspace root.

mount_map property

mount_map: dict[Path, Path]

Return logical workspace mount points mapped to their host sources.

lock_rules property

lock_rules: dict[str, bool]

Return explicit lock overrides keyed by workspace-relative paths.

has_locks property

has_locks: bool

Return whether any path is effectively protected by a lock rule.

mount_mode

mount_mode(
    path: str | Path,
) -> Literal["read-only", "read-write"] | None

Return the registered mount mode containing a logical workspace path.

参数:

名称 类型 描述 默认
path str | Path

Absolute or workspace-relative logical path.

必需

返回:

类型 描述
Literal['read-only', 'read-write'] | None

"read-only" or "read-write" for a mounted path, otherwise

Literal['read-only', 'read-write'] | None

None.

is_locked

is_locked(path: str | Path) -> bool

Return the effective lock state after applying the nearest override.

contains_locked_paths

contains_locked_paths(path: str | Path) -> bool

Return whether a path is or contains an explicitly locked subtree.

set_locked

set_locked(relative_path: str, locked: bool) -> Path

Set an explicit lock rule on a workspace file or directory tree.

参数:

名称 类型 描述 默认
relative_path str

Workspace-relative file or directory path.

必需
locked bool

Lock the path when true or explicitly unlock it when false.

必需

返回:

类型 描述
Path

The affected workspace path.

引发:

类型 描述
ValueError

If the path is invalid, missing, or belongs to a mounted input.

load_lock_rules

load_lock_rules(rules: dict[str, bool]) -> None

Replace lock overrides from persisted workspace state.

参数:

名称 类型 描述 默认
rules dict[str, bool]

Workspace-relative paths mapped to explicit lock states.

必需

resolve

resolve(
    relative_path: str,
    *,
    access: Literal[
        "read", "write", "create", "remove"
    ] = "read",
) -> Path | None

Resolve a safe workspace-relative path.

参数:

名称 类型 描述 默认
relative_path str

Relative path supplied by the caller.

必需
access Literal['read', 'write', 'create', 'remove']

Intended operation. write changes existing content, create adds a new entry, and remove deletes, moves, or replaces an existing entry.

'read'

返回:

类型 描述
Path | None

The resolved path, or None when the requested access is invalid.

mount

mount(source: str | Path, *, readonly: bool = True) -> Path

Expose a host file or directory through a registered link.

参数:

名称 类型 描述 默认
source str | Path

Existing host file or directory.

必需
readonly bool

Whether workspace operations and sandboxed code may modify it.

True

返回:

类型 描述
Path

The logical link inside the workspace.

iter_files

iter_files() -> Iterator[tuple[Path, Path]]

Yield logical and resolved paths for every workspace file.

get_sandbox_runner

get_sandbox_runner() -> SandboxRunner

Return the process-wide sandbox runner.

Model APIs

sr_harness.api

ToolList module-attribute

ToolList = list[BaseTool | type[BaseTool]]

ToolParserName module-attribute

ToolParserName = Literal['text', 'json', 'xml', 'openai']

__all__ module-attribute

__all__ = [
    "APICallResult",
    "BaseAPI",
    "DeepSeekAPI",
    "GeminiAPI",
    "LMStudioAPI",
    "ManualAPI",
    "ModelResponseTruncatedError",
    "OpenAIAPI",
    "OpenRouterAPI",
    "SiliconFlowAPI",
    "ToolList",
    "ToolParserName",
]

BaseAPI

BaseAPI(
    model: str | None = None,
    tool_list: ToolList | None = None,
    tool_parser_name: ToolParserName = "text",
    environment: Mapping[str, str] | None = None,
)

Bases: ABC, FactoryMixin

Common request, parser, and tool-call behavior for LLM providers.

tool_description_text cached property

tool_description_text: str

Format available tools for a model using a text-based parser.

返回:

名称 类型 描述
str str

The operation result.

tool_description_json cached property

tool_description_json: List[Dict]

Build OpenAI-compatible native function descriptions.

返回:

类型 描述
List[Dict]

List[Dict]: The operation result.

getenv

getenv(name: str, default: str | None = None) -> str | None

Read a session-scoped provider setting before the process environment.

require_env

require_env(name: str) -> str

Return a required session-scoped provider setting.

cancel

cancel() -> None

Request cancellation when a provider offers no stronger primitive.

build_parser

build_parser(parser: ToolParserName) -> BaseParser | None

Build parser.

参数:

名称 类型 描述 默认
parser ToolParserName

Argument parser to configure.

必需

返回:

类型 描述
BaseParser | None

BaseParser | None: The operation result.

add_tool_description

add_tool_description(
    messages: List[Dict[str, str]],
) -> List[Dict[str, str]]

Add text-formatted tool instructions to the leading system message.

参数:

名称 类型 描述 默认
messages List[Dict[str, str]]

Conversation messages in provider-compatible order.

必需

返回:

类型 描述
List[Dict[str, str]]

List[Dict[str, str]]: The operation result.

normalize_openai_tool_calls

normalize_openai_tool_calls(
    tool_calls: List[Any],
) -> List[ToolCall]

Normalize provider-native function calls into internal ToolCall objects.

参数:

名称 类型 描述 默认
tool_calls List[Any]

Tool calls returned by the model.

必需

返回:

类型 描述
List[ToolCall]

List[ToolCall]: The operation result.

ModelResponseTruncatedError

ModelResponseTruncatedError(
    message: str,
    *,
    partial_message: dict[str, Any],
    tool_calls: list[ToolCall],
    usage: dict[str, dict[str, int | float]],
    sample: int,
)

Bases: RuntimeError

Report a length-limited response while preserving its partial message.

参数:

名称 类型 描述 默认
message str

Human-readable explanation of the truncation.

必需
partial_message dict[str, Any]

Provider response accumulated before truncation.

必需
tool_calls list[ToolCall]

Tool calls parsed from the partial response.

必需
usage dict[str, dict[str, int | float]]

Token and price usage reported for the truncated response.

必需
sample int

One-based local-sample index that was truncated.

必需

APICallResult

APICallResult(gen: Iterator, parser: BaseParser = None)

Wrapper for LLM generator that captures the return value.

Example

api = OpenAIAPI(model='gpt-4o-mini') result = api("Hello", n=3) # Returns APICallResult for content, tool_call in result: ... print(content, tool_call) # Stream generated content and tool calls print(result.usage) # Access via property print(result.contents) # List of generated contents

usage property

usage: dict

Token & Price usage statistics.

返回:

名称 类型 描述
dict dict

The operation result.

return_value property

return_value: dict

Alias for the generator return value.

返回:

名称 类型 描述
dict dict

The operation result.

contents property

contents: dict

Raw API contents.

返回:

名称 类型 描述
dict dict

The operation result.

tool_calls property

tool_calls: list

Tool calls returned by the provider.

返回:

名称 类型 描述
list list

The operation result.

ManualAPI

ManualAPI(model='manual', save_path=None, **kwargs)

Bases: BaseAPI

Interactive manual-response provider adapter.

OpenAIAPI

OpenAIAPI(model: str = 'gpt-5-mini', **kwargs: Any)

Bases: BaseAPI

OpenAI-compatible provider adapter.

build_native_tool_description

build_native_tool_description(
    use_chat_completions: bool = False,
) -> List[Dict]

Build native tool description.

参数:

名称 类型 描述 默认
use_chat_completions bool

The use chat completions value.

False

返回:

类型 描述
List[Dict]

List[Dict]: The operation result.

create_responses

create_responses(
    messages: List[Dict[str, str]],
    n: int = 1,
    max_tokens: int = 4096,
    temperature: float = 1.0,
    top_p: float = 1.0,
) -> Generator[str, None, Dict]

Create responses.

参数:

名称 类型 描述 默认
messages List[Dict[str, str]]

Conversation messages in provider-compatible order.

必需
n int

The n value.

1
max_tokens int

The max tokens value.

4096
temperature float

The temperature value.

1.0
top_p float

The top p value.

1.0

返回:

类型 描述
Dict

Generator[str, None, Dict]: The operation result.

create_chat_completions

create_chat_completions(
    messages: List[Dict[str, str]],
    n: int = 1,
    max_tokens: int = 4096,
    temperature: float = 1.0,
    top_p: float = 1.0,
) -> Generator[str, None, Dict]

Create chat completions.

参数:

名称 类型 描述 默认
messages List[Dict[str, str]]

Conversation messages in provider-compatible order.

必需
n int

The n value.

1
max_tokens int

The max tokens value.

4096
temperature float

The temperature value.

1.0
top_p float

The top p value.

1.0

返回:

类型 描述
Dict

Generator[str, None, Dict]: The operation result.

parse_usage

parse_usage(response: Response) -> Dict

Parse usage.

参数:

名称 类型 描述 默认
response Response

Provider response object.

必需

返回:

名称 类型 描述
Dict Dict

The operation result.

parse_chat_completions_usage

parse_chat_completions_usage(
    response: ChatCompletion,
) -> Dict

Parse chat completions usage.

参数:

名称 类型 描述 默认
response ChatCompletion

Provider response object.

必需

返回:

名称 类型 描述
Dict Dict

The operation result.

GeminiAPI

GeminiAPI(model: str = 'gemini-2.5-pro', **kwargs: Any)

Bases: BaseAPI

Google Gemini provider adapter.

DeepSeekAPI

DeepSeekAPI(model: str = 'deepseek-chat', **kwargs: Any)

Bases: BaseAPI

DeepSeek provider adapter.

OpenRouterAPI

OpenRouterAPI(
    model: str = "qwen/qwen3.6-plus", **kwargs: Any
)

Bases: BaseAPI

OpenRouter provider adapter.

LMStudioAPI

LMStudioAPI(
    model: str = "qwen_qwen3-4b-instruct-2507",
    **kwargs: Any,
)

Bases: 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.

normalize_endpoint staticmethod

normalize_endpoint(endpoint: str) -> str

Return the OpenAI-compatible chat-completions URL.

参数:

名称 类型 描述 默认
endpoint str

The endpoint value.

必需

返回:

名称 类型 描述
str str

The operation result.

SiliconFlowAPI

SiliconFlowAPI(model: str = 'Qwen3-8B', **kwargs: Any)

Bases: BaseAPI

SiliconFlow provider adapter.

qwen3_8b

qwen3_8b(
    url: str,
    headers: dict[str, str],
    payload: dict[str, Any],
) -> Generator[str, None, Dict]

Run the qwen3 8b operation.

参数:

名称 类型 描述 默认
url str

The url value.

必需
headers dict[str, str]

The headers value.

必需
payload dict[str, Any]

Serializable event payload.

必需

返回:

类型 描述
Dict

Generator[str, None, Dict]: The operation result.

deepseek_v3

deepseek_v3(
    url: str,
    headers: dict[str, str],
    payload: dict[str, Any],
) -> Generator[str, None, Dict]

Run the deepseek v3 operation.

参数:

名称 类型 描述 默认
url str

The url value.

必需
headers dict[str, str]

The headers value.

必需
payload dict[str, Any]

Serializable event payload.

必需

返回:

类型 描述
Dict

Generator[str, None, Dict]: The operation result.

Tools

sr_harness.tools

工具模块。

所有工具都应继承自 BaseTool,并实现 execute 方法,详见本目录下的 README.md

__all__ module-attribute

__all__ = [
    "BaseTool",
    "CodeExecutorTool",
    "ConstantFitTool",
    "CreateSkill",
    "EditSkill",
    "EditTool",
    "EICTool",
    "EvaluateCodeTool",
    "EvaluateTool",
    "HarmonicInteractionFitTool",
    "LLMTool",
    "ModelTestTool",
    "ND2Tool",
    "PDFReadTool",
    "PolynomialFitTool",
    "PowerLawFitTool",
    "PropertyPredictorTool",
    "PySRTool",
    "RationalFitTool",
    "ReadSkill",
    "ReadSourceTool",
    "RelationshipAnalysisTool",
    "SINDyTool",
    "SR4MDLTool",
    "StatisticsTool",
    "SubagentTool",
    "SubmitFormulaTool",
    "ToolCallResult",
    "ToolMetadata",
    "ToolRunAbort",
    "ValidateContextDataTool",
    "ValidateEvaluatorTool",
    "WebFetchTool",
    "WebSearchTool",
    "WorkspaceCodeExecutorTool",
    "WorkspaceShellTool",
]

ToolCallResult dataclass

ToolCallResult(
    ok: bool,
    result: Dict[str, Any],
    result_str: str,
    meta_data: Dict[str, Any],
)

Structured result returned by the tool execution boundary.

result retains the complete machine-readable value, while result_str is the bounded representation returned to the model.

get

get(key: str, default: Any = None) -> Any

Run the get operation.

参数:

名称 类型 描述 默认
key str

The key value.

必需
default Any

Fallback value.

None

返回:

名称 类型 描述
Any Any

The operation result.

ToolMetadata dataclass

ToolMetadata(
    name: str,
    description: str | None = None,
    parameters: Dict[str, Any] | None = None,
)

Description and parameter schema exposed for a tool.

description and parameters may be omitted so BaseTool can infer them from the implementation's signature and docstring.

BaseTool

BaseTool(
    context: AgentContext | None = None, **values: Any
)

Bases: ABC, FactoryMixin

工具基类。所有工具都应继承此类,并设置 / 实现以下字段和方法: - metadata: ToolMetadata 实例,提供工具的名称、描述和参数 schema(若不提供则尝试自动推断) - execute(): 工具的核心执行方法,接受 LLM 生成的参数并返回结果字典。工具的 execute 方法应该尽量保持参数简单,复杂的上下文信息(如数据)可以通过工具实例的 context 属性传入。 - format_result_dict(): 可选的类方法,用于将 execute 的结果字典格式化为字符串,供 LLM 阅读。默认实现是直接转换为字符串,不同工具可以根据需要重写此方法以提供更友好的结果展示。

context 中传入一些工具执行时需要的上下文信息,如数据、模型等,这些信息不适合放在 execute 的参数列表中让 LLM 生成

get_doc classmethod

get_doc() -> dict[str, str] | None

Return optional documentation to expose as a runtime skill.

execute abstractmethod

execute() -> Dict[str, Any]

Execute the tool and return its result.

The parameters of this method are generated by the LLM and should therefore remain simple. Pass complex runtime context, such as data, through the tool instance's context attribute. Implementations must be safe for concurrent process or thread execution.

The text before Args supplies metadata.description; argument descriptions supply the parameter schema descriptions. The signature and type hints supply its JSON schema. Automatic inference supports common scalar, list, and dictionary types. Define ToolMetadata.parameters explicitly for more complex schemas.

返回:

类型 描述
Dict[str, Any]

A structured result dictionary.

format_result_dict classmethod

format_result_dict(result: Dict[str, Any]) -> str

Format a tool result as text for the language model.

Subclasses may override this method to provide a clearer presentation.

参数:

名称 类型 描述 默认
result Dict[str, Any]

Structured result returned by execute.

必需

返回:

类型 描述
str

Text to append to the model conversation.

cancel

cancel() -> None

Request cancellation when a tool offers no stronger primitive.

normalize_formula classmethod

normalize_formula(
    eq: str, *, strip_modules: bool = True
) -> str

Validate and normalize an agent-provided formula before parsing it.

参数:

名称 类型 描述 默认
eq str

Formula text supplied by the agent.

必需
strip_modules bool

Whether to remove supported module prefixes.

True

返回:

类型 描述
str

The normalized formula text.

parse_formula classmethod

parse_formula(eq: str) -> Expression

Normalize and parse a formula with constants supported by all tools.

参数:

名称 类型 描述 默认
eq str

Formula text supplied by the agent.

必需

返回:

类型 描述
Expression

The parsed symbolic expression.

truncate_result_str classmethod

truncate_result_str(text: str) -> str

Bound text sent to the LLM while preserving the full raw result.

参数:

名称 类型 描述 默认
text str

Tool-result text to limit.

必需

返回:

类型 描述
str

The original text or a length-limited prefix with a truncation note.

to_tool_list classmethod

to_tool_list(
    tools_used: list[str] | None = None,
) -> list[dict]

Load OpenAI-compatible function-tool definitions.

参数:

名称 类型 描述 默认
tools_used list[str] | None

Tool names to include, or None for all registered tools.

None

返回:

类型 描述
list[dict]

Function-tool definitions in OpenAI-compatible format.

load_tool_list classmethod

load_tool_list(
    tools_used: list[str] | None = None,
) -> list[dict]

Load tool metadata for text and JSON parsers.

参数:

名称 类型 描述 默认
tools_used list[str] | None

Tool names to include, or None for all registered tools.

None

返回:

类型 描述
list[dict]

Names, descriptions, and parameter schemas for the selected tools.

load_tool_classes classmethod

load_tool_classes(
    tools_used: list[str] | None = None,
) -> list[type["BaseTool"]]

Load tool classes for native function calling.

参数:

名称 类型 描述 默认
tools_used list[str] | None

Tool names to include, or None for all registered tools.

None

返回:

类型 描述
list[type['BaseTool']]

The selected registered tool classes.

load_custom_tool classmethod

load_custom_tool(path: str) -> dict

Load or update one BaseTool stored in a skill's tool.py.

Reloading the same path replaces its previous registration. A load failure leaves that path unavailable, and a name owned by another path is rejected.

参数:

名称 类型 描述 默认
path str

Path to the custom Python tool module.

必需

返回:

类型 描述
dict

Registration details for the loaded tool.

discover_custom_tools classmethod

discover_custom_tools(
    skill_manager: SkillManager,
) -> list[type["BaseTool"]]

Discover custom tools.

参数:

名称 类型 描述 默认
skill_manager SkillManager

The skill manager value.

必需

返回:

类型 描述
list[type['BaseTool']]

list[type['BaseTool']]: The operation result.

to_dict classmethod

to_dict() -> dict

Export an OpenAI-compatible function-tool definition.

返回:

类型 描述
dict

The tool name, description, and JSON parameter schema.

infer_tool_description classmethod

infer_tool_description() -> str

Extract a tool description from the text before Args in execute.

返回:

类型 描述
str

The inferred description or a placeholder when none is provided.

infer_tool_parameters classmethod

infer_tool_parameters() -> Dict[str, Any]

Infer a parameter schema from the execute signature and docstring.

Automatic inference covers common Python and typing annotations. Complex constraints, enumerations, and formats should be declared explicitly in ToolMetadata.parameters.

返回:

类型 描述
Dict[str, Any]

An object-shaped JSON schema for model-supplied arguments.

parse_args_docstring staticmethod

parse_args_docstring(func: callable) -> dict[str, str]

Extract argument descriptions from a Google-style docstring.

参数:

名称 类型 描述 默认
func callable

Callable whose docstring describes its parameters.

必需

返回:

类型 描述
dict[str, str]

Descriptions keyed by parameter name.

parse_args_typehints classmethod

parse_args_typehints(annotation: Any) -> Dict[str, Any]

Convert a common Python type annotation to JSON Schema.

参数:

名称 类型 描述 默认
annotation Any

Type annotation to convert.

必需

返回:

类型 描述
Dict[str, Any]

A JSON Schema fragment.

parse_json_type staticmethod

parse_json_type(value_type: Any) -> str

Map a Python literal type to a JSON Schema type name.

参数:

名称 类型 描述 默认
value_type Any

Python type to inspect.

必需

返回:

类型 描述
str

A JSON type name, or an empty string for an unsupported type.

calculate_metrics classmethod

calculate_metrics(
    f: Expression, y_true: ndarray, y_pred: ndarray
) -> Dict[str, Any]

Calculate metrics for precomputed target and prediction arrays.

This helper lets code-defined models reuse the symbolic tools' metric definitions.

参数:

名称 类型 描述 默认
f Expression

Candidate expression used to compute structural complexity.

必需
y_true ndarray

Observed target values.

必需
y_pred ndarray

Predicted target values.

必需

返回:

类型 描述
Dict[str, Any]

Fit, correlation, information-criterion, and complexity metrics.

evaluate

evaluate(
    f: Expression,
    y: Expression,
    show_diagnostics: bool = True,
    fit: bool = False,
) -> Dict[str, Any]

Evaluate a symbolic prediction against a symbolic target.

Metrics, including formula complexity, are supplied by the active evaluator. Residual diagnostics include an error profile, worst samples, and strong residual-variable correlations.

参数:

名称 类型 描述 默认
f Expression

Symbolic prediction expression.

必需
y Expression

Symbolic target expression.

必需
show_diagnostics bool

Whether to include residual diagnostics.

True
fit bool

Whether to fit parameters on the training split before scoring.

False

返回:

类型 描述
Dict[str, Any]

Candidate eligibility and metrics for each available data split.

failed_evaluation

failed_evaluation(
    formula: str = "(None)",
) -> Dict[str, Any]

Build the common result shape when a formula-producing backend fails.

参数:

名称 类型 描述 默认
formula str

Formula or placeholder to report.

'(None)'

Returns: A non-candidate result with infinite error metrics.

format_evaluation_result classmethod

format_evaluation_result(
    result: Dict[str, Any],
    title: str = "Formula evaluation",
) -> str

Format the common formula-evaluation schema for an LLM.

参数:

名称 类型 描述 默认
result Dict[str, Any]

Evaluation mapping produced by evaluate.

必需
title str

Heading shown above the formatted result.

'Formula evaluation'

返回:

类型 描述
str

Concise formula, metric, warning, and diagnostic text.

residual_diagnostics classmethod

residual_diagnostics(
    y_true: ndarray,
    y_pred: ndarray,
    data: Dict[str, Any] = None,
    target_expression: str = None,
    max_samples: int = 3,
    max_correlations: int = 5,
) -> Dict[str, Any]

Return compact diagnostics for prediction residuals.

参数:

名称 类型 描述 默认
y_true ndarray

Observed target values.

必需
y_pred ndarray

Predicted target values.

必需
data Dict[str, Any]

Optional variables used to explain residual patterns.

None
target_expression str

Target label included in diagnostic rows.

None
max_samples int

Maximum number of worst samples to include.

3
max_correlations int

Maximum number of residual correlations to include.

5

返回:

类型 描述
Dict[str, Any]

Error profile, worst samples, and strongest residual correlations.

correlation_coefficients staticmethod

correlation_coefficients(
    x: ndarray, y: ndarray
) -> tuple[float, float]

Return finite-sample Pearson and Spearman coefficients.

Undefined correlations, including constant inputs, are returned as NaN. Warnings for these mathematically valid edge cases are suppressed.

参数:

名称 类型 描述 默认
x ndarray

First numeric sample.

必需
y ndarray

Second numeric sample.

必需

返回:

类型 描述
tuple[float, float]

Pearson and Spearman correlation coefficients.

ToolRunAbort

Bases: RuntimeError

Raise from a tool to bypass BaseTool.call error handling.

StatisticsTool

StatisticsTool(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Implementation of the statistics tool.

execute

execute(
    variables: List[str] = None,
    n_bins: int = 10,
    near_zero_threshold: float = 1e-08,
) -> Dict[str, Any]

Execute statistical analysis.

参数:

名称 类型 描述 默认
variables List[str]

List of variable names to analyze, e.g., ["x1", "x2", "y"]. Use all variables (including the target variable) by default. Expressions are also supported, e.g., ["sin(x1)", "(x1-x2)**2", "sin(y+x1)"].

None
n_bins int

Number of equal-width histogram bins used to summarize each distribution (1-100).

10
near_zero_threshold float

First absolute-value threshold used to count near-zero samples. The output also reports thresholds 1e-6 and 1e-4.

1e-08

format_result_dict classmethod

format_result_dict(result: Dict[str, Any]) -> str

Format a tool result for the language model.

参数:

名称 类型 描述 默认
result Dict[str, Any]

Result mapping to format or update.

必需

返回:

名称 类型 描述
str str

The operation result.

get_stats

get_stats(
    arr: ndarray,
    n_bins: int = 10,
    near_zero_threshold: float = 1e-08,
) -> Dict[str, Any]

Compute statistics for a single array.

参数:

名称 类型 描述 默认
arr ndarray

Input array.

必需

返回:

类型 描述
Dict[str, Any]

Dictionary of statistics.

RelationshipAnalysisTool

RelationshipAnalysisTool(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Implementation of the relationship analysis tool.

execute

execute(
    variables: List[str] = None,
    y: str = None,
    n_bins: int = 5,
    pairwise: bool = False,
    binning: str = "quantile",
    n_folds: int = 5,
    collapse_model: str = "bins",
) -> Dict[str, Any]

Analyze feature-target relationships, conditional distributions, and one-dimensional collapse.

参数:

名称 类型 描述 默认
variables List[str]

Variables or expressions to analyze. Use all numeric non-target variables by default.

None
y str

Target variable or expression. Use the formula-discovery target by default.

None
n_bins int

Number of bins for each feature's conditional target summary (2-100).

5
pairwise bool

Whether to also return full pairwise Pearson and Spearman matrices.

False
binning str

Binning strategy: "quantile" or "equal_width".

'quantile'
n_folds int

Number of disjoint cross-validation folds (2-20). Default: 5.

5
collapse_model str

One-dimensional predictor fitted on each training fold: "bins", "spline", or "isotonic".

'bins'

format_result_dict classmethod

format_result_dict(result: Dict[str, Any]) -> str

Format a tool result for the language model.

参数:

名称 类型 描述 默认
result Dict[str, Any]

Result mapping to format or update.

必需

返回:

名称 类型 描述
str str

The operation result.

EvaluateTool

EvaluateTool(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Implementation of the evaluate tool.

execute

execute(
    f: str,
    y: str = None,
    fit: bool = False,
    show_diagnostics: bool = True,
) -> Dict[str, Any]

Evaluate formula fit quality to data.

This tool can return candidate formulas for submission when y is the target variable and f does not depend on the target variable.

参数:

名称 类型 描述 默认
f str

Formula string, e.g., "x1**2 + sin(x2) + 3.5 * tanh(x3)". Common operators like sin, sinh, sec, sech, and sigmoid are all supported; do not use numpy or np.

必需
y str

Target variable name. Use target variable by default. Expressions are also supported, e.g., "log(y)", "y - x1"

None
fit bool

Whether to optimize formula parameters using BFGS algorithm.

False
show_diagnostics bool

Whether the result should include a compact residual error profile, the worst samples, and the strongest residual-variable correlations.

True

format_result_dict classmethod

format_result_dict(result: Dict[str, Any]) -> str

Format a tool result for the language model.

参数:

名称 类型 描述 默认
result Dict[str, Any]

Result mapping to format or update.

必需

返回:

名称 类型 描述
str str

The operation result.

SubmitFormulaTool

SubmitFormulaTool(
    context: AgentContext | None = None, **values: Any
)

Bases: EvaluateTool

Implementation of the submit formula tool.

EvaluateCodeTool

EvaluateCodeTool(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Implementation of the evaluate code tool.

execute

execute(
    model_code: str,
    predict_code: str,
    y: str = None,
    timeout_seconds: int = DEFAULT_TIMEOUT_SECONDS,
    memory_limit_mb: int = DEFAULT_MEMORY_LIMIT_MB,
    output_limit_bytes: int = DEFAULT_OUTPUT_LIMIT_BYTES,
    show_diagnostics: bool = True,
) -> Dict[str, Any]

Evaluate a Python-defined candidate model on the current dataset.

If possible, first use read_skill to review sr-harness-engine-syntax and any relevant companion documentation, such as sr-harness-engine-graph-syntax for graph or hypergraph models. Prefer a structured SRHarness Engine formula when it can express the candidate, and use this tool when it cannot do so conveniently. The code runs in a restricted sandbox, then the tool computes metrics against the target and returns the formatted model under the formula key.

This tool can return candidate formulas for submission when y is the target variable and predict_code does not depend on the target variable.

参数:

名称 类型 描述 默认
model_code str

Code containing exactly one function with signature def func(data) plus optional top-level imports. data is a dictionary mapping variable names to numeric arrays, including the target variable. This function should return a Python dict as the fitted model, which will be passed to predict_code and format_code. The returned model should contain a description field that identifies the model with a concise mathematical formula (e.g., y = aₖx² + bₖx + cₖ, yᵢ = MLP1(xᵢ) + Σ Aᵢⱼ MLP2(xᵢ, xⱼ)).

必需
predict_code str

Code containing exactly one function with signature def func(data, model) plus optional top-level imports. The function should return the predicted value for the target y, which must be array-like and compatible with the target shape.

必需
y str

Target variable name. Use target variable by default. Expressions are also supported, e.g., "log(y)", "y - x1"

None
timeout_seconds int

Wall-clock timeout in seconds. The effective value is capped.

DEFAULT_TIMEOUT_SECONDS
memory_limit_mb int

Address-space memory limit in MB. The effective value is capped.

DEFAULT_MEMORY_LIMIT_MB
output_limit_bytes int

Limit on the amount of output (in bytes) that can be produced.

DEFAULT_OUTPUT_LIMIT_BYTES
show_diagnostics bool

Whether metrics should include compact residual diagnostics.

True

format_result_dict classmethod

format_result_dict(result: Dict[str, Any]) -> str

Format a tool result for the language model.

参数:

名称 类型 描述 默认
result Dict[str, Any]

Result mapping to format or update.

必需

返回:

名称 类型 描述
str str

The operation result.

LLMTool

LLMTool(context: AgentContext | None = None, **values: Any)

Bases: BaseTool

Implementation of the l l m tool.

execute

execute(
    llm_provider: str,
    llm_model: str,
    messages: List[Dict[str, str]] | str,
) -> Dict[str, Any]

Call LLM API.

参数:

名称 类型 描述 默认
llm_provider str

LLM provider name, e.g., "openai", "deepseek", "gemini".

必需
llm_model str

Model name, e.g., "gpt-4o-mini", "deepseek-chat".

必需
messages List[Dict[str, str]] | str

List of messages, each as [{"role": "user"|"assistant", "content": "..."}, ...].

必需

PolynomialFitTool

PolynomialFitTool(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Implementation of the polynomial fit tool.

execute

execute(
    x: List[str] = None,
    y: str = None,
    max_degree: int = 2,
    include_interactions: bool = True,
    interaction_blacklist: List[Tuple[str, str]] = None,
    interaction_whitelist: List[Tuple[str, str]] = None,
    include_bias: bool = True,
    simplify: bool = True,
    show_diagnostics: bool = True,
) -> Dict[str, Any]

Execute polynomial fit.

This tool can return candidate formulas for submission when y is the target variable and x does not depend on the target variable.

参数:

名称 类型 描述 默认
x List[str]

List of input feature names, e.g., ["x1", "x2"]. Use all features other than y by default. Expressions are also supported, e.g., ["sin(x1)", "(x1-x2)**2"].

None
y str

Target variable name. Use target variable by default. Expressions are also supported, e.g., "log(y)", "y - x1"

None
max_degree int

Maximum polynomial degree.

2
include_interactions bool

Whether to include interaction terms.

True
interaction_blacklist List[Tuple[str, str]]

List of variable pairs that should not interact. E.g., [("x1", "x2")] means no interaction between x1 and x2.

None
interaction_whitelist List[Tuple[str, str]]

Only allow specified variable pairs to interact. By default, all pairs are allowed (unless in blacklist). If specified, only interactions in the whitelist are generated.

None
include_bias bool

Whether to include bias/intercept term.

True
simplify bool

Whether to conservatively remove monomials whose fitted contributions are negligible on the training samples, then refit the remaining coefficients. Enabled by default.

True
show_diagnostics bool

Whether final metrics should include compact residual diagnostics.

True

format_result_dict classmethod

format_result_dict(result: Dict[str, Any]) -> str

Format a tool result for the language model.

参数:

名称 类型 描述 默认
result Dict[str, Any]

Result mapping to format or update.

必需

返回:

名称 类型 描述
str str

The operation result.

generate_terms

generate_terms(
    features: List[Expression],
    max_degree: int,
    allowed_interactions: Set[Tuple[str, str]],
    include_bias: bool,
) -> List[Expression]

Generate symbolic terms up to a total degree.

参数:

名称 类型 描述 默认
features List[Expression]

Input feature expressions.

必需
max_degree int

Maximum total polynomial degree.

必需
allowed_interactions Set[Tuple[str, str]]

Optional interaction combinations to retain.

必需
include_bias bool

Whether to include the constant term.

必需

返回:

类型 描述
List[Expression]

Generated polynomial terms.

HarmonicInteractionFitTool

HarmonicInteractionFitTool(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Implementation of the harmonic interaction fit tool.

execute

execute(
    carrier: str,
    oscillator: str,
    y: str = None,
    degree: int = 2,
    include_bias: bool = False,
    max_cycles: float = 20.0,
    grid_size: int = 320,
    show_diagnostics: bool = True,
) -> Dict[str, Any]

Fit y = polynomial(carrier) + carrier * sin(frequency * oscillator).

参数:

名称 类型 描述 默认
carrier str

State variable or expression that multiplies the sine term.

必需
oscillator str

Variable or expression used as the sine argument.

必需
y str

Target variable; defaults to the discovery target.

None
degree int

Polynomial degree in carrier, from 1 through 4.

2
include_bias bool

Whether to fit an additive constant.

False
max_cycles float

Largest number of cycles across the observed oscillator span.

20.0
grid_size int

Number of initial frequency-grid points, from 64 through 2048.

320
show_diagnostics bool

Include residual diagnostics in the returned evaluation.

True

format_result_dict classmethod

format_result_dict(result: Dict[str, Any]) -> str

Format a tool result for the language model.

参数:

名称 类型 描述 默认
result Dict[str, Any]

Result mapping to format or update.

必需

返回:

名称 类型 描述
str str

The operation result.

PowerLawFitTool

PowerLawFitTool(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Implementation of the power law fit tool.

execute

execute(
    x: List[str] = None,
    y: str = None,
    include_scale: bool = True,
    snap_exponents: bool = False,
    max_denominator: int = 8,
    snap_tolerance: float = 0.05,
    max_snap_rmse_degradation: float = 0.01,
    n_stability_folds: int = 5,
    show_diagnostics: bool = True,
) -> Dict[str, Any]

Fit a multiplicative power law y = c * product(x_i ** p_i) in log space.

参数:

名称 类型 描述 默认
x List[str]

Strictly positive input variables or expressions on every training sample. Use all numeric non-target variables by default.

None
y str

Strictly positive target variable or expression on every training sample. Use the formula-discovery target by default.

None
include_scale bool

Whether to fit the multiplicative scale c.

True
snap_exponents bool

Whether to try nearby simple rational exponents and refit c.

False
max_denominator int

Largest denominator considered when snapping exponents (1-32).

8
snap_tolerance float

Maximum distance from every fitted exponent to its snapped value.

0.05
max_snap_rmse_degradation float

Maximum normalized RMSE degradation allowed after snapping.

0.01
n_stability_folds int

Number of disjoint folds for leave-one-fold-out exponent confidence intervals (2-20).

5
show_diagnostics bool

Whether final metrics should include compact residual diagnostics.

True

format_result_dict classmethod

format_result_dict(result: Dict[str, Any]) -> str

Format a tool result for the language model.

参数:

名称 类型 描述 默认
result Dict[str, Any]

Result mapping to format or update.

必需

返回:

名称 类型 描述
str str

The operation result.

RationalFitTool

RationalFitTool(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Implementation of the rational fit tool.

execute

execute(
    x: List[str] = None,
    y: str = None,
    numerator_degree: int = 2,
    denominator_degree: int = 1,
    include_interactions: bool = True,
    numerator_degrees: List[int] = None,
    denominator_degrees: List[int] = None,
    validation_fraction: float = 0.2,
    top_k: int = 5,
    complexity_penalty: float = 1e-12,
    show_diagnostics: bool = True,
) -> Dict[str, Any]

Fit a rational expression P(x) / Q(x) by linearized least squares with Q's constant fixed to one.

参数:

名称 类型 描述 默认
x List[str]

Input variables or expressions. Use all numeric non-target variables by default.

None
y str

Target variable or expression. Use the formula-discovery target by default.

None
numerator_degree int

Maximum total degree of numerator P (0-8).

2
denominator_degree int

Maximum total degree of denominator Q excluding its fixed constant (0-8).

1
include_interactions bool

Whether polynomial terms may contain multiple input features.

True
numerator_degrees List[int]

Optional numerator degree grid; overrides numerator_degree when provided.

None
denominator_degrees List[int]

Optional denominator degree grid; overrides denominator_degree when provided.

None
validation_fraction float

Deterministic holdout fraction used to rank degree combinations (0.05-0.5).

0.2
top_k int

Number of degree-grid candidates to return (1-20).

5
complexity_penalty float

Penalty per fitted coefficient added to validation RMSE after target-scale normalization.

1e-12
show_diagnostics bool

Whether final metrics should include compact residual diagnostics.

True

format_result_dict classmethod

format_result_dict(result: Dict[str, Any]) -> str

Format a tool result for the language model.

参数:

名称 类型 描述 默认
result Dict[str, Any]

Result mapping to format or update.

必需

返回:

名称 类型 描述
str str

The operation result.

ConstantFitTool

ConstantFitTool(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Implementation of the constant fit tool.

execute

execute(
    eq: str, y: str = None, use_eq_as_y: bool = False
) -> Dict[str, Any]

Compare nearby simple constants at each numeric position in eq.

Search nearby integers and fractions (denominator <= 12, numerator <= 32), pi, e, sqrt(2)..sqrt(10), and signed half/double multiples of these named constants. Candidates must be within 5% relative distance of the original number. The Pareto front maximizes validation R2 if validation data exist, otherwise train R2, and minimizes the count of original numeric constants left unchanged.

参数:

名称 类型 描述 默认
eq str

Required formula containing at least one numeric constant.

必需
y str

Target variable or expression; overrides use_eq_as_y when supplied.

None
use_eq_as_y bool

If y is omitted, compare against original eq rather than the tool context's target variable.

False

format_result_dict classmethod

format_result_dict(result: Dict[str, Any]) -> str

Format a tool result for the language model.

参数:

名称 类型 描述 默认
result Dict[str, Any]

Result mapping to format or update.

必需

返回:

名称 类型 描述
str str

The operation result.

CodeExecutorTool

CodeExecutorTool(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Implementation of the code executor tool.

execute

execute(
    program: str,
    timeout_seconds: int = DEFAULT_TIMEOUT_SECONDS,
    memory_limit_mb: int = DEFAULT_MEMORY_LIMIT_MB,
    output_limit_bytes: int = DEFAULT_OUTPUT_LIMIT_BYTES,
) -> Dict[str, Any]

Execute Python code and return printed output. 1) Use import sys, json; data_dict = json.loads(sys.stdin.read()) to access data mapping variable names to lists. 2) Use print() to produce output. 3) The code is executed in an operating-system sandbox with resource limits. 4) Installed scientific Python libraries are available. Files outside the ephemeral sandbox, networking, and child-process creation are unavailable.

参数:

名称 类型 描述 默认
program str

Python code string to execute, starting with import sys, json; data_dict = json.loads(sys.stdin.read()) to access input data.

必需
timeout_seconds int

Wall-clock timeout in seconds. The effective value is capped.

DEFAULT_TIMEOUT_SECONDS
memory_limit_mb int

Address-space memory limit in MB. The effective value is capped.

DEFAULT_MEMORY_LIMIT_MB
output_limit_bytes int

Limit on the amount of output (in bytes) that can be produced.

DEFAULT_OUTPUT_LIMIT_BYTES

format_result_dict classmethod

format_result_dict(result: Dict[str, Any]) -> str

Format a tool result for the language model.

参数:

名称 类型 描述 默认
result Dict[str, Any]

Result mapping to format or update.

必需

返回:

名称 类型 描述
str str

The operation result.

extract_code classmethod

extract_code(code: str) -> str

Extract Python source from an optional Markdown fence.

serialization classmethod

serialization(value: Any) -> Any

Convert context data to JSON-compatible values.

bounded_int classmethod

bounded_int(
    value: Any, default: int, minimum: int, maximum: int
) -> int

Return a bounded integer tool argument.

WorkspaceCodeExecutorTool

WorkspaceCodeExecutorTool(
    context: AgentContext | None = None, **values: Any
)

Bases: CodeExecutorTool

Implementation of the workspace code executor tool.

execute

execute(
    program: str,
    timeout_seconds: int = DEFAULT_TIMEOUT_SECONDS,
    memory_limit_mb: int = DEFAULT_MEMORY_LIMIT_MB,
    output_limit_bytes: int = DEFAULT_OUTPUT_LIMIT_BYTES,
) -> Dict[str, Any]

Execute Python code in the workspace directory with file access. 1) Code runs with cwd set to the workspace directory. 2) Use open("filename") or pandas.read_csv("filename") to read workspace files. 3) Use open("output.csv", "w") to write results back to the workspace. 4) All file paths must be within the workspace. Absolute paths outside workspace are forbidden. 5) Installed scientific Python libraries are available. Networking and child-process creation are unavailable.

参数:

名称 类型 描述 默认
program str

Python code string to execute.

必需
timeout_seconds int

Wall-clock timeout in seconds. The effective value is capped.

DEFAULT_TIMEOUT_SECONDS
memory_limit_mb int

Address-space memory limit in MB. The effective value is capped.

DEFAULT_MEMORY_LIMIT_MB
output_limit_bytes int

Limit on the amount of output (in bytes) that can be produced.

DEFAULT_OUTPUT_LIMIT_BYTES

ReadSkill

ReadSkill(**context: Any)

Bases: BaseTool

Implementation of the read skill.

execute

execute(
    name: str = "",
    file_path: str = "",
    show_tree: bool = False,
    query: str = "",
) -> Dict[str, Any]

Inspect a skill's instructions, directory structure, or a file.

参数:

名称 类型 描述 默认
name str

The exact skill name to inspect. Leave empty to search by query.

''
file_path str

Optional path relative to the skill directory, such as tool.py or references/example.md. Empty reads SKILL.md.

''
show_tree bool

Whether to include all files and subdirectories in the skill.

False
query str

Task description used to recommend skills when name is empty.

''

format_result_dict classmethod

format_result_dict(result: Dict[str, Any]) -> str

Format a tool result for the language model.

参数:

名称 类型 描述 默认
result Dict[str, Any]

Result mapping to format or update.

必需

返回:

名称 类型 描述
str str

The operation result.

CreateSkill

CreateSkill(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Implementation of the create skill.

execute

execute(
    request: str = "",
    force: bool = False,
    history_messages: int | None = None,
) -> Dict[str, Any]

Create a reusable skill in one tool call. The tool passes the current Agent buffer and request to the configured LLM, determines whether the skill is instruction-only, data-analysis, or formula-proposal, supplies the matching demo, iterates internally to complete the draft, and then writes the skill.

参数:

名称 类型 描述 默认
request str

Explain the reusable capability or lesson to capture. The current Agent conversation and the tool-call message are supplied automatically.

''
force bool

Replace an existing editable skill's SKILL.md and tool.py. Other files are preserved; read-only skills cannot be replaced.

False
history_messages int | None

Number of most recent Agent messages to provide to the authoring LLM. Defaults to all available messages.

None

format_result_dict classmethod

format_result_dict(result: Dict[str, Any]) -> str

Format a tool result for the language model.

参数:

名称 类型 描述 默认
result Dict[str, Any]

Result mapping to format or update.

必需

返回:

名称 类型 描述
str str

The operation result.

EditSkill

EditSkill(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Implementation of the edit skill.

execute

execute(name: str, patch: str) -> Dict[str, Any]

Edit an existing skill with exact search/replace blocks. Use this when an existing skill is clearly relevant but should be corrected, refined, or extended based on concrete results from the current or recent work. You do not need to find a perfect formula or reach MSE = 0.0 before editing a skill; edit it when an attempt reveals a useful reusable tactic. Prefer small, evidence-backed edits. Do not overwrite broad guidance with a one-off dataset detail, a final formula, or an unverified guess. If no existing skill matches the reusable lesson, create a new skill instead.

参数:

名称 类型 描述 默认
name str

The exact skill name to edit.

必需
patch str

One or more SEARCH/REPLACE blocks. Each SEARCH text must match exactly once in the target skill file. Format:

<<<<<<< SEARCH old text copied exactly from the skill file ======= new replacement text

REPLACE

Use multiple blocks for multiple focused edits.

必需

format_result_dict classmethod

format_result_dict(result: Dict[str, Any]) -> str

Format a tool result for the language model.

参数:

名称 类型 描述 默认
result Dict[str, Any]

Result mapping to format or update.

必需

返回:

名称 类型 描述
str str

The operation result.

EditTool

EditTool(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Implementation of the edit tool.

execute

execute(
    name: str, tool_patch: str, skill_patch: str = ""
) -> Dict[str, Any]

Edit and reload a custom tool using exact search/replace blocks.

参数:

名称 类型 描述 默认
name str

Exact skill name containing the custom tool.

必需
tool_patch str

One or more exact SEARCH/REPLACE blocks for tool.py, using <<<<<<< SEARCH + old text + ======= + new text + >>>>>>> REPLACE. SEARCH text must match exactly once. The resulting tool must not use @BaseTool.register(...).

必需
skill_patch str

Optional blocks in the same format applied to the complete SKILL.md file. name is the skill directory name, not the tool's metadata.name.

''

format_result_dict classmethod

format_result_dict(result: Dict[str, Any]) -> str

Format a tool result for the language model.

参数:

名称 类型 描述 默认
result Dict[str, Any]

Result mapping to format or update.

必需

返回:

名称 类型 描述
str str

The operation result.

SINDyTool

SINDyTool(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Implementation of the s i n dy tool.

execute

execute(
    x: List[str] = None,
    y: str = None,
    poly_degree: int = 3,
    include_trig: bool = False,
    threshold: float = 0.1,
    max_samples: int = 5000,
    show_diagnostics: bool = True,
) -> Dict[str, Any]

Run SINDy (Sparse Identification of Nonlinear Dynamics) to discover symbolic expressions from data. SINDy builds a library of candidate nonlinear functions and uses sparse regression (STLSQ) to find a parsimonious combination that explains the target variable. Best suited for polynomial, interaction, and trigonometric relationships.

This tool can return candidate formulas for submission when y is the target variable and x does not depend on the target variable.

参数:

名称 类型 描述 默认
x List[str]

List of input feature names to use. If not specified, all features except target are used. Expressions are also supported, e.g., ["sin(x1)", "(x1-x2)**2"].

None
y str

Target variable name. If not specified, the default target variable is used. Expressions are also supported, e.g., "log(y)", "y - x1"

None
poly_degree int

Maximum polynomial degree for the feature library (1-5). Higher values find more complex relationships but are slower.

3
include_trig bool

Whether to include sin/cos terms in the feature library. Enable this if you suspect trigonometric relationships.

False
threshold float

Sparsity threshold for STLSQ optimizer (0.01-1.0). Larger values produce sparser (simpler) formulas.

0.1
max_samples int

Maximum number of data samples to use for fitting (for speed). Data is subsampled if larger.

5000
show_diagnostics bool

Whether final metrics should include compact residual diagnostics.

True

format_result_dict classmethod

format_result_dict(result: Dict[str, Any]) -> str

Format a tool result for the language model.

参数:

名称 类型 描述 默认
result Dict[str, Any]

Result mapping to format or update.

必需

返回:

名称 类型 描述
str str

The operation result.

PySRTool

PySRTool(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Implementation of the py s r tool.

execute

execute(
    binary_operators: List[str],
    unary_operators: List[str],
    x: List[str] = None,
    y: str = None,
    timeout: int = 30,
    maxsize: int = 25,
    max_samples: int = 500,
    show_diagnostics: bool = True,
) -> Dict[str, Any]

Run PySR (genetic programming symbolic regression) to evolve mathematical expressions that fit the data. PySR perform evolutionary search for symbolic formulas. It is powerful for discovering complex nonlinear relationships including trigonometric, exponential, sqrt, and nested functions. However, it is also computationally intensive and requires careful tuning of operators and variables to find good formulas within reasonable time. You MUST specify the binary and unary operators based on your hypothesis about the data.

This tool can return candidate formulas for submission when y is the target variable and x does not depend on the target variable.

参数:

名称 类型 描述 默认
binary_operators List[str]

List of binary operators for PySR to use. Choose from: "+", "-", "*", "/", "^". Select operators you believe are relevant to the underlying formula.

必需
unary_operators List[str]

List of unary operators for PySR to use. Choose from: "sin", "cos", "exp", "log", "sqrt", "square", "cube", "abs", "tanh", "sign". Select operators based on your hypothesis about the data.

必需
x List[str]

List of input feature names to use. If not specified, all features except target are used. Expressions are also supported, e.g., ["sin(x1)", "(x1-x2)**2"].

None
y str

Target variable name. If not specified, the default target variable is used. Expressions are also supported, e.g., "log(y)", "y - x1"

None
timeout int

Maximum search time in seconds (default 30, max 120). If PySR did not find a good formula in a previous run, increase timeout (e.g., 60 or 90) to give it more search time.

30
maxsize int

Maximum expression complexity in number of nodes (10-40). Larger allows more complex formulas.

25
max_samples int

Maximum number of data samples to use for fitting (for speed). Data is subsampled if larger.

500
show_diagnostics bool

Whether final metrics should include compact residual diagnostics.

True

format_result_dict classmethod

format_result_dict(result: Dict[str, Any]) -> str

Format a tool result for the language model.

参数:

名称 类型 描述 默认
result Dict[str, Any]

Result mapping to format or update.

必需

返回:

名称 类型 描述
str str

The operation result.

PropertyPredictorTool

PropertyPredictorTool(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Implementation of the property predictor tool.

execute

execute() -> Dict[str, Any]

Predict mathematical properties of the data using a neural network. This tool analyzes the relationship between input variables and the target to detect: - Monotonicity: Whether y is monotonically increasing, decreasing, or constant w.r.t. each variable. - Convexity: Whether y is convex, concave, or affine w.r.t. each variable. - Periodicity: A heuristic per-variable periodicity prediction. A negative prediction does not rule out a periodic term modulated by another variable (for example x * sin(omega * t)). - Multiplicative Separability: Whether y = f(x1) * g(x2) * ... Additionally, this tool automatically tests variable COMBINATIONS (xixj, xi+xj, xi-xj, xi/xj) to detect properties that only emerge in combinations (e.g., sin(x1x2) is periodic in x1*x2 but neither x1 nor x2 alone appears periodic). No arguments needed — the tool automatically uses the data provided to the agent.

format_result_dict classmethod

format_result_dict(result: Dict[str, Any]) -> str

Format a tool result for the language model.

参数:

名称 类型 描述 默认
result Dict[str, Any]

Result mapping to format or update.

必需

返回:

名称 类型 描述
str str

The operation result.

WorkspaceShellTool

WorkspaceShellTool(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Implementation of the workspace shell tool.

get_doc classmethod

get_doc() -> dict[str, str]

Return documentation exposed as a runtime skill.

返回:

类型 描述
dict[str, str]

dict[str, str]: The operation result.

execute

execute(
    command: str,
    output_limit_bytes: int = DEFAULT_OUTPUT_LIMIT_BYTES,
) -> Dict[str, Any]

Execute a restricted shell command in the workspace directory. Supported commands: ls, cat, head, tail, wc, grep, sort, cut, cp, mv, rm, mkdir, gunzip, gzip, unzip, tar. All file paths are relative to the workspace root. Absolute paths and path traversal (e.g., ../) are forbidden.

参数:

名称 类型 描述 默认
command str

A shell command string. Examples: "ls", "cat data.csv | head -5", "gunzip data.csv.gz".

必需
output_limit_bytes int

Maximum stdout size returned by each command segment.

DEFAULT_OUTPUT_LIMIT_BYTES

format_result_dict classmethod

format_result_dict(result: Dict[str, Any]) -> str

Format a tool result for the language model.

参数:

名称 类型 描述 默认
result Dict[str, Any]

Result mapping to format or update.

必需

返回:

名称 类型 描述
str str

The operation result.

execute_single

execute_single(
    command: str, workspace: Workspace, stdin_text: str
) -> Dict[str, Any]

Execute one command segment after pipeline parsing.

参数:

名称 类型 描述 默认
command str

Parsed command and arguments.

必需
workspace Workspace

Active restricted workspace.

必需
stdin_text str

Text received from the previous pipeline segment.

必需

返回:

类型 描述
Dict[str, Any]

Structured command output and status.

SubagentTool

SubagentTool(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Implementation of the subagent tool.

execute

execute(
    objective: str,
    mode: str = "hypothesis_generation",
    candidate_formulas: List[str] = None,
    evidence: str = "",
) -> Dict[str, Any]

Run a bounded independent SR analysis with a specific scientific role.

Use this only when diversity or an independent audit is valuable: generating competing hypotheses before committing search budget, critiquing near-tied candidates, diagnosing structured residuals, or recovering a stagnated search. The subagent cannot execute tools or mutate the main search state; it must return falsifiable recommendations.

参数:

名称 类型 描述 默认
objective str

Precise scientific question or search decision to resolve.

必需
mode str

hypothesis_generation, candidate_critique, residual_diagnosis, or search_recovery.

'hypothesis_generation'
candidate_formulas List[str]

Candidate expressions to compare when relevant.

None
evidence str

Compact metrics, residual summaries, units, or search history from main tools.

''

format_result_dict classmethod

format_result_dict(result: Dict[str, Any]) -> str

Format a tool result for the language model.

参数:

名称 类型 描述 默认
result Dict[str, Any]

Result mapping to format or update.

必需

返回:

名称 类型 描述
str str

The operation result.

WebFetchTool

WebFetchTool(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Implementation of the web fetch tool.

execute

execute(
    url: str, max_characters: int = 30000
) -> Dict[str, Any]

Fetch readable text from a public HTTP or HTTPS page.

参数:

名称 类型 描述 默认
url str

Absolute public webpage URL returned by web_search.

必需
max_characters int

Maximum number of extracted text characters, between 1000 and 50000.

30000

WebSearchTool

WebSearchTool(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Implementation of the web search tool.

execute

execute(query: str, max_results: int = 5) -> Dict[str, Any]

Search the public web for papers, documentation, and scientific context.

参数:

名称 类型 描述 默认
query str

Specific search query.

必需
max_results int

Maximum number of results, between 1 and 10.

5

ValidateContextDataTool

ValidateContextDataTool(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Validate context.data without mutating the live AgentContext.

execute

execute(path: str = 'context.data') -> dict[str, Any]

Validate a manifest-backed context-data directory and explain every repair.

This calls the production load_context_data loader, so a successful result guarantees that InteractiveSession can load the same collection. On failure it returns all detectable errors together with specific repair suggestions instead of stopping at an opaque exception.

参数:

名称 类型 描述 默认
path str

Workspace-relative directory containing manifest.json and flat NPY files.

'context.data'

返回:

类型 描述
dict[str, Any]

Validation status, complete diagnostics, array summaries, and repair actions.

format_result_dict classmethod

format_result_dict(result: dict[str, Any]) -> str

Format complete, actionable diagnostics for the data-preparation Agent.

PDFReadTool

PDFReadTool(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Implementation of the p d f read tool.

execute

execute(
    source: str, start_page: int = 1, max_pages: int = 10
) -> Dict[str, Any]

Extract text from selected pages of a local or public PDF.

参数:

名称 类型 描述 默认
source str

Local PDF path or an absolute public http(s) URL.

必需
start_page int

First page to read, one-indexed.

1
max_pages int

Maximum pages to extract, between 1 and 50.

10

format_result_dict classmethod

format_result_dict(result: Dict[str, Any]) -> str

Format a tool result for the language model.

参数:

名称 类型 描述 默认
result Dict[str, Any]

Result mapping to format or update.

必需

返回:

名称 类型 描述
str str

The operation result.

EICTool

EICTool(context: AgentContext | None = None, **values: Any)

Bases: BaseTool

Diagnose numerical information loss throughout an expression tree.

execute

execute(
    f: str,
    noise_level: float = 0.001,
    repeats: int = 8,
    random_state: int = 0,
    zero_epsilon: float = 1e-06,
) -> Dict[str, Any]

Evaluate whole-formula and per-subtree EIC diagnostics.

Relative Gaussian noise is injected after every non-leaf operation, following the EIC paper's recursive algorithm. The formula EIC is the maximum over all subtree EIC values, which exposes unstable internal structures even when an outer operation masks them.

参数:

名称 类型 描述 默认
f str

Formula to assess.

必需
noise_level float

Relative Gaussian noise injected after each operation.

0.001
repeats int

Independent perturbation runs to average, between 1 and 100.

8
random_state int

Random seed for reproducibility.

0
zero_epsilon float

Denominator fallback used only where a clean subtree output is zero.

1e-06

format_result_dict classmethod

format_result_dict(result: Dict[str, Any]) -> str

Format a tool result for the language model.

参数:

名称 类型 描述 默认
result Dict[str, Any]

Result mapping to format or update.

必需

返回:

名称 类型 描述
str str

The operation result.

get_doc classmethod

get_doc() -> dict[str, str]

Return documentation exposed as a runtime skill.

返回:

类型 描述
dict[str, str]

dict[str, str]: The operation result.

ND2Tool

ND2Tool(context: AgentContext | None = None, **values: Any)

Bases: BaseTool

Implementation of the n d2 tool.

execute

execute(
    vars_node: List[str] = None,
    vars_edge: List[str] = None,
    y: str = None,
    root_type: str = "node",
    binary_operators: List[str] = None,
    unary_operators: List[str] = None,
    timeout: int = 60,
    episode_limit: int = 10000,
    beam_size: int = 10,
    max_coeff_num: int = 5,
) -> Dict[str, Any]

Run NDformer-guided MCTS on node or edge dynamics in the current data.

The context must contain adjacency A and/or edge list G, a target shaped (time, node) or (time, edge), and node/edge variables with matching final axes. ND2_HOME must point to the official repository; ND2_CHECKPOINT defaults to $ND2_HOME/weights/checkpoint.pth.

参数:

名称 类型 描述 默认
vars_node List[str]

Node-level variable names. Inferred from the node axis when omitted.

None
vars_edge List[str]

Edge-level variable names. Inferred from the edge axis when omitted.

None
y str

Target variable name. Defaults to the configured target.

None
root_type str

Output expression type, either "node" or "edge".

'node'
binary_operators List[str]

ND2 binary tokens. Defaults to its standard binary vocabulary.

None
unary_operators List[str]

ND2 unary tokens. Defaults to its standard unary vocabulary.

None
timeout int

Wall-time search limit in seconds, between 10 and 3600.

60
episode_limit int

Maximum MCTS episodes, between 1 and 1000000.

10000
beam_size int

Number of expansions retained per MCTS step, between 1 and 100.

10
max_coeff_num int

Maximum fitted scalar coefficients, between 0 and 20.

5

backend_status classmethod

backend_status() -> Dict[str, Any]

Run the backend status operation.

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: The operation result.

format_result_dict classmethod

format_result_dict(result: Dict[str, Any]) -> str

Format a tool result for the language model.

参数:

名称 类型 描述 默认
result Dict[str, Any]

Result mapping to format or update.

必需

返回:

名称 类型 描述
str str

The operation result.

get_doc classmethod

get_doc() -> dict[str, str]

Return documentation exposed as a runtime skill.

返回:

类型 描述
dict[str, str]

dict[str, str]: The operation result.

SR4MDLTool

SR4MDLTool(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Implementation of the s r4 m d l tool.

execute

execute(
    binary_operators: List[str],
    unary_operators: List[str],
    x: List[str] = None,
    y: str = None,
    timeout: int = 60,
    maxsize: int = 30,
    max_samples: int = 500,
    n_iter: int = 100,
    show_diagnostics: bool = True,
) -> Dict[str, Any]

Run MDLformer-guided Monte Carlo tree search on the current data.

Like call_pysr, this tool constructs a regression dataset from agent-visible expressions and returns an evaluated candidate formula. SR4MDL must be cloned into an isolated directory, SR4MDL_HOME must point to it, and SR4MDL_CHECKPOINT must point to its trained checkpoint (default: $SR4MDL_HOME/weights/checkpoint.pth).

参数:

名称 类型 描述 默认
binary_operators List[str]

Binary search operators chosen from "+", "-", "*", "/".

必需
unary_operators List[str]

Unary operators chosen from "sqrt", "sin", "cos", "neg", "inv", "log", "exp", "square", "cube".

必需
x List[str]

Input feature names or expressions. Defaults to numeric non-target columns.

None
y str

Target name or expression. Defaults to the configured target.

None
timeout int

Soft wall-time budget in seconds, checked whenever a new best tree appears.

60
maxsize int

Maximum expression-tree length, between 5 and 100.

30
max_samples int

Maximum fitting samples, between 20 and 5000.

500
n_iter int

Maximum MCTS iterations, between 1 and 10000.

100
show_diagnostics bool

Whether final metrics include compact residual diagnostics.

True

backend_status classmethod

backend_status() -> Dict[str, Any]

Run the backend status operation.

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: The operation result.

format_result_dict classmethod

format_result_dict(result: Dict[str, Any]) -> str

Format a tool result for the language model.

参数:

名称 类型 描述 默认
result Dict[str, Any]

Result mapping to format or update.

必需

返回:

名称 类型 描述
str str

The operation result.

get_doc classmethod

get_doc() -> dict[str, str]

Return documentation exposed as a runtime skill.

返回:

类型 描述
dict[str, str]

dict[str, str]: The operation result.

ModelTestTool

ModelTestTool(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Report a requested value during a model connectivity test.

execute

execute(answer: str) -> dict[str, str]

Return the value supplied by the model-test request.

参数:

名称 类型 描述 默认
answer str

Exact value requested by the test prompt.

必需

返回:

类型 描述
dict[str, str]

The reported answer.

ReadSourceTool

ReadSourceTool(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Inspect installed source files and locate symbol definitions or references.

execute

execute(
    path: str | None = None,
    symbol: str | None = None,
    include_implementation: bool = True,
    include_references: bool = False,
) -> dict[str, Any]

Read a source path or locate a Python symbol.

参数:

名称 类型 描述 默认
path str | None

File or directory relative to the installed src tree.

None
symbol str | None

Qualified or unqualified Python symbol to locate.

None
include_implementation bool

Whether symbol queries return definitions.

True
include_references bool

Whether symbol queries return references.

False

返回:

类型 描述
dict[str, Any]

A directory listing, file source, or symbol-query result.

format_result_dict classmethod

format_result_dict(result: dict[str, Any]) -> str

Format a source inspection result for a language model.

参数:

名称 类型 描述 默认
result dict[str, Any]

Structured result returned by :meth:execute.

必需

返回:

类型 描述
str

Human-readable source text or query matches.

ValidateEvaluatorTool

ValidateEvaluatorTool(
    context: AgentContext | None = None, **values: Any
)

Bases: BaseTool

Load an evaluator file in isolation and use it to evaluate one formula.

execute

execute(
    f: str,
    evaluator_file: str | None = None,
    y: str | None = None,
    fit: bool = False,
    show_diagnostics: bool = False,
) -> dict[str, Any]

Validate a custom evaluator without changing the live context.

参数:

名称 类型 描述 默认
evaluator_file str | None

Optional workspace-relative Python file under context.evaluator/. When omitted, validate the evaluator already attached to the context.

None
f str

Formula to evaluate.

必需
y str | None

Optional target expression; defaults to context.target.

None
fit bool

Whether to fit formula parameters first.

False
show_diagnostics bool

Whether to include residual diagnostics.

False

format_result_dict classmethod

format_result_dict(result: dict[str, Any]) -> str

Format evaluator identity and formula-evaluation details.

参数:

名称 类型 描述 默认
result dict[str, Any]

Structured result returned by :meth:execute.

必需

返回:

类型 描述
str

A model-readable evaluator validation report.

Symbolic Engine

sr_harness_engine

SRHarness Engine: structured symbolic models for scientific discovery.

Variable module-attribute

Variable = Symbol

sin module-attribute

sin = _unary('sin')

cos module-attribute

cos = _unary('cos')

tan module-attribute

tan = _unary('tan')

tanh module-attribute

tanh = _unary('tanh')

sinh module-attribute

sinh = _unary('sinh')

cosh module-attribute

cosh = _unary('cosh')

arcsin module-attribute

arcsin = _unary('arcsin')

arccos module-attribute

arccos = _unary('arccos')

arctan module-attribute

arctan = _unary('arctan')

exp module-attribute

exp = _unary('exp')

log module-attribute

log = _unary('log')

log10 module-attribute

log10 = _unary('log10')

sqrt module-attribute

sqrt = _unary('sqrt')

abs module-attribute

abs = _unary('abs')

sigmoid module-attribute

sigmoid = _unary('sigmoid')

sign module-attribute

sign = _unary('sign')

sec module-attribute

sec = _unary('sec')

sech module-attribute

sech = _unary('sech')

csc module-attribute

csc = _unary('csc')

cot module-attribute

cot = _unary('cot')

inv module-attribute

inv = _unary('inv')

__all__ module-attribute

__all__ = [
    "Aggregate",
    "Binary",
    "Expression",
    "FitResult",
    "Function",
    "Gather",
    "GroupedParameter",
    "Index",
    "Indexed",
    "Number",
    "Parameter",
    "Reduction",
    "RelationField",
    "RelationLift",
    "Symbol",
    "Variable",
    "abs",
    "aggr",
    "arccos",
    "arcsin",
    "arctan",
    "cos",
    "cosh",
    "bind_parameters",
    "cot",
    "count_parameters",
    "csc",
    "delay",
    "desugar",
    "evaluate",
    "exp",
    "fit",
    "fold_constants",
    "function",
    "gather",
    "grouped_param",
    "inv",
    "log",
    "log10",
    "param",
    "parameter_values",
    "parse",
    "reduction",
    "render",
    "sec",
    "sech",
    "sigmoid",
    "sign",
    "sin",
    "sinh",
    "sour",
    "sqrt",
    "tan",
    "tanh",
    "targ",
    "unbound_parameters",
]

Aggregate dataclass

Aggregate(relation: Expression, operand: Expression)

Bases: Expression

Convenience aggregation node lowered to indexed syntax.

Binary dataclass

Binary(operator: str, left: Expression, right: Expression)

Bases: Expression

Binary expression node.

Expression

Base class of every symbolic expression node.

operands property

operands: tuple[Expression, ...]

Child expressions, exposed as an immutable tuple.

返回:

类型 描述
tuple[Expression, ...]

The direct child nodes in expression order.

evaluate

evaluate(
    values: Mapping[str, Any] | None = None,
    *,
    parameters: Mapping[str, Any] | None = None,
    time: Any = None,
    delay_resolver: Any = None,
    num_nodes: int | None = None,
) -> Any

Evaluate this expression with NumPy values.

参数:

名称 类型 描述 默认
values Mapping[str, Any] | None

Values keyed by symbol name, or a context exposing data and optional num_nodes metadata.

None
parameters Mapping[str, Any] | None

Fitted parameter values keyed by parameter name.

None
time Any

Optional sample times.

None
delay_resolver Any

Optional callback that resolves delayed values.

None
num_nodes int | None

Explicit node count for indexed expressions.

None

返回:

类型 描述
Any

The evaluated scalar or array.

iter_preorder

iter_preorder() -> Iterator[Expression]

Yield this node followed by its descendants.

产生:

类型 描述
Expression

Expression nodes in preorder.

iter_postorder

iter_postorder() -> Iterator[Expression]

Yield descendants followed by this node.

产生:

类型 描述
Expression

Expression nodes in postorder.

copy

copy() -> Expression

Return an independent copy.

返回:

类型 描述
Expression

A deep copy of this expression.

replace

replace(old: Expression, new: Expression) -> Expression

Return a tree in which the exact old node is replaced by new.

参数:

名称 类型 描述 默认
old Expression

Existing expression node to replace.

必需
new Expression

Replacement expression node.

必需

返回:

类型 描述
Expression

A copied expression tree with matching nodes replaced.

to_str

to_str(
    *, latex: bool = False, number_format: str = ""
) -> str

Render the expression as plain text or LaTeX.

参数:

名称 类型 描述 默认
latex bool

Whether to render LaTeX notation.

False
number_format str

Format specification for numeric literals.

''

返回:

类型 描述
str

The rendered expression.

to_tree

to_tree(*, number_format: str = '') -> str

Render a compact preorder tree for diagnostics.

参数:

名称 类型 描述 默认
number_format str

Format specification for numeric literals.

''

返回:

类型 描述
str

A multiline representation of the expression tree.

fit

fit(
    values: Mapping[str, Any],
    target: Any = None,
    *,
    initial: Mapping[str, Any] | None = None,
    method: str = "BFGS",
    options: Mapping[str, Any] | None = None,
    num_nodes: int | None = None,
) -> FitResult

Fit named and grouped parameters against a target array.

参数:

名称 类型 描述 默认
values Mapping[str, Any]

Values keyed by symbol name, or a context exposing data, target, and optional num_nodes metadata.

必需
target Any

Target name or target values. Omit when supplied by context.

None
initial Mapping[str, Any] | None

Optional initial parameter values.

None
method str

Optimization method name.

'BFGS'
options Mapping[str, Any] | None

Optional optimizer settings.

None
num_nodes int | None

Explicit node count for indexed expressions.

None

返回:

类型 描述
FitResult

The fitted expression, parameter values, predictions, and loss.

fold_constants

fold_constants() -> Expression

Return a copy with closed numerical subexpressions evaluated.

返回:

类型 描述
Expression

A simplified expression with closed numeric branches folded.

count_parameters

count_parameters(
    values: Mapping[str, Any] | None = None,
    *,
    parameters: Mapping[str, Any] | None = None,
) -> int

Count independent fitted values represented by this expression.

参数:

名称 类型 描述 默认
values Mapping[str, Any] | None

Values keyed by symbol name.

None
parameters Mapping[str, Any] | None

Fitted parameter values keyed by parameter name.

None

返回:

类型 描述
int

The number of independent scalar parameter values.

Function dataclass

Function(name: str, arguments: tuple[Expression, ...])

Bases: Expression

Named function-call expression node.

Gather dataclass

Gather(relation: Expression, operand: Expression)

Bases: Expression

Weighted collection of a structural expression on relation entries.

GroupedParameter dataclass

GroupedParameter(
    by: Expression,
    name: str | None = None,
    value: Mapping[Any, float] | None = None,
    default: float | None = None,
)

Bases: Expression

Parameter with one fitted value per category.

Index dataclass

Index(name: str)

Symbolic relation index.

Indexed dataclass

Indexed(base: Expression, indices: tuple[Index, ...])

Bases: Expression

Expression annotated with symbolic indices.

Number dataclass

Number(value: int | float)

Bases: Expression

Fixed numeric literal.

Parameter dataclass

Parameter(name: str, value: float | None = None)

Bases: Expression

Named scalar parameter optimized during fitting.

Reduction dataclass

Reduction(
    indices: tuple[Index, ...],
    operand: Expression,
    relation: Expression | None = None,
)

Bases: Expression

Sum reduction with an optional relation binder.

RelationLift dataclass

RelationLift(
    role: str,
    operand: Expression,
    relation: Expression | None = None,
)

Bases: Expression

Convenience source or target projection used inside an aggregation.

Symbol dataclass

Symbol(name: str, value: Any = None)

Bases: Expression

Named input symbol with an optional bound value.

FitResult dataclass

FitResult(
    expression: Expression,
    parameters: dict[str, Any],
    loss: float,
    success: bool,
    message: str,
    n_iter: int,
)

Result of fitting an expression to target observations.

evaluate

evaluate(
    values: Mapping[str, Any],
    *,
    time: Any = None,
    delay_resolver: Any = None,
    num_nodes: int | None = None,
) -> Any

Evaluate the supplied model or expression.

参数:

名称 类型 描述 默认
values Mapping[str, Any]

Values keyed by symbol name or an evaluation context.

必需
time Any

Optional sample times.

None
delay_resolver Any

Optional callback that resolves delayed values.

None
num_nodes int | None

Explicit node count for indexed expressions.

None

返回:

类型 描述
Any

Predictions from the fitted expression.

RelationField dataclass

RelationField(values: Any, relation: str)

Values stored on the entries of a named relation.

参数:

名称 类型 描述 默认
values Any

Array whose last dimension enumerates relation entries.

必需
relation str

Name of the coordinate-table symbol defining those entries.

必需

aggr

aggr(relation: Any, operand: Any = None) -> Expression

Build and lower target-wise graph aggregation syntax.

参数:

名称 类型 描述 默认
relation Any

Edge relation, or a product containing it when operand is omitted.

必需
operand Any

Message expression to aggregate by target node.

None

返回:

类型 描述
Expression

The equivalent canonical indexed reduction.

function

function(name: str, *arguments: Any) -> Function

Create a supported symbolic function call.

参数:

名称 类型 描述 默认
name str

Function name recognized by the evaluator.

必需
*arguments Any

Function operands.

()

返回:

类型 描述
Function

A symbolic function node.

gather

gather(relation: Any, operand: Any) -> Gather

Collect structural values at the nonzero entries of a relation.

参数:

名称 类型 描述 默认
relation Any

Indexed relation or relation-valued expression.

必需
operand Any

Structural expression evaluated at relation coordinates.

必需

返回:

类型 描述
Gather

A relation-aligned symbolic field.

grouped_param

grouped_param(
    by: Expression,
    *,
    name: str | None = None,
    value: Mapping[Any, float] | None = None,
    default: float | None = None,
) -> GroupedParameter

Create a parameter with one fitted value per category.

参数:

名称 类型 描述 默认
by Expression

Symbol or expression containing category labels.

必需
name str | None

Optional parameter-map name.

None
value Mapping[Any, float] | None

Optional initial values keyed by category.

None
default float | None

Value used for categories absent from value.

None

返回:

类型 描述
GroupedParameter

A category-dependent parameter expression.

param

param(name: str, value: float | None = None) -> Parameter

Create a named scalar parameter.

参数:

名称 类型 描述 默认
name str

Parameter name shared by all matching occurrences.

必需
value float | None

Optional initial or fixed value.

None

返回:

类型 描述
Parameter

A symbolic scalar parameter.

reduction

reduction(
    indices: Index | tuple[Index, ...],
    operand: Any,
    relation: Any = None,
) -> Reduction

Create an indexed sum reduction.

参数:

名称 类型 描述 默认
indices Index | tuple[Index, ...]

Symbolic indices.

必需
operand Any

Expression being reduced or transformed.

必需
relation Any

Relation expression that binds symbolic indices.

None

返回:

类型 描述
Reduction

A symbolic reduction node.

sour

sour(*arguments: Any) -> RelationLift

Project node values onto relation sources inside aggr.

参数:

名称 类型 描述 默认
*arguments Any

Either value or relation, value.

()

返回:

类型 描述
RelationLift

A source projection used by aggregation desugaring.

targ

targ(*arguments: Any) -> RelationLift

Project node values onto relation targets inside aggr.

参数:

名称 类型 描述 默认
*arguments Any

Either value or relation, value.

()

返回:

类型 描述
RelationLift

A target projection used by aggregation desugaring.

count_parameters

count_parameters(
    expression: Expression,
    values: Mapping[str, Any] | None = None,
    *,
    parameters: Mapping[str, Any] | None = None,
) -> int

Count independent fitted values represented by an expression.

Repeated named parameters count once. A grouped parameter counts once per known category. When categories are unavailable, it counts as one unresolved parameter family.

参数:

名称 类型 描述 默认
expression Expression

Symbolic expression to process.

必需
values Mapping[str, Any] | None

Values keyed by symbol name.

None
parameters Mapping[str, Any] | None

Fitted parameter values keyed by parameter name.

None

返回:

类型 描述
int

The number of independent scalar parameter values.

fold_constants

fold_constants(expression: Expression) -> Expression

Evaluate closed numerical subexpressions without reordering terms.

参数:

名称 类型 描述 默认
expression Expression

Symbolic expression to process.

必需

返回:

类型 描述
Expression

A simplified expression with constant-only branches evaluated.

parameter_values

parameter_values(expression: Expression) -> dict[str, Any]

Collect parameter values already bound into an expression.

unbound_parameters

unbound_parameters(expression: Expression) -> list[str]

Return stable names for parameter nodes that have no fitted value.

evaluate

evaluate(
    expression: Expression,
    values: Mapping[str, Any] | None = None,
    *,
    parameters: Mapping[str, Any] | None = None,
    time: Any = None,
    delay_resolver: Callable[..., Any] | None = None,
    num_nodes: int | None = None,
) -> Any

Evaluate an expression without executing arbitrary Python code.

参数:

名称 类型 描述 默认
expression Expression

Symbolic expression to process.

必需
values Mapping[str, Any] | None

Values keyed by symbol name.

None
parameters Mapping[str, Any] | None

Fitted parameter values keyed by parameter name.

None
time Any

Optional sample times.

None
delay_resolver Callable[..., Any] | None

Optional callback that resolves delayed values.

None
num_nodes int | None

Explicit node count for indexed expressions.

None

返回:

类型 描述
Any

The evaluated scalar or NumPy array.

bind_parameters

bind_parameters(
    expression: Expression, parameters: Mapping[str, Any]
) -> Expression

Return an expression whose parameter nodes contain fitted values.

fit

fit(
    expression: Expression,
    values: Mapping[str, Any],
    target: Any,
    *,
    initial: Mapping[str, Any] | None = None,
    method: str = "BFGS",
    options: Mapping[str, Any] | None = None,
    num_nodes: int | None = None,
) -> FitResult

Minimize mean squared error and return fitted parameter values.

参数:

名称 类型 描述 默认
expression Expression

Symbolic expression to process.

必需
values Mapping[str, Any]

Values keyed by symbol name.

必需
target Any

Target name or target values.

必需
initial Mapping[str, Any] | None

Optional initial parameter values.

None
method str

Optimization method name.

'BFGS'
options Mapping[str, Any] | None

Optional optimizer settings.

None
num_nodes int | None

Explicit node count for indexed expressions.

None

返回:

类型 描述
FitResult

Fitted parameters, expression, predictions, and loss.

parse

parse(
    source: str, symbols: Mapping[str, Any] | None = None
) -> Expression

Parse source without using eval or executing user code.

参数:

名称 类型 描述 默认
source str

Source text to parse.

必需
symbols Mapping[str, Any] | None

Optional predefined symbols or numeric constants.

None

返回:

类型 描述
Expression

The parsed canonical expression.

_unary

_unary(name: str) -> Callable[[Any], Expression]

delay

delay(value: Any, delta: Any) -> Expression

Create a delayed-value expression.

参数:

名称 类型 描述 默认
value Any

Time-dependent expression to sample from the past.

必需
delta Any

Scalar or sample-aligned delay interval.

必需

返回:

类型 描述
Expression

A symbolic delay(value, delta) call.