跳转至

API Reference

本页根据 SRHarness 源码中的类型标注与 Google 风格 docstring 自动生成。

公开 API 仅包含各顶层包显式导出(__all__)的类与函数;第三方内嵌模块(_vendor)、Web 路由处理函数以及以下划线 _ 开头的内部实现细节不属于向后兼容范围。

你可以通过右侧目录快速跳转到对应的模块、类与方法。


This reference is generated automatically from SRHarness type annotations and Google-style docstrings.

The public API consists of objects explicitly exported by each package (__all__). Vendored modules (_vendor), web route handlers, and internal helpers prefixed with an underscore (_) are outside the stability contract.

Agents

sr_harness.agents

SRAgent implementations.

__all__ module-attribute

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

Agent

Bases: ABC, FactoryMixin

Abstract base class for tool-using language-model agents.

Provides shared mechanics for binding an :class:~sr_harness.core.AgentContext, initializing enabled tools and the LLM provider adapter, and executing tool calls either serially or in parallel worker processes. Concrete subclasses implement their own conversation loop and domain state management.

run abstractmethod

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

Execute the agent's main task loop.

参数:

名称 类型 描述 默认
*args Any

Positional arguments defined by the concrete agent subclass.

()
**kwargs Any

Keyword arguments defined by the concrete agent subclass.

{}

返回:

名称 类型 描述
Any Any

Task result produced by the concrete agent implementation.

initialize_with_context

initialize_with_context(context: AgentContext) -> None

Bind tools, skills, and the model API to a shared runtime context.

参数:

名称 类型 描述 默认
context AgentContext

Shared agent and tool execution context containing data, workspace access, and runtime settings.

必需

set_messages

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

Store the active conversation messages on the shared tool context.

参数:

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

Conversation messages ordered as sent to the model provider.

必需

execute_action

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

Execute a batch of tool calls sequentially in the current process.

参数:

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

Normalized tool calls emitted by the language model.

必需

返回:

类型 描述
list[ToolCallResult]

list[ToolCallResult]: Tool execution results in the same order as actions.

execute_action_parallel

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

Execute a batch of independent tool calls concurrently across worker processes.

参数:

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

Normalized tool calls emitted by the language model.

必需
max_workers int

Maximum number of worker processes to spawn.

必需

返回:

类型 描述
list[ToolCallResult]

list[ToolCallResult]: Tool execution 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 | None = None,
    skills: list[str] | None = None,
    interaction_manager: InteractionManager,
)

Bases: Agent

Interactive agent that inspects raw workspace files and builds context.data/.

Maintains a multi-turn conversation across user instructions, running sandboxed Python scripts and workspace utilities to clean data, derive variables, and validate context.data/manifest.json before committing structured arrays to the shared :class:~sr_harness.core.AgentContext.

Initialize the data preparation agent.

参数:

名称 类型 描述 默认
llm_provider str

Name of the LLM provider backend (e.g., "openrouter").

必需
llm_model str

Model identifier requested from the provider.

必需
context AgentContext

Shared runtime context holding the workspace and active dataset.

必需
tools list[str] | None

Optional list of enabled tool names. Defaults to DEFAULT_TOOLS.

None
tool_parser str | BaseParser

Tool-call parser name or instance.

'openai'
llm_max_tokens int | None

Optional per-response output token cap.

None
skills list[str] | None

Optional list of enabled skill names.

None
interaction_manager InteractionManager

Manager handling user stop commands and timeline events.

必需

queue_runtime_settings

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

Queue validated model and capability settings to apply before the next turn.

参数:

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

Validated dictionary of provider, model, parser, token-limit, tool, and skill settings.

必需

initialize_with_context

initialize_with_context(context: AgentContext) -> None

Bind configured skills and initialize context-aware data-preparation tools.

参数:

名称 类型 描述 默认
context AgentContext

Shared runtime context providing workspace and dataset access.

必需

run

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

Process a user instruction and run tool turns until preparation completes or pauses.

参数:

名称 类型 描述 默认
instruction str

Natural-language data-preparation request from the user.

必需

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Execution summary containing status, message, finish_reason, turn_count, and the current context schema.

EvaluatorConstructionAgent

EvaluatorConstructionAgent(
    *,
    llm_provider: str,
    llm_model: str,
    context: AgentContext,
    tools: list[BaseTool],
    interaction_manager: InteractionManager,
    tool_parser: str = "openai",
    llm_max_tokens: int | None = None,
    max_steps: int = 16,
    variable_role_updater: Callable[..., dict[str, Any]]
    | None = None,
)

Bases: Agent

Agent that writes, tests, and repairs custom Evaluator subclasses in the workspace.

Inspects built-in evaluator source code, writes a custom :class:~sr_harness.evaluator.DefaultEvaluator subclass under context.evaluator/, and validates it against the active dataset inside the OS sandbox without mutating live search state.

Initialize the evaluator construction agent.

参数:

名称 类型 描述 默认
llm_provider str

Name of the LLM provider backend.

必需
llm_model str

Model identifier requested from the provider.

必需
context AgentContext

Shared runtime context used to validate candidate evaluators.

必需
tools list[BaseTool]

Initialized tool instances exposed to the agent.

必需
interaction_manager InteractionManager

Manager handling stop requests and timeline events.

必需
tool_parser str

Tool-call parser format name (defaults to "openai").

'openai'
llm_max_tokens int | None

Optional per-response output token cap.

None
max_steps int

Maximum number of model-tool turns per user instruction.

16
variable_role_updater Callable[..., dict[str, Any]] | None

Optional workbench callback for explicitly requested role changes.

None

queue_runtime_settings

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

Queue updated model or tool settings to take effect on the next turn.

参数:

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

Validated dictionary of model, parser, token-limit, tool, and skill settings.

必需

run

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

Build or repair a custom evaluator from a natural-language specification.

参数:

名称 类型 描述 默认
instruction str

Natural-language description of the desired evaluation behavior.

必需

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Construction summary including status, message, validated evaluator source and custom_file (when validated), and recorded tool events.

引发:

类型 描述
ValueError

If instruction is empty or whitespace-only.

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 | None = None,
    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

Symbolic-regression agent that coordinates an R-C-L-K search tree.

Drives language models and scientific tools across restarts (R), independent parallel conversation branches (C), iterative refinement steps (L), and local response samples (K), tracking all evaluated formulas and maintaining a global Pareto front.

Initialize the symbolic-regression agent and its R-C-L-K search configuration.

参数:

名称 类型 描述 默认
llm_provider str

Base LLM provider name (e.g., "openrouter", "deepseek").

必需
llm_model str

Base model identifier (e.g., "deepseek/deepseek-v4-flash-0731").

必需
tools list[str] | None

Enabled tool names, or None to use DEFAULT_TOOLS.

None
skills List[str] | None

Enabled skill names, or None to expose all available skills.

None
verbose bool

Whether to emit debug-level runtime logs.

False
tool_parser str | BaseParser

Tool-call parser mode ("openai", "text", "json", "xml") or a :class:~sr_harness.parser.BaseParser instance.

'openai'
save_path Optional[str]

Directory where run logs and search records are written, or None to disable file persistence.

None
run_id str | None

Explicit unique run identifier, or None to generate one.

None
local_sample_size int

Number of model responses sampled per step (K).

1
max_refinement_depth int

Maximum iterative steps per conversation branch (L).

20
global_width int

Number of parallel conversation branches per restart (C).

1
max_restart_loop int

Number of outer restart loops (R).

1
restart_top_k int

Number of top historical formulas injected into each new restart.

1
llm_max_tokens int | None

Optional maximum output tokens per model response.

None
max_workers int

Worker processes for parallel tool calls (0 runs serially).

0
validation_fraction float

Fraction of samples reserved for validation (0 disables splitting).

0.2
split_by str

Validation split strategy ("random" or "ood").

'random'
split_ood_variable str | None

Variable name used to sort samples when split_by="ood".

None
split_random_state int

Random seed for reproducible train/validation splitting.

42
ranking_metric str

Metric name used to rank candidate formulas (defaults to "mse").

'mse'
larger_is_better bool

Whether higher values of ranking_metric rank better.

False
force_initial_diagnostics bool

Whether to automatically run statistical and relationship diagnostics before the first model call of each branch.

False
auto_routing bool

Whether to dynamically route between base and strong models.

True
strong_llm_provider str | None

Provider for the strong model (defaults to llm_provider).

None
strong_llm_model str | None

Optional stronger model identifier for complex steps.

None
context AgentContext | None

Optional shared :class:~sr_harness.core.AgentContext instance.

None
skill_manager SkillManager | None

Optional :class:~sr_harness.skills.SkillManager instance.

None

run

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

Initialize the runtime context and execute a complete symbolic-regression search.

参数:

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

Input feature arrays keyed by variable name.

必需
y Dict[str, ndarray] | ndarray

Target variable array or single-entry mapping {target_name: array}.

必需
problem_description str

Natural-language description of the scientific discovery problem.

必需

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Serializable search summary containing the best formula, Pareto front, all evaluated candidates, and resource usage statistics.

prepare_tool_context

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

Context manager that binds per-run resources to the shared tool context.

参数:

名称 类型 描述 默认
tool_context AgentContext

Shared context passed to initialized tools.

必需

产生:

名称 类型 描述
AgentContext AgentContext

The active context ready for tool initialization.

search

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

Execute the R-C-L-K search loop over an already initialized context.

At each refinement step, builds the prompt, queries the language model for K samples, executes tool calls, records search-tree nodes, extracts candidate formulas, updates the branch conversation buffer, and checks termination conditions.

参数:

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

Input feature arrays keyed by variable name.

必需
y Dict[str, ndarray]

Target variable mapping {target_name: array}.

必需
problem_description str

Natural-language description of the discovery task.

必需

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Final search result dictionary for the completed or stopped run.

create_initial_buffer

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

Build the initial conversation buffer for a new branch, including the opening progress summary.

参数:

名称 类型 描述 默认
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 variable mapping {target_name: array}.

必需
restart_records list[CandidateRecord]

Top historical candidates from prior restarts used to seed the prompt.

必需

返回:

类型 描述
list[Message]

list[Message]: Initial message list ready to start a conversation branch.

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]

Assemble the initial system and user messages before branch buffer metadata is attached.

参数:

名称 类型 描述 默认
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 variable mapping {target_name: array}.

必需
restart_records list[CandidateRecord]

Top historical candidates from prior restarts.

必需

返回:

类型 描述
list[Message]

list[Message]: Two-element list containing the finalized system and user messages.

create_initial_system_prompt

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

Render the system prompt defining the agent's role, workflow, and tool instructions.

参数:

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

Historical candidates from prior restarts (used to adjust guidance).

必需

返回:

名称 类型 描述
str str

Formatted 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

Render the initial user prompt describing the problem, variables, and prior restart results.

参数:

名称 类型 描述 默认
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 variable mapping {target_name: array}.

必需
restart_records list[CandidateRecord]

Top historical candidates seeded from earlier restarts.

必需

返回:

名称 类型 描述
str str

Formatted user prompt text.

customize_initial_prompts

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

Hook for subclasses to modify initial system and user messages before they enter the buffer.

参数:

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

Initial system and user message dictionaries.

必需
X dict[str, ndarray]

Input feature arrays keyed by variable name.

必需
y dict[str, ndarray]

Target variable mapping {target_name: array}.

必需

返回:

类型 描述
list[Message]

list[Message]: Customized message list to insert into the branch buffer.

on_buffer_messages_added

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

Hook invoked whenever new messages are appended to a branch conversation buffer.

参数:

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

Messages that were just appended to the buffer.

必需
**coordinate int

Optional R, C, and L coordinates for the active step.

{}

prepare_model_messages

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

Build the full message list sent to the language model for step (R, C, L).

Runs initial diagnostics on L=1 when force_initial_diagnostics is enabled and strips internal buffer metadata keys before sending.

参数:

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

Current branch conversation 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]]: Provider-ready conversation messages.

prepare_iteration

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

Apply any pending runtime updates or control commands before step (R, C, L) begins.

参数:

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

Current branch conversation 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: Control transition token ("stop", "next_c", "next_r"), or None to proceed with the step.

refresh_data

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

Synchronize the agent's feature and target views if the shared context.data revision changed.

返回:

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

dict[str, Any] | None: Summary of variable or role changes when a new data revision was applied, or None if the dataset is unchanged.

finish_iteration

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

Check whether the search should terminate at the end of step (R, C, L).

参数:

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

Current branch conversation 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: Terminal status string (such as "early_stopped") when stopping criteria are met, or None to continue searching.

run_initial_diagnostics

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

Execute opening statistical, relationship, and skill diagnostics for the start of a branch.

参数:

名称 类型 描述 默认
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]: Formatted user-role message containing the diagnostic outputs.

request_llm

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

Route the request to the appropriate model tier and sample K responses for step (R, C, L).

参数:

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

Provider-ready conversation messages.

必需
R int

One-based restart index.

必需
L int

One-based refinement-step index.

必需
C int

One-based conversation-branch index.

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

Optional callback receiving live streaming progress updates.

None

返回:

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

tuple[list[APICallSample], Usage | None]: Sampled assistant responses and aggregated token/cost usage.

execute_tool_calls

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

Execute all tool calls across the K sampled model responses for step (R, C, L).

参数:

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

Sampled 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]]

list[list[ToolCallResult]]: Tool execution results grouped by sample index.

record_tool_calls

record_tool_calls(
    tool_calls: List[ToolCall],
    results: List[ToolCallResult],
    R: int,
    L: int,
    C: int,
    forced: bool = False,
) -> None

Append tool call inputs and outputs to tool_calls.jsonl and update usage counters.

参数:

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

Tool calls executed in the current batch.

必需
results List[ToolCallResult]

Corresponding tool execution results.

必需
R int

One-based restart index.

必需
L int

One-based refinement-step index.

必需
C int

One-based conversation-branch index.

必需
forced bool

Whether the calls were triggered by automatic initial diagnostics rather than emitted by the model.

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]]

Select the best-performing K sample to continue the branch and fold in sibling analysis results.

参数:

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

Current branch conversation buffer.

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

Sampled model responses for the current step.

必需
results_list List[List[ToolCallResult]]

Tool results aligned with response_list.

必需
node_parents Dict[str, str]

Mapping of parent node IDs by link relation ("strong" / "weak").

必需
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]]

tuple[list[Message], dict[str, str]]: Updated conversation buffer and the parent-node mapping for the next refinement step.

build_response_followup_messages

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

Build any framework follow-up messages to append after processing model responses.

参数:

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

Sampled model responses for the current step.

必需
results_list list[list[ToolCallResult]]

Tool results aligned with response_list.

必需
R int

One-based restart index.

必需
L int

One-based refinement-step index.

必需
C int

One-based conversation-branch index.

必需

返回:

类型 描述
list[Message]

list[Message]: Follow-up messages to append (empty in non-interactive mode).

build_progress_message

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

Format a user-role message summarizing remaining step budget and the current Pareto front.

参数:

名称 类型 描述 默认
L int

Next one-based refinement-step index.

必需

返回:

类型 描述
dict[str, str]

dict[str, str]: User-role message injected before the next model request.

push_candidate

push_candidate(record: CandidateRecord) -> None

Add or update a candidate formula record in the run state.

参数:

名称 类型 描述 默认
record CandidateRecord

Evaluated candidate formula record.

必需

collect_candidates

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

Extract valid candidate formulas from tool results and update the global leaderboard.

参数:

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

Sampled model responses for the current step.

必需
results_list list[list[ToolCallResult]]

Tool results aligned with response_list.

必需
R int

One-based restart index.

必需
L int

One-based refinement-step index.

必需
C int

One-based conversation-branch index.

必需

返回:

类型 描述
list[CandidateRecord]

list[CandidateRecord]: All candidate records ranked under the active metric.

log_info

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

Log step timing, token/cost usage, best candidate score, and tool-call counts.

参数:

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

Sampled 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

Update cumulative token and cost counters and append raw responses to response.jsonl.

参数:

名称 类型 描述 默认
llm_result Any

Completed :class:~sr_harness.core.APICallSummary from the provider.

必需
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: Step and cumulative token/price usage dictionary, or None if usage data is unavailable.

record_search_iteration

record_search_iteration(
    response_list: list[APICallSample],
    results_list: list[list[ToolCallResult]],
    parent_nodes: dict[str, str],
    prompt: list[Message],
    usage: Usage | None,
    R: int,
    L: int,
    C: int,
) -> None

Register search-tree nodes for all K samples in step (R, C, L).

参数:

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

Sampled model responses for the current step.

必需
results_list list[list[ToolCallResult]]

Tool results aligned with response_list.

必需
parent_nodes dict[str, str]

Mapping of parent node IDs by relation type.

必需
prompt list[Message]

Prompt messages sent to the model for this step.

必需
usage Usage | None

Step and cumulative token/cost usage dictionary.

必需
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 the current (R, C, L, K) search coordinates as a human-readable string.

参数:

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

Current one-based restart index, or None before starting.

必需
L int | None

Current one-based refinement-step index, or None.

必需
C int | None

Current one-based conversation-branch index, or None.

必需

返回:

名称 类型 描述
str str

Formatted coordinate string such as "(R=1/1) × (C=1/1) × (L=2/20) × (K=1)".

get_ranking_metric

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

Extract the configured ranking metric value and its display label from a candidate record.

参数:

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

:class:~sr_harness.core.CandidateRecord or candidate dictionary.

必需

返回:

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

tuple[str | None, float | int | None]: Pair of (display_label, metric_value), or (None, None) if the metric is missing.

candidate_sort_key

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

Compute a (metric_key, complexity_key) tuple for sorting candidates (smaller sorts first).

参数:

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

:class:~sr_harness.core.CandidateRecord or candidate dictionary.

必需

返回:

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

tuple[float, float] | None: Sort key tuple where lower values indicate higher rank, or None if the candidate lacks a finite ranking metric.

candidate_to_dict staticmethod

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

Convert a :class:~sr_harness.core.CandidateRecord into a flat dictionary for formatting utilities.

参数:

名称 类型 描述 默认
record CandidateRecord

Candidate record to convert.

必需

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Flattened candidate dictionary with top-level split results.

best_candidate

best_candidate() -> CandidateRecord | None

Return the highest-ranked candidate formula discovered so far.

返回:

类型 描述
CandidateRecord | None

CandidateRecord | None: Top-ranked candidate record, or None if no valid candidate has been evaluated yet.

get_pareto_front

get_pareto_front() -> list[CandidateRecord]

Return candidate formulas on the accuracy-versus-complexity Pareto front.

返回:

类型 描述
list[CandidateRecord]

list[CandidateRecord]: Pareto-optimal candidates ordered from simplest to most accurate.

build_search_result

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

Assemble a serializable final result dictionary for the run.

参数:

名称 类型 描述 默认
status str

Terminal run status ("completed", "early_stopped", "interrupted", or "failed").

必需
R int | None

Final one-based restart index, or None.

必需
L int | None

Final one-based refinement-step index, or None.

必需
C int | None

Final one-based conversation-branch index, or None.

必需

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Complete search result dictionary ready for JSON serialization.

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 | None = None,
    max_workers: int = 0,
    validation_fraction: float = 0.2,
    split_by: str = "random",
    split_ood_variable: str | None = None,
    split_random_state: int = 42,
    ranking_metric: str = "mse",
    larger_is_better: bool = False,
    use_workspace: bool = False,
    workspace_files: List[str | Path] | None = None,
    force_initial_diagnostics: bool = False,
    pause_on_truncated_response: bool = True,
    tool_free_stop_review_rounds: int = 1,
    stop_guard_mode: str = "none",
    stop_guard_metric: str | None = None,
    stop_guard_threshold: float | None = None,
    stop_guard_split: str = "validation",
    stop_guard_larger_is_better: bool = True,
    auto_routing: bool = True,
    strong_llm_provider: str | None = None,
    strong_llm_model: str | None = None,
    context: AgentContext | None = None,
    skill_manager: SkillManager | None = None,
)

Bases: SRAgent

Interactive symbolic-regression agent with live timeline events and human-in-the-loop controls.

Extends :class:~sr_harness.agents.SRAgent with real-time event publishing, safe pause and force-interrupt boundaries, live settings and data refresh between turns, configurable stop guards, and user guidance injection.

Initialize the interactive symbolic-regression agent.

参数:

名称 类型 描述 默认
llm_provider str

Base LLM provider name.

必需
llm_model str

Base model identifier.

必需
interaction_manager SRInteractionManager

Manager coordinating pause/resume commands, branch transitions, and live timeline events.

必需
tools list[str] | None

Enabled tool names, or None to use DEFAULT_TOOLS.

None
skills List[str] | None

Enabled skill names, or None to expose all available skills.

None
verbose bool

Whether to emit debug-level runtime logs.

False
tool_parser str | BaseParser

Tool-call parser mode or :class:~sr_harness.parser.BaseParser instance.

'openai'
save_path Optional[str]

Directory where run logs are persisted, or None.

None
run_id str | None

Explicit unique run identifier, or None to generate one.

None
local_sample_size int

Number of model responses sampled per step (K).

1
max_refinement_depth int

Maximum iterative steps per branch (L).

50
global_width int

Number of parallel conversation branches per restart (C).

1
max_restart_loop int

Number of outer restart loops (R).

1
restart_top_k int

Number of top historical formulas injected into each new restart.

1
llm_max_tokens int | None

Optional maximum output tokens per model response.

None
max_workers int

Worker processes for parallel tool calls (0 runs serially).

0
validation_fraction float

Fraction of samples reserved for validation.

0.2
split_by str

Validation split strategy ("random" or "ood").

'random'
split_ood_variable str | None

Variable name used to order OOD splits.

None
split_random_state int

Random seed for train/validation splitting.

42
ranking_metric str

Metric name used to rank candidate formulas.

'mse'
larger_is_better bool

Whether higher values of ranking_metric are better.

False
use_workspace bool

Whether to create a managed workspace when none is supplied.

False
workspace_files List[str | Path] | None

Optional host files or directories to mount read-only.

None
force_initial_diagnostics bool

Whether to run opening diagnostics at L=1.

False
pause_on_truncated_response bool

Whether to pause at the end of a turn if a model response hits its output token limit.

True
tool_free_stop_review_rounds int

Number of recent turns sent to a separate tool-free check when the model emits no tool calls (0 disables).

1
stop_guard_mode str

Stop-permission condition ("none", "best_in_topk", "metric_threshold", or "budget_exhausted").

'none'
stop_guard_metric str | None

Metric inspected when stop_guard_mode="metric_threshold".

None
stop_guard_threshold float | None

Target metric threshold for metric_threshold mode.

None
stop_guard_split str

Dataset split ("validation" or "train") checked by the metric threshold guard.

'validation'
stop_guard_larger_is_better bool

Whether the stop-guard metric is larger-is-better.

True
auto_routing bool

Whether to dynamically route between base and strong models.

True
strong_llm_provider str | None

Provider for the strong model.

None
strong_llm_model str | None

Optional stronger model identifier.

None
context AgentContext | None

Optional shared :class:~sr_harness.core.AgentContext.

None
skill_manager SkillManager | None

Optional :class:~sr_harness.skills.SkillManager.

None

on_buffer_messages_added

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

Publish prompt_added timeline events whenever system or user messages enter the buffer.

参数:

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

Newly appended conversation messages.

必需
**coordinate int

Active R, C, and L search coordinates.

{}

initialize_with_context

initialize_with_context(context: AgentContext) -> None

Bind tools and API to the shared context and attach the cancellation signal.

参数:

名称 类型 描述 默认
context AgentContext

Shared runtime context for the interactive session.

必需

prepare_tool_context

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

Bind interactive workspace and stop-check hooks to the tool context for the duration of a run.

参数:

名称 类型 描述 默认
tool_context AgentContext

Shared context used to initialize tools.

必需

产生:

名称 类型 描述
AgentContext AgentContext

Context configured with workspace access and finish-search hooks.

prepare_iteration

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

Handle pause requests, queued user messages, setting updates, and data refreshes before a turn.

参数:

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

Current branch conversation 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: Branch transition command ("next_c" or "next_r"), or None to continue the current branch.

build_data_refresh_message staticmethod

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

Format a user-role notification describing variable or role updates in context.data.

参数:

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

Revision change dictionary returned by :meth:refresh_data.

必需

返回:

类型 描述
dict[str, str]

dict[str, str]: User-role message informing the model of the updated dataset.

finish_iteration

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

Check explicit finish_search requests or tool-free stop reviews at the end of a turn.

Unlike non-interactive runs, satisfying a stop condition pauses the agent at a safe boundary rather than terminating the session thread, allowing the user to inspect results and resume exploration if desired.

参数:

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

Current branch conversation 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: Always None so the interactive session remains resumable; pauses are coordinated through self.interaction_manager.

build_response_followup_messages

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

Drain and return any follow-up user prompts generated during the current step (such as rejected stop reasons).

参数:

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

Sampled model responses for the current step.

必需
results_list list[list[ToolCallResult]]

Tool results aligned with response_list.

必需
R int

One-based restart index.

必需
L int

One-based refinement-step index.

必需
C int

One-based conversation-branch index.

必需

返回:

类型 描述
list[Message]

list[Message]: Follow-up messages to append to the conversation buffer.

create_initial_system_prompt

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

Create the interactive system prompt without advertising workspace-mutation tools.

参数:

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

Top historical candidates from prior restarts.

必需

返回:

名称 类型 描述
str str

System prompt tailored for interactive symbolic regression.

normalize_system_prompt classmethod

normalize_system_prompt(prompt: str) -> str

Strip legacy workspace-tool instructions from a saved or user-submitted system prompt.

参数:

名称 类型 描述 默认
prompt str

Raw system prompt string.

必需

返回:

名称 类型 描述
str str

Cleaned system prompt with capability-neutral guidance.

customize_initial_prompts

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

Apply variable descriptions and user/system prompt overrides from the WebUI.

参数:

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

Generated initial system and user messages.

必需
X dict[str, Any]

Input feature arrays keyed by variable name.

必需
y dict[str, Any]

Target variable mapping {target_name: array}.

必需

返回:

类型 描述
list[Message]

list[Message]: Messages incorporating any active UI overrides.

request_llm

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

Sample model responses while streaming live delta events to the WebUI timeline.

Handles mid-stream force-interruptions and optional pause-on-truncation policies.

参数:

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

Provider-ready conversation messages.

必需
R int

One-based restart index.

必需
L int

One-based refinement-step index.

必需
C int

One-based conversation-branch index.

必需

返回:

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

tuple[list[APICallSample], Usage]: Completed or partially recovered model responses and token/cost usage.

tool_schema

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

Return the JSON parameter schema for an initialized tool by name.

参数:

名称 类型 描述 默认
name str

Registered tool name.

必需

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Tool parameter JSON schema, or an empty dict if not found.

execute_action

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

Execute tool calls sequentially while publishing start/completion events and honoring force-pause.

参数:

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

Normalized tool calls to execute.

必需

返回:

类型 描述
list[ToolCallResult]

list[ToolCallResult]: Tool execution results in call order.

execute_tool_calls

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

Bind the current refinement step L and execute tool calls for all K samples.

参数:

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

Sampled 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]]

list[list[ToolCallResult]]: Tool results grouped by sample index.

collect_candidates

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

Collect candidate formulas and publish a topk_updated event to the WebUI.

参数:

名称 类型 描述 默认
*args Any

Positional arguments forwarded to :meth:SRAgent.collect_candidates.

()
**kwargs Any

Keyword arguments forwarded to :meth:SRAgent.collect_candidates.

{}

返回:

类型 描述
list[CandidateRecord]

list[CandidateRecord]: Ranked candidate records.

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 publish timeline cards for framework-initiated diagnostics.

参数:

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

Executed tool calls.

必需
results list[ToolCallResult]

Corresponding tool execution results.

必需
R int

One-based restart index.

必需
L int

One-based refinement-step index.

必需
C int

One-based conversation-branch index.

必需
forced bool

Whether the calls were triggered automatically by initial diagnostics.

False

execute_action_parallel

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

Disallow parallel tool execution in interactive mode.

参数:

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

Tool calls to execute.

必需
max_workers int

Requested worker count.

必需

引发:

类型 描述
NotImplementedError

Always raised because interactive tool events and cancellation hooks are managed serially.

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__ = [
    "APICallSample",
    "APICallSummary",
    "AgentContext",
    "CandidateRecord",
    "ContextManifestError",
    "ParentLink",
    "ParentRelation",
    "SearchCoordinate",
    "SearchNode",
    "SearchResult",
    "SearchRunState",
    "ToolCall",
    "ToolCallResult",
    "ToolMetadata",
    "inspect_context_data",
    "json_value",
    "load_context_data",
    "update_context_data_descriptions",
]

APICallSample dataclass

APICallSample(
    content: str | None,
    tool_calls: list[ToolCall] | None = None,
    message_extra: dict[str, Any] | None = None,
    finish_reason: str | None = None,
)

Single assistant completion sample normalized across model providers.

Stores the assistant text content, parsed tool_calls, completion finish_reason, and any provider-specific message_extra fields (such as reasoning traces). Accessing :attr:message reconstructs a provider-ready assistant message dictionary on demand.

Initialize a normalized assistant response sample.

参数:

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

Assistant text content, or None when only tool calls were emitted.

必需
tool_calls list[ToolCall] | None

Normalized tool calls extracted from the response.

None
message_extra dict[str, Any] | None

Additional provider-specific message fields (e.g., reasoning).

None
finish_reason str | None

Provider stop reason (such as "stop", "tool_calls", or "length").

None

tool_calls property

tool_calls: list[ToolCall]

Return a copy of the normalized tool calls emitted in this sample.

返回:

类型 描述
list[ToolCall]

list[ToolCall]: Normalized tool call objects.

reasoning property

reasoning: Any

Extract the model's reasoning trace across provider-specific field formats.

返回:

名称 类型 描述
Any Any

Reasoning text or structured reasoning blocks, or None if absent.

truncated property

truncated: bool

Return whether generation stopped because it hit the output token limit.

返回:

名称 类型 描述
bool bool

True when finish_reason is "length" or "max_tokens".

message property

message: dict[str, Any]

Reconstruct a provider-compatible assistant message dictionary for conversation history.

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Assistant message containing role, content, provider extras, and serialized tool_calls.

APICallSummary dataclass

APICallSummary(gen: Iterator[APICallSample])

Iterable wrapper over a provider response generator that captures aggregate usage and status.

Iterating over an :class:APICallSummary yields individual :class:APICallSample instances as they complete, then populates ok, error, token_usage, money_usage, and extra from the generator's final return value.

truncated property

truncated: bool

Return whether any yielded sample in this call was truncated by the token limit.

返回:

名称 类型 描述
bool bool

True if at least one sample has truncated == True.

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: Workspace | None = None,
)

Authoritative runtime context shared across agents, evaluators, and tools.

Holds the active dataset arrays (data), variable and axis metadata, selected target and feature names, the active :class:~sr_harness.evaluator.DefaultEvaluator, the conversation :class:~sr_harness.runtime.Workspace, and cached training/validation views.

参数:

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

Runtime configuration namespace shared by agents, evaluators, and tools.

None
data dict[str, Any] | None

Mapping of variable and axis names to NumPy arrays.

None
target str | None

Name of the active dependent variable, if selected.

None
variable_descriptions dict[str, str] | None

Human-readable descriptions keyed by variable or axis name.

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

Mapping from each variable name to its tuple of axis names.

None
variable_structures dict[str, str] | None

Mapping from edge-aligned variable names to their relation name.

None
relation_names set[str] | None

Set of variable names representing graph or hypergraph edge tables.

None
num_nodes int | None

Total node count when graph or hypergraph relations are present.

None
evaluator DefaultEvaluator | object

Evaluator instance used for splitting, parameter fitting, and scoring.

_DEFAULT_EVALUATOR
workspace Workspace | None

Optional managed workspace accessible to workspace-aware tools.

None

Initialize an agent runtime context.

参数:

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

Runtime configuration namespace.

None
data dict[str, Any] | None

Mapping of variable and axis names to NumPy arrays.

None
target str | None

Name of the active target variable.

None
variable_descriptions dict[str, str] | None

Descriptions keyed by variable or axis name.

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

Axis tuples keyed by variable name.

None
variable_structures dict[str, str] | None

Relation variable names keyed by edge-aligned variable name.

None
relation_names set[str] | None

Names of graph or hypergraph relation variables.

None
num_nodes int | None

Node count for relational datasets.

None
evaluator DefaultEvaluator | object

Active formula evaluator instance.

_DEFAULT_EVALUATOR
workspace Workspace | None

Optional managed workspace instance.

None

train_split property

train_split: AgentContext

Return the cached training split context, calling evaluator.split(self) on first access.

返回:

名称 类型 描述
AgentContext AgentContext

Context view containing the training split arrays.

validation_split property

validation_split: AgentContext

Return the cached validation split context, calling evaluator.split(self) on first access.

返回:

名称 类型 描述
AgentContext AgentContext

Context view containing the validation split arrays.

invalidate_splits

invalidate_splits() -> None

Clear cached training and validation context splits so they are recomputed on next access.

with_data

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

Create a lightweight view over data that shares runtime arguments and metadata with this context.

参数:

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

Replacement mapping of variable and axis arrays.

必需

返回:

名称 类型 描述
AgentContext AgentContext

New context view bound to data.

axis_names

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

Return all coordinate axis names referenced by variables in first-appearance order.

返回:

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

tuple[str, ...]: Ordered axis names.

variable_names

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

Return all non-axis variable names in manifest order.

返回:

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

tuple[str, ...]: Ordered variable names.

feature_names

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

Return selected input feature names (excluding axes and the active target).

返回:

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

tuple[str, ...]: Active feature variable names.

commit_context_data

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

Replace the live dataset with a validated load_context_data() bundle and increment data_revision.

参数:

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

Validated dataset dictionary returned by :func:load_context_data.

必需

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Summary containing the new revision, variables, axes, relation_names, and num_nodes.

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 aligned 1D/tabular arrays directly into the live context and increment data_revision.

参数:

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

Mapping of column names to NumPy-compatible arrays.

必需
target str

Name of the target variable to predict.

必需
features list[str] | None

Names of input feature variables to retain.

None
variable_descriptions dict[str, str] | None

Optional human-readable descriptions by column name.

None

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Summary containing the new revision, target, features, columns, and rows.

add_features

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

Append new sample-aligned feature arrays to the active dataset while keeping the current target.

参数:

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

Mapping of new feature names to aligned arrays.

必需
descriptions dict[str, str] | None

Optional descriptions for the newly added features.

None

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Updated commit summary after merging the new features.

引发:

类型 描述
ValueError

If no target variable is currently configured or feature shapes do not align.

update_selection

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

Update the active target, selected input features, and variable descriptions.

参数:

名称 类型 描述 默认
target str

Name of the target variable.

必需
features list[str]

List of input feature variable names.

必需
variable_descriptions dict[str, str] | None

Optional updated descriptions keyed by variable or axis name.

None

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Summary with the incremented revision, target, and features.

schema

schema() -> dict[str, Any]

Return a JSON-serializable summary of variables, shapes, dtypes, axes, and roles in the context.

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Schema dictionary suitable for WebUI previews and diagnostics.

ContextManifestError

Bases: ValueError

Exception raised when context.data/manifest.json or its referenced .npy files fail validation.

CandidateRecord dataclass

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

Evaluated candidate formula together with its provenance node and split metrics.

属性:

名称 类型 描述
formula str

Canonical string representation of the fitted candidate expression.

node_id str

Identifier of the search node that produced this candidate.

details dict[str, Any]

Evaluation payload containing data_split_results, complexity, and optional residual diagnostics.

complexity property

complexity: Any

Return the structural complexity score of the candidate formula.

返回:

名称 类型 描述
Any Any

Integer/float complexity value from details, or None if unavailable.

split_metrics

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

Return the metric dictionary for a specific dataset split (e.g., "train" or "validation").

参数:

名称 类型 描述 默认
split str

Name of the data split to look up.

必需

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Metrics recorded for split, or an empty dictionary if absent.

metric

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

Look up a single numeric metric value on the specified data split.

参数:

名称 类型 描述 默认
name str

Metric key (such as "mse", "rmse", or "r2").

必需
split str

Name of the data split (e.g., "validation" or "train").

必需

返回:

名称 类型 描述
Any Any

Metric value if present on split (or at the top level of details), otherwise None.

to_dict

to_dict() -> dict[str, Any]

Serialize the candidate record for result.json or state snapshots.

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Dictionary containing formula, node_id, and details.

display_dict

display_dict() -> dict[str, Any]

Build a flattened dictionary with top-level mse, r2, and complexity for UI cards.

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Flattened candidate dictionary ready for frontend rendering.

ParentLink(parent_node_id: str, relation: ParentRelation)

Directed link connecting a search-tree node to one of its parent nodes.

属性:

名称 类型 描述
parent_node_id str

Unique node identifier of the parent search node.

relation ParentRelation

Link strength—"strong" for the primary conversation continuation or "weak" for sibling tool-output context.

to_dict

to_dict() -> dict[str, str]

Serialize the parent link to a JSON-compatible dictionary.

返回:

类型 描述
dict[str, str]

dict[str, str]: Dictionary with parent_node_id and relation.

SearchCoordinate dataclass

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

Four-dimensional (R, C, L, K) coordinate identifying a node in the symbolic-regression search tree.

属性:

名称 类型 描述
R int

One-based outer restart index.

C int

One-based parallel conversation-branch index.

L int

One-based iterative refinement-step index.

K int

One-based local response-sample index.

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 a single (R, C, L, K) node in the search tree.

属性:

名称 类型 描述
run_id str

Unique identifier of the owning search run.

node_id str

Unique identifier of this search node.

node_label str

Short human-readable label (e.g., "R1-C1-L2-K1").

coordinate SearchCoordinate

Structured :class:SearchCoordinate for this node.

parents tuple[ParentLink, ...]

Tuple of :class:ParentLink references to predecessor nodes.

created_at str

UTC ISO-8601 timestamp when the node was recorded.

core dict[str, Any]

Lightweight summary (formula, metrics, tool names, content preview).

detail dict[str, Any]

Full prompt messages, raw response, tool call outputs, and usage.

to_dict

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

Serialize the search node to a dictionary for logging or WebUI streaming.

参数:

名称 类型 描述 默认
include_detail bool

If True, include the full detail payload (prompts, raw responses, and full tool results); if False, omit detail for lightweight tree rendering.

True

返回:

类型 描述
dict[str, Any]

dict[str, Any]: JSON-serializable node dictionary.

SearchResult dataclass

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

Final summary of a completed, early-stopped, interrupted, or failed symbolic-regression run.

属性:

名称 类型 描述
status Literal['completed', 'early_stopped', 'interrupted', 'failed']

Terminal run status string.

progress str

Human-readable (R, C, L, K) progress summary.

candidates list[CandidateRecord]

Ranked list of all unique :class:CandidateRecord instances.

pareto_front list[int]

Indices into candidates forming the Pareto front.

best_candidate int | None

Index of the top-ranked candidate in candidates (usually 0), or None when no valid candidate was found.

to_dict

to_dict() -> dict[str, Any]

Serialize the search result for result.json and API responses.

返回:

类型 描述
dict[str, Any]

dict[str, Any]: JSON-serializable dictionary of run status, candidates, Pareto front indices, and best candidate index.

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 and on-disk state tracker for one symbolic-regression run.

Records every (R, C, L, K) search node, deduplicates and ranks candidate formulas, computes the Pareto front, and optionally persists run.json, nodes.jsonl, and result.json under save_path.

Initialize the search run state and write run.json when save_path is provided.

参数:

名称 类型 描述 默认
save_path str | Path | None

Directory for persisting run logs, or None for in-memory only.

必需
ranking_metric str

Metric name used to rank candidates (e.g., "mse").

必需
larger_is_better bool

Whether larger values of ranking_metric are preferred.

必需
agent_metadata dict[str, Any] | None

Optional startup configuration metadata written to run.json.

None
run_id str | None

Optional explicit run identifier (generated automatically when omitted).

None

node_count property

node_count: int

Return the total number of search nodes recorded so far.

返回:

名称 类型 描述
int int

Number of nodes in the search tree.

latest_coordinate property

latest_coordinate: SearchCoordinate | None

Return the coordinate of the most recently recorded search node.

返回:

类型 描述
SearchCoordinate | None

SearchCoordinate | None: Latest coordinate, or None if no nodes exist yet.

now staticmethod

now() -> str

Return the current UTC timestamp formatted as an ISO-8601 string.

返回:

名称 类型 描述
str str

UTC timestamp ending with "Z".

node_label staticmethod

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

Format a compact display label for a search coordinate.

参数:

名称 类型 描述 默认
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

Label formatted as "R{R}-C{C}-L{L}-K{K}".

node_id

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

Build the globally unique node identifier for coordinate (R, C, L, K) in this run.

参数:

名称 类型 描述 默认
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

Unique node identifier "{run_id}:R{R}-C{C}-L{L}-K{K}".

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

Create a validated :class:ParentLink connecting a child node to parent_node_id.

参数:

名称 类型 描述 默认
parent_node_id str

Unique identifier of the parent search node.

必需
relation ParentRelation

Link relation type ("strong" or "weak").

必需

返回:

名称 类型 描述
ParentLink ParentLink

Constructed parent link instance.

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

Record SearchNode entries for all K local samples in step (R, C, L).

参数:

名称 类型 描述 默认
response_list list

Sampled model responses for the step.

必需
results_list list

Tool execution results aligned with response_list.

必需
parents tuple[ParentLink, ...]

Tuple of :class:ParentLink objects inherited from previous steps.

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

Prompt messages sent to the model for this step.

必需
usage dict[str, Any]

Token and cost accounting dictionary for the step.

必需
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

Insert a candidate formula or replace an existing record for the same formula if the new one ranks higher.

参数:

名称 类型 描述 默认
candidate CandidateRecord

Newly evaluated :class:CandidateRecord.

必需

返回:

名称 类型 描述
bool bool

True if the candidate was added or improved upon an existing entry; False if an equal or better record for the same formula already existed.

update_diagnostics

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

Attach residual diagnostic metadata to an existing candidate formula record.

参数:

名称 类型 描述 默认
formula str

Canonical formula string identifying the candidate.

必需
diagnostics dict[str, Any]

Diagnostic dictionary to store under details["diagnostics"].

必需

ranked_candidates

ranked_candidates() -> list[CandidateRecord]

Return all recorded candidates sorted from best to worst under the active ranking metric.

返回:

类型 描述
list[CandidateRecord]

list[CandidateRecord]: Sorted list of candidate records.

pareto_indices

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

Compute the indices of candidates that lie on the accuracy-complexity Pareto front.

参数:

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

Optional candidate list to inspect (defaults to :meth:ranked_candidates).

None

返回:

类型 描述
list[int]

list[int]: Zero-based indices into candidates ordered by non-decreasing complexity.

result

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

Build and optionally persist the :class:SearchResult snapshot for the current state.

参数:

名称 类型 描述 默认
status str

Run completion status string.

必需
progress str

Human-readable (R, C, L, K) progress string.

必需

返回:

名称 类型 描述
SearchResult SearchResult

Snapshot containing ranked candidates and Pareto front indices.

records

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

Return serialized search-tree node dictionaries in creation order.

参数:

名称 类型 描述 默认
include_detail bool

Whether to include full prompt/response/tool payloads.

False

返回:

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

list[dict[str, Any]]: Serialized node records.

export_state

export_state() -> dict[str, Any]

Export a JSON-serializable snapshot of all nodes and candidates for session persistence.

返回:

类型 描述
dict[str, Any]

dict[str, Any]: State dictionary that can be passed to :meth:from_state.

from_state classmethod

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

Reconstruct a :class:SearchRunState instance from an :meth:export_state snapshot.

参数:

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

Previously exported state dictionary.

必需
save_path str | Path | None

Optional directory for subsequent file persistence.

None

返回:

名称 类型 描述
SearchRunState 'SearchRunState'

Restored search run state.

node_record

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

Look up and serialize a single search node by its node_id (including full details).

参数:

名称 类型 描述 默认
node_id str

Unique node identifier to look up.

必需

返回:

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

dict[str, Any] | None: Serialized node dictionary, or None if not found.

ToolCall dataclass

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

Normalized representation of a single tool invocation requested by a language model.

属性:

名称 类型 描述
name str

Registered name of the tool to invoke.

params dict

Dictionary of keyword arguments passed to tool.execute(**params).

id str | None

Optional provider-assigned tool-call identifier.

raw Any

Optional raw provider tool-call structure.

raw_str str | None

Optional raw text snippet from which the call was parsed.

ToolCallResult dataclass

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

Standardized outcome returned by BaseTool.__call__().

result preserves the full machine-readable dictionary for run logging and candidate extraction, whereas result_str is a concise, length-bounded text summary formatted for the language model's next turn.

get

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

Look up a key inside the structured result dictionary when result is a mapping.

参数:

名称 类型 描述 默认
key str

Dictionary key to look up in self.result.

必需
default Any

Value returned when key is absent.

None

返回:

名称 类型 描述
Any Any

Value associated with key, or default.

ToolMetadata dataclass

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

Declarative metadata describing a tool's name, purpose, and JSON parameter schema.

When description or parameters are omitted, :class:~sr_harness.tools.BaseTool infers them automatically from execute()'s type annotations and Google-style docstring.

inspect_context_data

inspect_context_data(
    directory: str | Path,
    *,
    workspace: Workspace | None = None,
) -> dict[str, Any]

Validate a context.data/ directory and return structured errors and warnings without raising.

参数:

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

Path to the context.data/ directory to inspect.

必需
workspace Workspace | None

Optional :class:~sr_harness.runtime.Workspace used to enforce safe file reads.

None

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Diagnostic report with valid, errors, warnings, variables, axes, relations, and num_nodes.

load_context_data

load_context_data(
    directory: str | Path,
    *,
    workspace: Workspace | None = None,
) -> dict[str, Any]

Validate and load a context.data/ directory into arrays and metadata for :class:AgentContext.

参数:

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

Path to the context.data/ directory containing manifest.json and .npy files.

必需
workspace Workspace | None

Optional :class:~sr_harness.runtime.Workspace used to enforce safe file reads.

None

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Dictionary containing data, variable_descriptions, variable_axes, variable_structures, relation_names, num_nodes, manifest, and warnings.

引发:

类型 描述
ContextManifestError

If manifest.json or any referenced .npy array violates the format rules.

update_context_data_descriptions

update_context_data_descriptions(
    directory: str | Path,
    descriptions: dict[str, str],
    *,
    workspace: Workspace | None = None,
) -> dict[str, Any]

Update variable and axis descriptions in context.data/manifest.json and reload the dataset.

Validates the entire context.data/ directory first, then writes updated non-empty description strings atomically (or in place when the parent directory is read-only but manifest.json is writable).

参数:

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

Path to the context.data/ directory.

必需
descriptions dict[str, str]

Mapping of variable or axis names to updated description strings.

必需
workspace Workspace | None

Optional :class:~sr_harness.runtime.Workspace enforcing write permissions.

None

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Reloaded dataset dictionary matching :func:load_context_data.

json_value

json_value(value: Any) -> Any

Recursively convert runtime objects and NumPy scalars/arrays into standards-compliant JSON values.

Replaces non-finite floats (NaN, ±inf) with None so the output can be serialized strictly by standard JSON encoders.

参数:

名称 类型 描述 默认
value Any

Arbitrary Python or NumPy value to sanitize.

必需

返回:

名称 类型 描述
Any Any

JSON-serializable structure made of primitives, lists, and dicts.

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

Base evaluation protocol for splitting datasets, fitting constants, and scoring formulas.

Provides the five standard classmethod entry points shared by all formula evaluation tools: :meth:split, :meth:fit, :meth:evaluate, :meth:fit_candidate, and :meth:evaluate_candidate. Custom evaluators inherit from :class:DefaultEvaluator and override only the methods that need task-specific behavior.

split classmethod

split(context: AgentContext) -> ContextSplits

Partition context into "train" and "validation" :class:~sr_harness.core.AgentContext views.

参数:

名称 类型 描述 默认
context AgentContext

Complete unsplit :class:~sr_harness.core.AgentContext.

必需

返回:

名称 类型 描述
ContextSplits ContextSplits

Dictionary {"train": train_context, "validation": validation_context}.

fit classmethod

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

Optimize free parameters in f on the training split to approximate y.

参数:

名称 类型 描述 默认
f Expression

Right-hand side symbolic expression containing optional parameters.

必需
y Expression

Left-hand side target expression.

必需
context AgentContext

Training split :class:~sr_harness.core.AgentContext.

必需

返回:

类型 描述
Expression

engine.Expression: Copy of f with all parameter nodes bound to fitted numeric values.

evaluate classmethod

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

Compute regression and complexity metrics for the equality y = f on context.

参数:

名称 类型 描述 默认
f Expression

Parameter-bound right-hand side expression.

必需
y Expression

Left-hand side target expression.

必需
context AgentContext

Training or validation :class:~sr_harness.core.AgentContext.

必需

返回:

名称 类型 描述
MetricDict MetricDict

Dictionary mapping metric names (mse, rmse, mae, mape, r2, aic, bic, pearson_r, spearman_r, complexity) to numeric values.

fit_candidate classmethod

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

Fit a formal candidate expression f predicting context.target on the training split.

By default, delegates to cls.fit(f, Symbol(context.target), context).

参数:

名称 类型 描述 默认
f Expression

Candidate symbolic expression predicting the target variable.

必需
context AgentContext

Training split :class:~sr_harness.core.AgentContext.

必需

返回:

类型 描述
Expression

engine.Expression: Copy of f with fitted parameter values bound.

evaluate_candidate classmethod

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

Evaluate a fitted formal candidate expression f against context.target.

By default, delegates to cls.evaluate(f, Symbol(context.target), context). Override this method to add candidate-only metrics such as ODE trajectory rollout error.

参数:

名称 类型 描述 默认
f Expression

Parameter-bound candidate expression.

必需
context AgentContext

Training or validation :class:~sr_harness.core.AgentContext.

必需

返回:

名称 类型 描述
MetricDict MetricDict

Dictionary of numeric evaluation metrics.

GraphEvaluator

Bases: DefaultEvaluator

Evaluator for graph and hypergraph datasets with node (..., N), edge (..., E), and hyperedge (..., H) arrays.

Passes context.num_nodes to the symbolic engine during fitting and evaluation, and slices only sample-aligned leading dimensions during :meth:split so shared edge and hyperedge coordinate tables remain intact.

fit classmethod

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

Fit parameters in f to approximate y using graph-aware broadcast evaluation.

参数:

名称 类型 描述 默认
f Expression

Symbolic expression whose parameters will be fitted.

必需
y Expression

Target symbolic expression.

必需
context AgentContext

Training context containing node/edge arrays and num_nodes.

必需

返回:

类型 描述
Expression

engine.Expression: Copy of f with fitted parameter values bound.

evaluate classmethod

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

Evaluate y = f on graph or hypergraph data using context.num_nodes.

参数:

名称 类型 描述 默认
f Expression

Parameter-bound expression to evaluate.

必需
y Expression

Target symbolic expression.

必需
context AgentContext

Training or validation context containing graph metadata.

必需

返回:

名称 类型 描述
MetricDict MetricDict

Dictionary of numeric regression and complexity metrics.

split classmethod

split(context: AgentContext) -> ContextSplits

Split sample-aligned leading axes into train and validation views while preserving shared relation tables.

参数:

名称 类型 描述 默认
context AgentContext

Unsplit graph or hypergraph :class:~sr_harness.core.AgentContext.

必需

返回:

名称 类型 描述
ContextSplits ContextSplits

Dictionary {"train": train_context, "validation": validation_context}.

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: Workspace | None = None,
)

Authoritative runtime context shared across agents, evaluators, and tools.

Holds the active dataset arrays (data), variable and axis metadata, selected target and feature names, the active :class:~sr_harness.evaluator.DefaultEvaluator, the conversation :class:~sr_harness.runtime.Workspace, and cached training/validation views.

参数:

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

Runtime configuration namespace shared by agents, evaluators, and tools.

None
data dict[str, Any] | None

Mapping of variable and axis names to NumPy arrays.

None
target str | None

Name of the active dependent variable, if selected.

None
variable_descriptions dict[str, str] | None

Human-readable descriptions keyed by variable or axis name.

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

Mapping from each variable name to its tuple of axis names.

None
variable_structures dict[str, str] | None

Mapping from edge-aligned variable names to their relation name.

None
relation_names set[str] | None

Set of variable names representing graph or hypergraph edge tables.

None
num_nodes int | None

Total node count when graph or hypergraph relations are present.

None
evaluator DefaultEvaluator | object

Evaluator instance used for splitting, parameter fitting, and scoring.

_DEFAULT_EVALUATOR
workspace Workspace | None

Optional managed workspace accessible to workspace-aware tools.

None

Initialize an agent runtime context.

参数:

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

Runtime configuration namespace.

None
data dict[str, Any] | None

Mapping of variable and axis names to NumPy arrays.

None
target str | None

Name of the active target variable.

None
variable_descriptions dict[str, str] | None

Descriptions keyed by variable or axis name.

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

Axis tuples keyed by variable name.

None
variable_structures dict[str, str] | None

Relation variable names keyed by edge-aligned variable name.

None
relation_names set[str] | None

Names of graph or hypergraph relation variables.

None
num_nodes int | None

Node count for relational datasets.

None
evaluator DefaultEvaluator | object

Active formula evaluator instance.

_DEFAULT_EVALUATOR
workspace Workspace | None

Optional managed workspace instance.

None

train_split property

train_split: AgentContext

Return the cached training split context, calling evaluator.split(self) on first access.

返回:

名称 类型 描述
AgentContext AgentContext

Context view containing the training split arrays.

validation_split property

validation_split: AgentContext

Return the cached validation split context, calling evaluator.split(self) on first access.

返回:

名称 类型 描述
AgentContext AgentContext

Context view containing the validation split arrays.

invalidate_splits

invalidate_splits() -> None

Clear cached training and validation context splits so they are recomputed on next access.

with_data

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

Create a lightweight view over data that shares runtime arguments and metadata with this context.

参数:

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

Replacement mapping of variable and axis arrays.

必需

返回:

名称 类型 描述
AgentContext AgentContext

New context view bound to data.

axis_names

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

Return all coordinate axis names referenced by variables in first-appearance order.

返回:

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

tuple[str, ...]: Ordered axis names.

variable_names

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

Return all non-axis variable names in manifest order.

返回:

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

tuple[str, ...]: Ordered variable names.

feature_names

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

Return selected input feature names (excluding axes and the active target).

返回:

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

tuple[str, ...]: Active feature variable names.

commit_context_data

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

Replace the live dataset with a validated load_context_data() bundle and increment data_revision.

参数:

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

Validated dataset dictionary returned by :func:load_context_data.

必需

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Summary containing the new revision, variables, axes, relation_names, and num_nodes.

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 aligned 1D/tabular arrays directly into the live context and increment data_revision.

参数:

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

Mapping of column names to NumPy-compatible arrays.

必需
target str

Name of the target variable to predict.

必需
features list[str] | None

Names of input feature variables to retain.

None
variable_descriptions dict[str, str] | None

Optional human-readable descriptions by column name.

None

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Summary containing the new revision, target, features, columns, and rows.

add_features

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

Append new sample-aligned feature arrays to the active dataset while keeping the current target.

参数:

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

Mapping of new feature names to aligned arrays.

必需
descriptions dict[str, str] | None

Optional descriptions for the newly added features.

None

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Updated commit summary after merging the new features.

引发:

类型 描述
ValueError

If no target variable is currently configured or feature shapes do not align.

update_selection

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

Update the active target, selected input features, and variable descriptions.

参数:

名称 类型 描述 默认
target str

Name of the target variable.

必需
features list[str]

List of input feature variable names.

必需
variable_descriptions dict[str, str] | None

Optional updated descriptions keyed by variable or axis name.

None

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Summary with the incremented revision, target, and features.

schema

schema() -> dict[str, Any]

Return a JSON-serializable summary of variables, shapes, dtypes, axes, and roles in the context.

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Schema dictionary suitable for WebUI previews and diagnostics.

_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)

Thread-safe controller managing execution state, pause/stop commands, and timeline events for one agent.

参数:

名称 类型 描述 默认
event_capacity int

Maximum number of recent timeline events retained in memory.

1000

Initialize the interaction manager with an empty event ring buffer.

参数:

名称 类型 描述 默认
event_capacity int

Maximum number of timeline events to keep in memory (defaults to 1000).

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[[], str | None],
) -> Iterator[None]

Register cancellation for the current blocking operation.

参数:

名称 类型 描述 默认
cancel Callable[[], str | 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, *, limit: int | None = None
) -> dict[str, Any]

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

参数:

名称 类型 描述 默认
after_sequence int

Last sequence already consumed by the caller.

0
limit int | None

Maximum events per batch; omitted for an unlimited internal snapshot.

None

返回:

类型 描述
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)

Queued user guidance message waiting to be injected at the next safe agent boundary.

属性:

名称 类型 描述
content str

Non-empty user message text.

created_at float

Unix timestamp when the message was queued.

SRInteractionManager

SRInteractionManager(*, event_capacity: int = 1000)

Bases: InteractionManager

Interaction manager with symbolic-regression branch commands.

Initialize the symbolic-regression interaction manager.

参数:

名称 类型 描述 默认
event_capacity int

Maximum number of timeline events retained in memory (defaults to 1000).

1000

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

Routing decision specifying which provider/model tier to call and why.

属性:

名称 类型 描述
tier str

Selected tier label ("base" or "strong").

provider str

Selected LLM provider name.

model str

Selected model identifier.

score int

Complexity score computed for the task and step.

reason str

Human-readable explanation of the routing decision.

ModelRouter

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

Policy that dynamically selects between a fast base model and an optional stronger model.

Evaluates task complexity (such as PDEs, ODEs, graph/network structure, noise, or high feature counts) and current refinement depth L to route key steps to the strong model when automatic routing is enabled.

Initialize the model router with base and optional strong model backends.

参数:

名称 类型 描述 默认
enabled bool

Whether automatic routing to the strong model is enabled.

必需
base_provider str

Provider name for the base model.

必需
base_model str

Model identifier for the base model.

必需
strong_provider str | None

Optional provider name for the strong model (defaults to base_provider).

None
strong_model str | None

Optional model identifier for the strong model.

None

has_strong_backend property

has_strong_backend: bool

Return whether a distinct strong provider/model backend is configured.

返回:

名称 类型 描述
bool bool

True if strong_model is set and differs from the base provider/model.

assess

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

Score the intrinsic difficulty of a discovery task from its description and feature count.

参数:

名称 类型 描述 默认
task str

Natural-language problem description.

必需
feature_count int

Number of input feature variables.

必需

返回:

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

tuple[int, list[str]]: Pair of (complexity_score, matched_reason_tags).

route

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

Select the base or strong model backend for a specific refinement step.

参数:

名称 类型 描述 默认
task_score int

Task complexity score returned by :meth:assess.

必需
task_reasons list[str]

Matched difficulty reasons returned by :meth:assess.

必需
refinement_step int

Current one-based refinement step index L.

必需

返回:

名称 类型 描述
ModelRoute ModelRoute

Selected model route and rationale.

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.

Initialize the sandbox runner and verify that the host kernel supports Landlock ABI 3+.

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, *, read_only: bool = False)

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.

read_only property

read_only: bool

Return whether every workspace mutation is disabled.

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 whether path is protected by a user lock rule or a read-only mount.

参数:

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

Absolute or workspace-relative path to check.

必需

返回:

名称 类型 描述
bool bool

True if writing or deleting path is blocked by a lock rule.

contains_locked_paths

contains_locked_paths(path: str | Path) -> bool

Return whether path or any descendant inside its directory tree is explicitly locked.

参数:

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

Workspace-relative or absolute path to inspect.

必需

返回:

名称 类型 描述
bool bool

True if path or any nested entry is locked.

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.

safe_open

safe_open(
    path: str | Path,
    mode: Literal["r", "rb"] = "r",
    *,
    encoding: str | None = None,
    errors: str | None = None,
) -> IO

Atomically open a file for reading inside the workspace or an authorized mount without escaping via symlinks.

参数:

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

Workspace-relative or mounted path to open.

必需
mode Literal['r', 'rb']

Read mode ("r" for text or "rb" for binary).

'r'
encoding str | None

Text encoding when mode == "r".

None
errors str | None

Encoding error handling strategy when mode == "r".

None

返回:

名称 类型 描述
IO IO

Open read-only file stream.

create_directory

create_directory(
    relative_path: str,
    *,
    parents: bool = False,
    exist_ok: bool = False,
) -> Path

Create a directory without following mutable workspace symlinks.

参数:

名称 类型 描述 默认
relative_path str

Workspace-relative directory path.

必需
parents bool

Create missing parent directories as needed.

False
exist_ok bool

Do not fail if the final directory already exists.

False

返回:

类型 描述
Path

The logical path of the created directory.

open_for_write

open_for_write(
    relative_path: str,
    mode: Literal["w", "wb", "x", "xb"] = "w",
    *,
    encoding: str | None = None,
    errors: str | None = None,
) -> IO

Open a workspace file for writing without following symbolic links.

参数:

名称 类型 描述 默认
relative_path str

Workspace-relative file path.

必需
mode Literal['w', 'wb', 'x', 'xb']

Truncating or exclusive text/binary write mode.

'w'
encoding str | None

Text encoding used by text modes.

None
errors str | None

Text encoding error strategy used by text modes.

None

返回:

类型 描述
IO

An open stream owned by the caller.

replace_file

replace_file(source: str | Path, destination: str) -> Path

Atomically replace a writable workspace file with a staged temporary file.

参数:

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

Path to the caller-owned staging file.

必需
destination str

Workspace-relative target file path.

必需

返回:

名称 类型 描述
Path Path

Logical workspace path of the replaced file.

install

install(source: str | Path, destination: str) -> Path

Atomically move a staged file or directory into the workspace without overwriting existing entries.

参数:

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

Path to the caller-owned staging file or directory.

必需
destination str

Workspace-relative destination path.

必需

返回:

名称 类型 描述
Path Path

Logical workspace path of the installed entry.

move

move(
    source: str,
    destination: str,
    *,
    overwrite: bool = False,
) -> Path

Move or rename a writable workspace entry while enforcing lock and mount boundaries.

参数:

名称 类型 描述 默认
source str

Workspace-relative source path.

必需
destination str

Workspace-relative destination path.

必需
overwrite bool

Whether to allow replacing an existing unlocked file at destination.

False

返回:

名称 类型 描述
Path Path

Logical workspace path of the moved entry.

remove

remove(
    relative_path: str,
    *,
    recursive: bool = False,
    missing_ok: bool = False,
) -> None

Delete a writable file or directory tree inside the workspace without following symlinks.

参数:

名称 类型 描述 默认
relative_path str

Workspace-relative path to remove.

必需
recursive bool

Whether to recursively delete non-empty directories.

False
missing_ok bool

If True, do not raise when relative_path does not exist.

False

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

__all__ module-attribute

__all__ = [
    "APICallSummary",
    "BaseAPI",
    "DeepSeekAPI",
    "GeminiAPI",
    "LMStudioAPI",
    "ManualAPI",
    "OpenAIAPI",
    "OpenRouterAPI",
    "SiliconFlowAPI",
]

BaseAPI

BaseAPI(
    model: str | None = None,
    tool_box: BaseParser | None = None,
    environment: Mapping[str, str] | None = None,
    save_path: str | Path | None = None,
)

Bases: ABC, FactoryMixin

Abstract base adapter for language-model providers.

Handles API key and proxy resolution from the session environment, native or parser-based tool formatting, OpenAI-compatible streaming and non-streaming chat completions, retry backoff, and cooperative cancellation.

Initialize the LLM provider adapter.

参数:

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

Model identifier to request (defaults to the subclass's default model).

None
tool_box BaseParser | None

Optional :class:~sr_harness.parser.BaseParser holding enabled tools.

None
environment Mapping[str, str] | None

Optional session-scoped environment mapping for API keys and proxies.

None
save_path str | Path | None

Optional directory path for logging raw provider responses.

None

model_list abstractmethod property

model_list: list[str]

Return the list of model identifiers supported by this provider adapter.

返回:

类型 描述
list[str]

list[str]: Supported model names.

get_env

get_env(
    name: str,
    default: str | None = None,
    *,
    required: bool = False,
) -> str | None

Read an environment variable from the session environment (falling back to os.environ).

参数:

名称 类型 描述 默认
name str

Environment variable name (e.g., "OPENROUTER_API_KEY").

必需
default str | None

Fallback value returned when the variable is unset or empty.

None
required bool

If True, raise a ValueError when no non-empty value is found.

False

返回:

类型 描述
str | None

str | None: Resolved environment variable value, or default.

proxy_url

proxy_url(url: str | None = None) -> str | None

Resolve the outbound HTTP/SOCKS proxy URL for url, honoring NO_PROXY exclusions.

参数:

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

Target request URL used to check NO_PROXY rules, or None.

None

返回:

类型 描述
str | None

str | None: Effective proxy URL, or None when direct connection should be used.

report_progress

report_progress(
    callback: ProgressCallback | None,
    update: dict[str, Any],
) -> None

Invoke the caller's progress callback with a live streaming or status update.

参数:

名称 类型 描述 默认
callback ProgressCallback | None

Optional progress callback supplied by the caller.

必需
update dict[str, Any]

Progress event dictionary to pass to callback.

必需

raise_if_cancelled

raise_if_cancelled() -> None

Raise :class:~sr_harness.core.ToolRunAbort immediately if cancellation has been requested.

wait_before_retry

wait_before_retry(delay: float) -> None

Sleep for delay seconds before retrying a failed request while remaining immediately cancellable.

参数:

名称 类型 描述 默认
delay float

Backoff duration in seconds.

必需

error_message

error_message(
    error: BaseException, *, description: str | None = None
) -> str

Log a provider exception and return a sanitized error message safe for the frontend.

参数:

名称 类型 描述 默认
error BaseException

Exception raised during the provider request.

必需
description str | None

Optional human-readable context describing the failed operation.

None

返回:

名称 类型 描述
str str

Sanitized error message with sensitive tokens redacted.

retry_delay staticmethod

retry_delay(error: Exception, attempt: int) -> float

Compute the retry backoff delay from a Retry-After header or exponential backoff.

参数:

名称 类型 描述 默认
error Exception

Exception raised by the HTTP/SDK client.

必需
attempt int

Zero-based retry attempt index.

必需

返回:

名称 类型 描述
float float

Delay in seconds before the next retry attempt.

openai_chat_completion

openai_chat_completion(
    client: Any,
    payload: dict[str, Any],
    *,
    sample: int,
    callback: ProgressCallback | None = None,
) -> tuple[Any, dict[str, Any], dict[str, Any], str]

Execute one OpenAI-compatible chat completion (streaming when a callback is provided) and normalize the output.

参数:

名称 类型 描述 默认
client Any

OpenAI-compatible SDK client instance.

必需
payload dict[str, Any]

Request keyword arguments passed to client.chat.completions.create.

必需
sample int

Zero-based sample index within the current batch.

必需
callback ProgressCallback | None

Optional callback receiving live streaming deltas.

None

返回:

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

tuple[Any, dict[str, Any], dict[str, Any], str]: Tuple of (completion_object, assistant_message_dict, usage_dict, finish_reason).

stream_openai_chat_completion

stream_openai_chat_completion(
    client: Any,
    payload: dict[str, Any],
    *,
    sample: int,
    callback: ProgressCallback,
) -> tuple[Any, dict[str, Any], dict[str, Any], str]

Consume an OpenAI-compatible SSE stream, publishing incremental reasoning/content deltas and assembling the final message.

参数:

名称 类型 描述 默认
client Any

OpenAI-compatible SDK client instance.

必需
payload dict[str, Any]

Request keyword arguments passed to client.chat.completions.create.

必需
sample int

Zero-based sample index within the current batch.

必需
callback ProgressCallback

Callback invoked for each incremental stream delta.

必需

返回:

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

tuple[Any, dict[str, Any], dict[str, Any], str]: Tuple of (synthetic_completion, assistant_message_dict, usage_dict, finish_reason).

parse_tool_calls

parse_tool_calls(
    message: dict[str, Any], content: str
) -> list[ToolCall]

Extract normalized :class:~sr_harness.core.ToolCall objects from an assistant message.

参数:

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

Raw provider assistant message dictionary.

必需
content str

Assistant text content.

必需

返回:

类型 描述
list[ToolCall]

list[ToolCall]: Parsed tool calls (empty list when no tools were called).

openai_token_usage staticmethod

openai_token_usage(
    completion: Any, *, other_key: str = "others"
) -> dict[str, int]

Extract prompt, completion, reasoning, and cached token counts from an OpenAI-style completion object.

参数:

名称 类型 描述 默认
completion Any

OpenAI-compatible completion response object.

必需
other_key str

Key name used to store cached/extra tokens (defaults to "others").

'others'

返回:

类型 描述
dict[str, int]

dict[str, int]: Token usage breakdown dictionary.

aggregate_sample_results staticmethod

aggregate_sample_results(
    results: list[ProviderSampleResult],
) -> dict[str, Any]

Combine per-sample token counts, costs, and error messages into a batch summary dictionary.

参数:

名称 类型 描述 默认
results list[ProviderSampleResult]

List of :class:ProviderSampleResult objects from one batch call.

必需

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Aggregated ok, error, token_usage, money_usage, and extra metadata.

format_response abstractmethod

format_response(
    message: Any,
    tool_calls: list[ToolCall],
    content: str | None = None,
) -> APICallSample

Convert a provider message and parsed tool calls into a normalized :class:~sr_harness.core.APICallSample.

参数:

名称 类型 描述 默认
message Any

Raw provider message object or dictionary.

必需
tool_calls list[ToolCall]

Normalized tool calls extracted from the message.

必需
content str | None

Optional explicit text content override.

None

返回:

名称 类型 描述
APICallSample APICallSample

Normalized response sample.

cancel

cancel() -> str | None

Signal active provider requests to abort at the next cancellation boundary and close active streams.

返回:

类型 描述
str | None

str | None: Optional diagnostic note if the underlying SDK cannot be preempted mid-request.

APICallSummary dataclass

APICallSummary(gen: Iterator[APICallSample])

Iterable wrapper over a provider response generator that captures aggregate usage and status.

Iterating over an :class:APICallSummary yields individual :class:APICallSample instances as they complete, then populates ok, error, token_usage, money_usage, and extra from the generator's final return value.

truncated property

truncated: bool

Return whether any yielded sample in this call was truncated by the token limit.

返回:

名称 类型 描述
bool bool

True if at least one sample has truncated == True.

ManualAPI

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

Bases: BaseAPI

Interactive terminal adapter that prints prompts to stdout and reads human-typed responses from stdin.

Initialize the manual terminal provider adapter.

参数:

名称 类型 描述 默认
model str

Placeholder model name (defaults to "manual").

'manual'
save_path str | Path | None

Optional directory path for saving transcripts.

None
**kwargs Any

Additional arguments forwarded to :class:BaseAPI.

{}

model_list property

model_list: list[str]

Return the synthetic ["manual"] model list for the terminal provider.

返回:

类型 描述
list[str]

list[str]: ["manual"].

cancel

cancel() -> str

Report that interactive stdin reads in the terminal cannot be preempted remotely from the WebUI.

返回:

名称 类型 描述
str str

Notice explaining that terminal input must complete first.

format_response

format_response(
    message: dict[str, Any],
    tool_calls: list[ToolCall],
    content: str | None = None,
) -> APICallSample

Wrap manually entered terminal text and parsed tool calls into an :class:~sr_harness.core.APICallSample.

参数:

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

Dictionary containing the manually entered response content.

必需
tool_calls list[ToolCall]

Tool calls parsed from the manual text.

必需
content str | None

Optional explicit text content override.

None

返回:

名称 类型 描述
APICallSample APICallSample

Normalized response sample.

OpenAIAPI

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

Bases: BaseAPI

LLM provider adapter for OpenAI and Azure OpenAI models (supporting both Responses and Chat Completions APIs).

Initialize the OpenAI / Azure OpenAI adapter.

参数:

名称 类型 描述 默认
model str

OpenAI deployment or model name (defaults to "gpt-5-mini").

'gpt-5-mini'
**kwargs Any

Additional arguments forwarded to :class:BaseAPI.

{}

model_list property

model_list: list[str]

Return the OpenAI / Azure OpenAI model identifiers supported by this adapter.

返回:

类型 描述
list[str]

list[str]: Supported model names.

cancel

cancel() -> str

Request cancellation and note that in-flight synchronous OpenAI SDK calls cannot be preempted mid-request.

返回:

名称 类型 描述
str str

Human-readable notice describing cancellation behavior.

format_response

format_response(
    message: Any,
    tool_calls: list[ToolCall],
    content: str | None = None,
) -> APICallSample

Convert an OpenAI Responses or Chat Completions message into an :class:~sr_harness.core.APICallSample.

参数:

名称 类型 描述 默认
message Any

Provider response item or message dictionary.

必需
tool_calls list[ToolCall]

Normalized tool calls extracted from the response.

必需
content str | None

Optional explicit text content override.

None

返回:

名称 类型 描述
APICallSample APICallSample

Normalized assistant response sample.

build_native_tool_description

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

Format enabled tools into the schema structure expected by OpenAI's Responses or Chat Completions API.

参数:

名称 类型 描述 默认
use_chat_completions bool

If True, return Chat Completions {"type": "function", "function": ...} entries; if False, return flattened Responses API tool definitions.

False

返回:

类型 描述
List[Dict]

List[Dict]: List of OpenAI tool schema dictionaries.

create_responses

create_responses(
    messages: List[Dict[str, str]],
    n: int = 1,
    max_tokens: int | None = None,
    temperature: float = 1.0,
    top_p: float = 1.0,
    callback: ProgressCallback | None = None,
) -> Generator[APICallSample, None, dict[str, Any]]

Sample completions using the OpenAI responses.create API (used for reasoning models such as gpt-5-mini).

参数:

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

Conversation messages in OpenAI format.

必需
n int

Number of independent samples to request.

1
max_tokens int | None

Optional maximum output token limit.

None
temperature float

Sampling temperature.

1.0
top_p float

Nucleus sampling probability threshold.

1.0
callback ProgressCallback | None

Optional progress callback.

None

产生:

名称 类型 描述
APICallSample APICallSample

Normalized response samples as they complete.

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Aggregated token usage, cost, and status summary.

create_chat_completions

create_chat_completions(
    messages: List[Dict[str, str]],
    n: int = 1,
    max_tokens: int | None = None,
    temperature: float = 1.0,
    top_p: float = 1.0,
    callback: ProgressCallback | None = None,
) -> Generator[APICallSample, None, dict[str, Any]]

Sample completions using the standard OpenAI chat.completions.create API.

参数:

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

Conversation messages in OpenAI format.

必需
n int

Number of independent samples to request.

1
max_tokens int | None

Optional maximum output token limit.

None
temperature float

Sampling temperature.

1.0
top_p float

Nucleus sampling probability threshold.

1.0
callback ProgressCallback | None

Optional progress callback.

None

产生:

名称 类型 描述
APICallSample APICallSample

Normalized response samples as they complete.

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Aggregated token usage, cost, and status summary.

parse_usage

parse_usage(response: Response) -> Dict

Extract token counts and estimated USD cost from an OpenAI Responses API result.

参数:

名称 类型 描述 默认
response Response

OpenAI Response object.

必需

返回:

名称 类型 描述
Dict Dict

Dictionary containing token_usage and money_usage breakdowns.

parse_chat_completions_usage

parse_chat_completions_usage(
    response: ChatCompletion,
) -> Dict

Extract token counts and estimated USD cost from an OpenAI ChatCompletion result.

参数:

名称 类型 描述 默认
response ChatCompletion

OpenAI ChatCompletion object.

必需

返回:

名称 类型 描述
Dict Dict

Dictionary containing token_usage and money_usage breakdowns.

GeminiAPI

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

Bases: BaseAPI

LLM provider adapter for Google Gemini models via the google-genai SDK.

Initialize the Google Gemini API adapter.

参数:

名称 类型 描述 默认
model str

Gemini model identifier (defaults to "gemini-2.5-pro").

'gemini-2.5-pro'
**kwargs Any

Additional arguments forwarded to :class:BaseAPI.

{}

model_list property

model_list: list[str]

Return the list of Google Gemini model identifiers supported by this adapter.

返回:

类型 描述
list[str]

list[str]: Supported Gemini model names.

cancel

cancel() -> str

Request cancellation and note that synchronous Gemini SDK calls pause after the in-flight HTTP request returns.

返回:

名称 类型 描述
str str

Human-readable notice explaining when the cancellation will take effect.

format_response

format_response(
    message: dict[str, Any],
    tool_calls: list[ToolCall],
    content: str | None = None,
) -> APICallSample

Convert a Gemini response dictionary into a normalized :class:~sr_harness.core.APICallSample.

参数:

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

Normalized Gemini message dictionary.

必需
tool_calls list[ToolCall]

Parsed tool calls from the response.

必需
content str | None

Optional explicit text content override.

None

返回:

名称 类型 描述
APICallSample APICallSample

Normalized assistant response sample.

DeepSeekAPI

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

Bases: BaseAPI

LLM provider adapter for the official DeepSeek API (OpenAI-compatible endpoint).

Initialize the DeepSeek API adapter.

参数:

名称 类型 描述 默认
model str

DeepSeek model identifier (defaults to "deepseek-chat").

'deepseek-chat'
**kwargs Any

Additional arguments forwarded to :class:BaseAPI.

{}

model_list property

model_list: list[str]

Fetch and return the list of available models from the DeepSeek catalog.

返回:

类型 描述
list[str]

list[str]: Model identifiers offered by DeepSeek.

format_response

format_response(
    message: dict[str, Any],
    tool_calls: list[ToolCall],
    content: str | None = None,
) -> APICallSample

Convert a DeepSeek assistant message into a normalized :class:~sr_harness.core.APICallSample.

参数:

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

Raw DeepSeek response message dictionary.

必需
tool_calls list[ToolCall]

Normalized tool calls extracted from the message.

必需
content str | None

Optional explicit text content override.

None

返回:

名称 类型 描述
APICallSample APICallSample

Normalized assistant response sample.

OpenRouterAPI

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

Bases: BaseAPI

LLM provider adapter for OpenRouter, supporting live model discovery and streaming tool calls.

Initialize the OpenRouter API adapter.

参数:

名称 类型 描述 默认
model str

OpenRouter model slug (defaults to "qwen/qwen3.6-plus").

'qwen/qwen3.6-plus'
**kwargs Any

Additional arguments forwarded to :class:BaseAPI.

{}

model_list property

model_list: list[str]

Fetch and return all text-capable model identifiers from the live OpenRouter catalog.

返回:

类型 描述
list[str]

list[str]: Available OpenRouter model slugs.

format_response

format_response(
    message: dict[str, Any],
    tool_calls: list[ToolCall],
    content: str | None = None,
) -> APICallSample

Convert an OpenRouter completion message into a normalized :class:~sr_harness.core.APICallSample.

参数:

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

Raw OpenRouter assistant message dictionary.

必需
tool_calls list[ToolCall]

Normalized tool calls extracted from the message.

必需
content str | None

Optional explicit text content override.

None

返回:

名称 类型 描述
APICallSample APICallSample

Normalized assistant response sample.

LMStudioAPI

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

Bases: BaseAPI

LLM provider adapter for a local or remote LM Studio server.

Automatically normalizes LM Studio's /api/v1/chat endpoint to the OpenAI-compatible /v1/chat/completions route required for multi-turn conversations and function calling.

Initialize the LM Studio API adapter.

参数:

名称 类型 描述 默认
model str

Local model identifier loaded in LM Studio.

'qwen_qwen3-4b-instruct-2507'
**kwargs Any

Additional arguments forwarded to :class:BaseAPI.

{}

model_list property

model_list: list[str]

Return the configured model identifier for this LM Studio instance.

返回:

类型 描述
list[str]

list[str]: Single-element list containing the active model name.

cancel

cancel() -> str

Request cancellation and note that synchronous LM Studio HTTP calls finish the active request before stopping.

返回:

名称 类型 描述
str str

Human-readable notice describing cancellation behavior.

format_response

format_response(
    message: dict[str, Any],
    tool_calls: list[ToolCall],
    content: str | None = None,
) -> APICallSample

Convert an LM Studio completion message into a normalized :class:~sr_harness.core.APICallSample.

参数:

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

Raw message dictionary returned by LM Studio.

必需
tool_calls list[ToolCall]

Normalized tool calls extracted from the message.

必需
content str | None

Optional explicit text content override.

None

返回:

名称 类型 描述
APICallSample APICallSample

Normalized assistant response sample.

normalize_endpoint staticmethod

normalize_endpoint(endpoint: str) -> str

Convert an LM Studio base URL or native chat path into the /v1/chat/completions endpoint URL.

参数:

名称 类型 描述 默认
endpoint str

Raw endpoint URL from LMSTUDIO_ENDPOINT or settings.

必需

返回:

名称 类型 描述
str str

Normalized OpenAI-compatible chat completions URL.

SiliconFlowAPI

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

Bases: BaseAPI

LLM provider adapter for SiliconFlow chat and reasoning models.

Initialize the SiliconFlow API adapter.

参数:

名称 类型 描述 默认
model str

SiliconFlow model identifier (defaults to "Qwen3-8B").

'Qwen3-8B'
**kwargs Any

Additional arguments forwarded to :class:BaseAPI.

{}

model_list property

model_list: list[str]

Fetch and return the available chat models from SiliconFlow's model catalog.

返回:

类型 描述
list[str]

list[str]: Supported SiliconFlow model identifiers.

cancel

cancel() -> str

Request cancellation and note that synchronous SiliconFlow HTTP requests pause once the active call returns.

返回:

名称 类型 描述
str str

Human-readable notice describing cancellation behavior.

format_response

format_response(
    message: dict[str, Any],
    tool_calls: list[ToolCall],
    content: str | None = None,
) -> APICallSample

Convert a SiliconFlow response message into a normalized :class:~sr_harness.core.APICallSample.

参数:

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

Raw SiliconFlow assistant message dictionary.

必需
tool_calls list[ToolCall]

Normalized tool calls extracted from the message.

必需
content str | None

Optional explicit text content override.

None

返回:

名称 类型 描述
APICallSample APICallSample

Normalized assistant response sample.

Tools

sr_harness.tools

Built-in symbolic-regression, data-analysis, and workspace tools for SRHarness.

__all__ module-attribute

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

ToolCallResult dataclass

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

Standardized outcome returned by BaseTool.__call__().

result preserves the full machine-readable dictionary for run logging and candidate extraction, whereas result_str is a concise, length-bounded text summary formatted for the language model's next turn.

get

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

Look up a key inside the structured result dictionary when result is a mapping.

参数:

名称 类型 描述 默认
key str

Dictionary key to look up in self.result.

必需
default Any

Value returned when key is absent.

None

返回:

名称 类型 描述
Any Any

Value associated with key, or default.

ToolMetadata dataclass

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

Declarative metadata describing a tool's name, purpose, and JSON parameter schema.

When description or parameters are omitted, :class:~sr_harness.tools.BaseTool infers them automatically from execute()'s type annotations and Google-style docstring.

BaseTool

BaseTool(context: AgentContext | None = None)

Bases: ABC, FactoryMixin

Abstract base class for all SRHarness tools.

Subclasses register a tool name via @BaseTool.register(...), implement :meth:execute with simple JSON-serializable parameters, and optionally override :meth:format_result_dict to render concise text for the Agent. When metadata.description or metadata.parameters are omitted, BaseTool infers them automatically from :meth:execute's signature, type annotations, and Google-style docstring.

Initialize the tool with an execution context.

参数:

名称 类型 描述 默认
context AgentContext | None

Runtime :class:AgentContext providing data splits, target, evaluator, and workspace. Defaults to an empty context when None.

None

引发:

类型 描述
TypeError

If context is neither an :class:AgentContext nor None.

get_doc classmethod

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

Return optional skill documentation exposed by this tool at runtime.

返回:

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

dict[str, str] | None: Skill mapping with name, description, and

dict[str, str] | None

content, or None if the tool does not expose a runtime skill.

execute abstractmethod

execute() -> Dict[str, Any]

Execute the tool logic on model-supplied arguments.

Keep parameters simple and JSON-compatible; access dataset arrays, target metadata, and workspace state via self.context. The summary before Args: becomes the default metadata.description, and parameter descriptions under Args: populate the JSON Schema sent to the Agent.

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Structured execution output.

format_result_dict classmethod

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

Format the structured output of :meth:execute into concise text for the Agent.

参数:

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

Result dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Formatted text observation appended to the Agent conversation.

cancel

cancel() -> None

Request cooperative cancellation of an in-flight tool invocation.

normalize_formula classmethod

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

Validate and normalize an Agent-supplied formula string prior to parsing.

Replaces ^ with ** and optionally strips np., numpy., and math. prefixes.

参数:

名称 类型 描述 默认
eq str

Raw formula string provided by the Agent.

必需
strip_modules bool

Whether to strip common Python math module prefixes.

True

返回:

名称 类型 描述
str str

Normalized formula string ready for :mod:sr_harness_engine.

parse_formula classmethod

parse_formula(eq: str) -> Expression

Normalize and parse a formula string with built-in pi and e constants.

参数:

名称 类型 描述 默认
eq str

Formula string to parse.

必需

返回:

类型 描述
Expression

engine.Expression: Parsed symbolic expression tree.

truncate_result_str classmethod

truncate_result_str(text: str) -> str

Truncate formatted tool output to MAX_RESULT_STR_LENGTH characters.

参数:

名称 类型 描述 默认
text str

Formatted tool output string.

必需

返回:

名称 类型 描述
str str

Original string or truncated prefix with an omitted-character count.

to_tool_list classmethod

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

Build OpenAI-compatible function-tool definitions for selected registered tools.

参数:

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

Optional list of tool names to include. Includes all registered tools when None.

None

返回:

类型 描述
list[dict]

list[dict]: OpenAI-format tool definitions.

load_tool_list classmethod

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

Load flat tool metadata dictionaries for prompt-based tool parsers.

参数:

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

Optional list of tool names to include. Includes all registered tools when None.

None

返回:

类型 描述
list[dict]

list[dict]: Dictionaries containing name, description, and parameters.

load_tool_classes classmethod

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

Return registered :class:BaseTool subclasses matching tools_used.

参数:

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

Optional list of tool names to include. Includes all registered tools when None.

None

返回:

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

list[type[BaseTool]]: Selected tool classes.

load_custom_tool classmethod

load_custom_tool(source: str, *, path: str | Path) -> dict

Validate and register a sandboxed custom tool from Python source code.

参数:

名称 类型 描述 默认
source str

Python source code defining a single :class:BaseTool subclass.

必需
path str | Path

Path to the tool.py file for diagnostics and reload tracking.

必需

返回:

名称 类型 描述
dict dict

Registration details including tool_name, path, class_name, and tool_class.

discover_custom_tools classmethod

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

Load and register all custom tools found in skill_manager.

参数:

名称 类型 描述 默认
skill_manager SkillManager

Skill manager used to scan tool.py files across skills.

必需

返回:

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

list[type[BaseTool]]: Registered sandbox-proxy tool classes.

to_dict classmethod

to_dict() -> dict

Export this tool class as an OpenAI function-calling schema dictionary.

返回:

名称 类型 描述
dict dict

OpenAI {"type": "function", "function": ...} schema.

infer_tool_description classmethod

infer_tool_description() -> str

Extract the tool description from the text preceding Args: in :meth:execute.

返回:

名称 类型 描述
str str

Inferred tool description, or "(no description provided)" if empty.

infer_tool_parameters classmethod

infer_tool_parameters() -> Dict[str, Any]

Infer a JSON Schema parameter object from :meth:execute's signature and docstring.

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: JSON Schema object definition with properties and required.

parse_args_docstring staticmethod

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

Parse parameter descriptions from a callable's Google-style docstring.

参数:

名称 类型 描述 默认
func callable

Callable whose docstring should be parsed.

必需

返回:

类型 描述
dict[str, str]

dict[str, str]: Mapping from parameter name to its description text.

parse_args_typehints classmethod

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

Convert a Python type annotation into a JSON Schema fragment.

参数:

名称 类型 描述 默认
annotation Any

Type annotation from :meth:execute.

必需

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Corresponding JSON Schema type definition.

parse_json_type staticmethod

parse_json_type(value_type: Any) -> str

Map a primitive Python type to its JSON Schema type name.

参数:

名称 类型 描述 默认
value_type Any

Python type object (e.g., int, float, str, bool).

必需

返回:

名称 类型 描述
str str

JSON Schema type name, or an empty string if unsupported.

calculate_metrics classmethod

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

Compute standard regression and complexity metrics from target and prediction arrays.

参数:

名称 类型 描述 默认
f Expression

Symbolic expression used to compute structural complexity.

必需
y_true ndarray

Ground-truth target array.

必需
y_pred ndarray

Predicted target array.

必需

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Regression metrics including MSE, RMSE, MAE, R2, AIC, BIC, correlations, and complexity.

evaluate

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

Evaluate a symbolic formula f against target expression y across data splits.

参数:

名称 类型 描述 默认
f Expression

Candidate symbolic expression for the right-hand side.

必需
y Expression

Target symbolic expression for the left-hand side.

必需
show_diagnostics bool

Whether to include worst-sample and residual-correlation diagnostics.

True
fit bool

Whether to optimize scalar parameters on the training split before scoring.

False

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Evaluation dictionary with formula, target_expression,

Dict[str, Any]

is_candidate, candidate_ineligibility_reasons, and data_split_results.

failed_evaluation

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

Build a fallback evaluation result with infinite error metrics when fitting fails.

参数:

名称 类型 描述 默认
formula str

Placeholder formula string to report.

'(None)'

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Non-candidate evaluation dictionary with inf/-inf metrics.

format_evaluation_result classmethod

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

Render a standardized evaluation dictionary into a compact report for the Agent.

参数:

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

Evaluation dictionary returned by :meth:evaluate.

必需
title str

Section title displayed at the top of the report.

'Formula evaluation'

返回:

名称 类型 描述
str str

Formatted fit metrics, eligibility notes, worst samples, and residual correlations.

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]

Compute error quantiles, worst-predicted samples, and residual-feature correlations.

参数:

名称 类型 描述 默认
y_true ndarray

Ground-truth target values.

必需
y_pred ndarray

Model-predicted values.

必需
data Dict[str, Any]

Optional dictionary of variables to correlate against residuals.

None
target_expression str

Optional target expression name to include in correlation checks.

None
max_samples int

Maximum number of high-error samples to return.

3
max_correlations int

Maximum number of residual correlations to return.

5

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Dictionary with error_profile, worst_samples, and strongest_residual_correlations.

correlation_coefficients staticmethod

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

Compute finite-sample Pearson linear and Spearman rank correlations.

参数:

名称 类型 描述 默认
x ndarray

First 1D numeric array.

必需
y ndarray

Second 1D numeric array.

必需

返回:

类型 描述
tuple[float, float]

tuple[float, float]: (pearson_r, spearman_r), or (nan, nan) when undefined.

ToolRunAbort

Bases: RuntimeError

Exception raised by a tool to abort execution and bypass BaseTool.__call__ recovery.

StatisticsTool

StatisticsTool(context: AgentContext | None = None)

Bases: BaseTool

Tool for computing summary statistics, sign/domain counts, near-zero fractions, and histograms.

execute

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

Compute summary statistics, domain/sign fractions, near-zero counts, and histograms for variables or expressions.

参数:

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

List of variable names or expressions to analyze, e.g., ["x1", "x2", "y"] or ["sin(x1)", "(x1-x2)**2"]. Analyzes all numeric variables (including the target) by default.

None
n_bins int

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

10
near_zero_threshold float

Primary absolute-value cutoff |x| <= threshold for counting near-zero samples (also reports 1e-6 and 1e-4).

1e-08

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Per-variable statistics dictionary, configuration, and any evaluation warnings.

format_result_dict classmethod

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

Format per-variable domain counts, quantiles, near-zero fractions, and histograms for the Agent.

参数:

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

Result dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Formatted statistical summary.

get_stats

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

Compute finite-sample summary statistics, sign ratios, near-zero counts, and histogram bins for a 1D array.

参数:

名称 类型 描述 默认
arr ndarray

Input numeric array to summarize.

必需
n_bins int

Number of equal-width histogram bins (1-100, default 10).

10
near_zero_threshold float

Primary absolute-value threshold for near-zero sample counting (default 1e-8).

1e-08

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Summary statistics and distribution bins for arr.

RelationshipAnalysisTool

RelationshipAnalysisTool(
    context: AgentContext | None = None,
)

Bases: BaseTool

Tool for analyzing feature-target correlations, conditional bin profiles, and 1D cross-validated collapse.

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 how each variable or expression relates to target y via correlations, binning, and 1D held-out fits.

For each candidate feature x_i, computes: - Pearson linear and Spearman rank correlations with y. - Conditional mean, std, and range of y across quantile or equal-width bins of x_i. - Cross-validated 1D predictive R2 (testing whether y ≈ g(x_i) collapses onto a single feature/composite) and the strongest remaining variable correlated with the 1D residual.

参数:

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

Feature names or expressions to analyze, e.g., ["x1", "x2", "x1 * x2"]. Defaults to all numeric non-target variables.

None
y str

Target variable name or expression. Defaults to context.target.

None
n_bins int

Number of bins for conditional target summaries and bin-mean collapse (2-100, default 5).

5
pairwise bool

Whether to also compute full pairwise Pearson and Spearman matrices across all analyzed variables.

False
binning str

Binning scheme, either "quantile" (default) or "equal_width".

'quantile'
n_folds int

Number of cross-validation folds for the 1D held-out collapse test (2-20, default 5).

5
collapse_model str

1D predictor used in cross-validation: "bins" (default), "spline", or "isotonic".

'bins'

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Per-variable correlations, conditional bin summaries, 1D held-out R2, residual associations, and optional pairwise matrices.

format_result_dict classmethod

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

Format feature-target correlations, conditional bin tables, and 1D collapse scores for the Agent.

参数:

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

Result dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Formatted relationship analysis report.

EvaluateTool

EvaluateTool(context: AgentContext | None = None)

Bases: BaseTool

Tool for scoring a symbolic formula against a target variable or expression.

execute

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

Evaluate how well a symbolic formula f fits target y on train and validation splits.

Automatically treats unknown variable names in f as tunable parameters and optimizes them with BFGS. Records a submission-eligible candidate when y is the default target variable and f does not reference y.

参数:

名称 类型 描述 默认
f str

Symbolic formula string, e.g., "x1**2 + sin(x2) + 3.5 * tanh(x3)". Standard math operators (sin, sinh, sec, sech, sigmoid, etc.) are supported directly without np. prefixes.

必需
y str

Target variable name or expression, e.g., "y", "log(y)", or "y - x1". Defaults to context.target.

None
fit bool

Whether to optimize scalar parameters in f on the training split via BFGS.

False
show_diagnostics bool

Whether to return residual quantiles, worst samples, and residual-feature correlations.

True

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Fit metrics across splits, candidate eligibility, fitted parameters, and residual diagnostics.

format_result_dict classmethod

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

Format formula evaluation metrics and parameter-fitting notes for the Agent.

参数:

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

Result dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Formatted evaluation summary.

SubmitFormulaTool

SubmitFormulaTool(context: AgentContext | None = None)

Bases: EvaluateTool

Tool for evaluating and submitting a candidate formula to the search harness.

EvaluateCodeTool

EvaluateCodeTool(context: AgentContext | None = None)

Bases: BaseTool

Tool for evaluating Python-defined candidate models inside an isolated OS sandbox.

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 train and validation splits.

Before using this tool, call read_skill to check sr-harness-engine-syntax (and sr-harness-engine-graph-syntax for graph/hypergraph problems). Prefer symbolic formulas in evaluate_formula whenever SRHarness Engine syntax can express the model; use evaluate_code only when custom Python logic is genuinely required. Returns a submission-eligible candidate when y is the default target variable and predict_code does not depend on y.

参数:

名称 类型 描述 默认
model_code str

Python source defining def func(data) -> dict (plus optional imports) that fits parameters on data and returns a model dict containing a concise mathematical description string.

必需
predict_code str

Python source defining def func(data, model) (plus optional imports) that computes predicted target values without reading the target variable from data.

必需
y str

Target variable name or expression, e.g., "y" or "log(y)". Defaults to context.target.

None
timeout_seconds int

Sandbox execution timeout in seconds (1-120, default 30).

DEFAULT_TIMEOUT_SECONDS
memory_limit_mb int

Sandbox memory limit in MB (64-4096, default 1024).

DEFAULT_MEMORY_LIMIT_MB
output_limit_bytes int

Maximum captured output in bytes (1024-1048576, default 65536).

DEFAULT_OUTPUT_LIMIT_BYTES
show_diagnostics bool

Whether to include residual diagnostics in the evaluation result.

True

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Model description, candidate eligibility, and per-split fit metrics.

format_result_dict classmethod

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

Format the code-model evaluation report with character-based code complexity notes.

参数:

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

Result dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Formatted evaluation summary for the code-defined model.

LLMTool

LLMTool(context: AgentContext | None = None)

Bases: BaseTool

Tool for querying a configured LLM provider and returning its response text and usage.

execute

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

Send a prompt or chat message list to an LLM provider and return the completion.

参数:

名称 类型 描述 默认
llm_provider str

Provider identifier, e.g., "openai", "deepseek", or "gemini".

必需
llm_model str

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

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

Prompt string or list of {"role": "user"|"assistant", "content": "..."} dicts.

必需

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Dictionary containing content, token_usage, and money_usage.

PolynomialFitTool

PolynomialFitTool(context: AgentContext | None = None)

Bases: BaseTool

Tool for fitting multivariate polynomials with interaction filtering and negligible-term pruning.

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]

Fit a multivariate polynomial up to max_degree using QR least squares and optional term pruning.

Supports custom input expressions, interaction whitelists/blacklists, and conservative pruning of monomials whose RMS and peak contributions are negligible on the training set. Returns a submission-eligible candidate when y is the default target variable and x does not depend on y.

参数:

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

Input variable names or expressions, e.g., ["x1", "sin(x2)"]. Defaults to all numeric non-target variables.

None
y str

Target variable name or expression, e.g., "y" or "log(y)". Defaults to context.target.

None
max_degree int

Maximum total degree of polynomial terms (default 2).

2
include_interactions bool

Whether cross-product terms between distinct features are allowed.

True
interaction_blacklist List[Tuple[str, str]]

Pairs of feature names [(u, v), ...] excluded from interacting.

None
interaction_whitelist List[Tuple[str, str]]

If provided, only these feature pairs [(u, v), ...] are allowed to interact.

None
include_bias bool

Whether to include a constant intercept term.

True
simplify bool

Whether to prune negligible monomials and refit the remaining coefficients (default True).

True
show_diagnostics bool

Whether to include residual diagnostics in the evaluation output.

True

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Fitted polynomial evaluation, pruning summary, and any collinearity warnings.

format_result_dict classmethod

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

Format the fitted polynomial evaluation and any numerical warnings for the Agent.

参数:

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

Result dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Formatted polynomial fit report.

generate_terms

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

Generate symbolic monomial expressions up to max_degree respecting interaction rules.

参数:

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

Parsed symbolic feature expressions.

必需
max_degree int

Maximum total degree per monomial.

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

Set of sorted feature-name pairs permitted to co-occur in a monomial.

必需
include_bias bool

Whether to include the degree-0 constant term 1.

必需

返回:

类型 描述
List[Expression]

List[engine.Expression]: Ordered list of symbolic monomials.

HarmonicInteractionFitTool

HarmonicInteractionFitTool(
    context: AgentContext | None = None,
)

Bases: BaseTool

Tool for fitting a polynomial trend plus a state-modulated sinusoidal interaction.

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) + c * carrier * sin(frequency * oscillator) by frequency grid search and local refinement.

参数:

名称 类型 描述 默认
carrier str

State variable or expression that forms the polynomial trend and modulates the sine term.

必需
oscillator str

Phase/time variable or expression inside sin(frequency * oscillator).

必需
y str

Target variable or expression. Defaults to context.target.

None
degree int

Polynomial degree in carrier (1-4, default 2).

2
include_bias bool

Whether to include a constant intercept term.

False
max_cycles float

Maximum number of oscillation cycles across the observed oscillator span (default 20.0).

20.0
grid_size int

Number of frequency grid points to scan before local refinement (64-2048, default 320).

320
show_diagnostics bool

Whether to include residual diagnostics in the returned evaluation.

True

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Evaluation result and fitted harmonic configuration.

format_result_dict classmethod

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

Format the fitted harmonic-interaction formula and frequency for the Agent.

参数:

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

Result dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Formatted evaluation and frequency summary.

PowerLawFitTool

PowerLawFitTool(context: AgentContext | None = None)

Bases: BaseTool

Tool for fitting multiplicative power laws y = c * prod(x_i ** p_i) in log space.

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 * prod(x_i ** p_i) via log-space least squares.

Requires all supplied x and y values to be finite and strictly positive on every training sample. Also computes jackknife 95% confidence intervals for each exponent and can snap exponents to nearby simple fractions p/q when accuracy loss is within tolerance.

参数:

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

Strictly positive input variable names or expressions. Defaults to all numeric non-target variables.

None
y str

Strictly positive target variable name or expression. Defaults to context.target.

None
include_scale bool

Whether to fit the leading multiplicative constant c.

True
snap_exponents bool

Whether to snap fitted exponents to nearby simple rationals and refit c.

False
max_denominator int

Maximum rational denominator considered when snapping exponents (1-32, default 8).

8
snap_tolerance float

Maximum absolute change allowed per snapped exponent (default 0.05).

0.05
max_snap_rmse_degradation float

Maximum normalized RMSE increase allowed after snapping (default 0.01).

0.01
n_stability_folds int

Number of jackknife folds for exponent confidence intervals (2-20, default 5).

5
show_diagnostics bool

Whether to include residual diagnostics in the evaluation output.

True

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Fitted power-law evaluation, exponent CIs, rational-snapping check, and domain warnings.

format_result_dict classmethod

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

Format the fitted power-law formula, exponent confidence intervals, and snapping results.

参数:

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

Result dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Formatted power-law fit report or domain-inapplicability message.

RationalFitTool

RationalFitTool(context: AgentContext | None = None)

Bases: BaseTool

Tool for fitting rational functions P(x) / Q(x) via linearized least squares and holdout selection.

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 function P(x) / Q(x) (with Q's constant term fixed to 1) across degree combinations.

Solves the linearized system P(x) - y * (Q(x) - 1) ≈ y on a training split, ranks (numerator_degree, denominator_degree) pairs by complexity-penalized holdout RMSE, refits the best degree pair on all finite samples, and checks whether the fitted denominator crosses or approaches zero.

参数:

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

Input variable names or expressions. Defaults to all numeric non-target variables.

None
y str

Target variable name or expression. Defaults to context.target.

None
numerator_degree int

Maximum total degree of numerator polynomial P (0-8, default 2).

2
denominator_degree int

Maximum total degree of non-constant denominator polynomial Q - 1 (0-8, default 1).

1
include_interactions bool

Whether cross-product monomials are included in P and Q.

True
numerator_degrees List[int]

Optional list of numerator degrees to grid-search; overrides numerator_degree.

None
denominator_degrees List[int]

Optional list of denominator degrees to grid-search; overrides denominator_degree.

None
validation_fraction float

Holdout fraction used to score degree pairs (0.05-0.5, default 0.2).

0.2
top_k int

Maximum number of simpler Pareto-optimal alternatives to report (1-20, default 5).

5
complexity_penalty float

Penalty per fitted term added to normalized holdout RMSE (default 1e-12).

1e-12
show_diagnostics bool

Whether to include residual diagnostics in the evaluation output.

True

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Best rational formula evaluation, Pareto alternatives, matrix rank, and denominator zero-crossing diagnostics.

format_result_dict classmethod

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

Format the best rational fit, Pareto alternatives, and pole/rank warnings for the Agent.

参数:

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

Result dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Formatted rational fit report.

ConstantFitTool

ConstantFitTool(context: AgentContext | None = None)

Bases: BaseTool

Tool for snapping floating-point constants in a formula to nearby exact mathematical constants.

execute

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

Test nearby integers, simple fractions, and named constants (pi, e, sqrt(n)) at each numeric literal in eq.

Searches within 5% relative distance of each numeric literal in eq for integers, rationals (numerator <= 32, denominator <= 12), pi, e, sqrt(2)..sqrt(10), and their ±0.5x, ±1x, ±2x multiples. Returns the Pareto front trading off the number of simplified constants against validation R2 (or train R2 when no validation split exists).

参数:

名称 类型 描述 默认
eq str

Formula string containing at least one floating-point or integer literal.

必需
y str

Target variable or expression to score against. Overrides use_eq_as_y when set.

None
use_eq_as_y bool

When True and y is omitted, score against the original eq output instead of context.target.

False

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Nearby constant candidates per literal and the Pareto front of simplified formulas.

format_result_dict classmethod

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

Format candidate constant replacements and the Pareto front for the Agent.

参数:

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

Result dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Formatted summary of constant replacements and Pareto-optimal formulas.

CodeExecutorTool

CodeExecutorTool(context: AgentContext | None = None)

Bases: BaseTool

Tool for running isolated, data-only Python analysis scripts in an OS sandbox.

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 a Python snippet in an isolated OS sandbox with the dataset piped via stdin.

Use this tool for custom statistical tests, transformations, or exploratory checks not covered by built-in analysis tools: 1. Load the dataset via import sys, json; data_dict = json.loads(sys.stdin.read()). 2. Print concise results with print(...) (only stdout/stderr are returned). 3. Scientific Python packages (numpy, scipy, scikit-learn, sympy, pandas) are pre-installed; filesystem writes outside the sandbox, network access, and subprocesses are blocked.

参数:

名称 类型 描述 默认
program str

Python code to run. Read sys.stdin as JSON to inspect context.data.

必需
timeout_seconds int

Wall-clock timeout in seconds (1-120, default 30).

DEFAULT_TIMEOUT_SECONDS
memory_limit_mb int

Maximum address-space memory in MB (64-4096, default 1024).

DEFAULT_MEMORY_LIMIT_MB
output_limit_bytes int

Maximum stdout/stderr capture size in bytes (1024-1048576, default 65536).

DEFAULT_OUTPUT_LIMIT_BYTES

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Sandbox stdout, stderr, timing, and resource-usage metrics.

format_result_dict classmethod

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

Format sandbox stdout, stderr, and execution duration for the Agent.

参数:

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

Result dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Formatted program output and runtime duration.

extract_code classmethod

extract_code(code: str) -> str

Strip optional Markdown code fences (e.g. python ...) from a code string.

参数:

名称 类型 描述 默认
code str

Raw code string or Markdown-fenced code block.

必需

返回:

名称 类型 描述
str str

Extracted Python source code.

serialization classmethod

serialization(value: Any) -> Any

Recursively convert NumPy arrays, scalars, and containers into JSON-serializable objects.

参数:

名称 类型 描述 默认
value Any

Arbitrary context data value to serialize.

必需

返回:

名称 类型 描述
Any Any

JSON-serializable Python primitive, list, or dict.

bounded_int classmethod

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

Coerce value to an integer clamped within [minimum, maximum].

参数:

名称 类型 描述 默认
value Any

Input value to coerce and clamp.

必需
default int

Fallback integer used when value cannot be converted.

必需
minimum int

Inclusive lower bound.

必需
maximum int

Inclusive upper bound.

必需

返回:

名称 类型 描述
int int

Clamped integer value.

WorkspaceCodeExecutorTool

WorkspaceCodeExecutorTool(
    context: AgentContext | None = None,
)

Bases: CodeExecutorTool

Tool for running sandboxed Python code with read/write access to the active workspace directory.

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 an OS sandbox with the active workspace mounted as the working directory.

  1. Runs with cwd set to the workspace root so relative paths (e.g., open("data.csv"), np.save("context.data/x.npy", arr)) read and write workspace files directly.
  2. Also receives serialized context.data on sys.stdin (optional to read).
  3. Scientific Python libraries are available; access outside the workspace, networking, and subprocess creation are blocked.

参数:

名称 类型 描述 默认
program str

Python source code to execute inside the workspace sandbox.

必需
timeout_seconds int

Wall-clock timeout in seconds (1-120, default 30).

DEFAULT_TIMEOUT_SECONDS
memory_limit_mb int

Maximum address-space memory in MB (64-4096, default 1024).

DEFAULT_MEMORY_LIMIT_MB
output_limit_bytes int

Maximum stdout/stderr capture size in bytes (1024-1048576, default 65536).

DEFAULT_OUTPUT_LIMIT_BYTES

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Sandbox stdout, stderr, timing, and resource-usage metrics.

ReadSkill

ReadSkill(context: AgentContext | None = None)

Bases: BaseTool

Tool for reading skill instructions (SKILL.md), auxiliary skill files, or searching skills.

Initialize the tool and filter advertised skills to those enabled in context.args.

参数:

名称 类型 描述 默认
context AgentContext | None

Runtime :class:AgentContext supplying skill_manager and enabled_skills.

None

execute

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

Read a skill's SKILL.md, read a specific file inside a skill, or search skills by query.

参数:

名称 类型 描述 默认
name str

Exact skill name to read. Leave empty when searching with query.

''
file_path str

Optional path relative to the skill directory (e.g., "tool.py" or "references/guide.md"). Reads SKILL.md when empty.

''
show_tree bool

Whether to include a listing of all files in the skill directory.

False
query str

Keyword or task description used to rank matching skills when name is empty.

''

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: XML-wrapped skill content, optional directory tree, or ranked skill matches.

format_result_dict classmethod

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

Format the skill content and optional directory tree for the Agent.

参数:

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

Result dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Skill content followed by optional directory tree entries.

CreateSkill

CreateSkill(context: AgentContext | None = None)

Bases: BaseTool

Tool for distilling reusable tactics or custom tools from the current run into a skill.

execute

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

Create and save a reusable skill (instructions, data-analysis tool, or formula-proposer tool).

Synthesizes the current Agent conversation and request using the configured LLM, determines whether the skill should be instruction-only (SKILL.md) or include a sandboxed custom tool (tool.py), validates the draft, and registers any new tool.

参数:

名称 类型 描述 默认
request str

Clear description of the reusable tactic, workflow, or custom tool to capture.

''
force bool

Overwrite an existing editable skill's SKILL.md and tool.py if True.

False
history_messages int | None

Optional number of recent conversation messages to include as context.

None

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Creation status, skill name, skill type, and registered custom tool metadata.

format_result_dict classmethod

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

Format the skill creation confirmation for the Agent.

参数:

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

Result dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Concise confirmation of the created skill and any registered custom tool.

EditSkill

EditSkill(context: AgentContext | None = None)

Bases: BaseTool

Tool for patching an existing editable SKILL.md file with exact SEARCH/REPLACE blocks.

execute

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

Update an editable skill's SKILL.md using exact SEARCH/REPLACE blocks.

Use this tool when concrete evidence from the current run refines or corrects an existing skill. Prefer small, generalizable edits; never hard-code dataset-specific constants or unverified guesses into a reusable skill.

参数:

名称 类型 描述 默认
name str

Exact name of the editable skill to modify.

必需
patch str

One or more <<<<<<< SEARCH ... ======= ... >>>>>>> REPLACE blocks where each SEARCH section matches SKILL.md exactly once.

必需

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Counts of requested and applied replacements plus any match warnings.

format_result_dict classmethod

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

Format the skill patch summary and any replacement warnings for the Agent.

参数:

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

Result dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Summary of applied replacements and warnings.

EditTool

EditTool(context: AgentContext | None = None)

Bases: BaseTool

Tool for patching and hot-reloading a custom tool.py inside an editable skill.

execute

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

Patch and reload a custom tool in an editable skill using exact SEARCH/REPLACE blocks.

参数:

名称 类型 描述 默认
name str

Skill directory name containing tool.py (not the tool's metadata.name).

必需
tool_patch str

One or more <<<<<<< SEARCH ... ======= ... >>>>>>> REPLACE blocks for tool.py. Each SEARCH block must match exactly once, and the resulting class must not use @BaseTool.register(...).

必需
skill_patch str

Optional SEARCH/REPLACE blocks to apply simultaneously to SKILL.md.

''

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Reload status, skill name, registered tool_name, and any patch warnings.

format_result_dict classmethod

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

Format the custom tool patch and reload status for the Agent.

参数:

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

Result dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Confirmation message or failure diagnostics.

SINDyTool

SINDyTool(context: AgentContext | None = None)

Bases: BaseTool

Sparse regression symbolic-discovery tool powered by PySINDy (STLSQ).

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 regression (STLSQ) over polynomial and optional trigonometric bases.

Constructs a library of polynomial/interaction terms (up to poly_degree) and optional Fourier terms (sin, cos), then prunes small coefficients using Sequentially Thresholded Least Squares. Fast and well-suited for additive polynomial, interaction, and harmonic laws. Returns a submission-eligible candidate when y is the default target variable and x does not depend on y.

参数:

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

Input variable names or expressions, e.g., ["x1", "x2"]. Defaults to all numeric non-target variables.

None
y str

Target variable name or expression, e.g., "y" or "y - x1". Defaults to the discovery target.

None
poly_degree int

Maximum polynomial degree in the candidate library (1-5, default 3).

3
include_trig bool

Whether to append sin/cos Fourier terms to the feature library.

False
threshold float

STLSQ coefficient cutoff (0.01-1.0, default 0.1). Larger values yield sparser formulas.

0.1
max_samples int

Maximum number of rows subsampled for fitting (default 5000).

5000
show_diagnostics bool

Whether to include residual diagnostics in the evaluation output.

True

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Fitted formula evaluation, SINDy configuration, and any warnings.

format_result_dict classmethod

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

Format the SINDy evaluation result and library settings for the Agent.

参数:

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

Result dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Formatted SINDy fit summary.

PySRTool

PySRTool(context: AgentContext | None = None)

Bases: BaseTool

Evolutionary symbolic-regression tool powered by PySR (SymbolicRegression.jl).

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 search to discover nonlinear symbolic formulas.

Best for discovering nonlinear combinations of algebraic, trigonometric, exponential, logarithmic, and radical terms. Because evolutionary search is computationally intensive, restrict binary_operators, unary_operators, and input features x to those motivated by your current hypothesis. Returns a submission-eligible candidate when y is the default target variable and x does not depend on y.

参数:

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

Binary operators to search over, chosen from ["+", "-", "*", "/", "^"].

必需
unary_operators List[str]

Unary operators to search over, chosen from ["sin", "cos", "exp", "log", "sqrt", "square", "cube", "abs", "tanh", "sign"].

必需
x List[str]

Input variable names or expressions, e.g., ["x1", "(x1 - x2)**2"]. Defaults to all numeric non-target variables.

None
y str

Target variable name or expression, e.g., "y" or "log(y)". Defaults to the discovery target.

None
timeout int

Search time budget in seconds (10-120, default 30). Increase to 60-120 if an initial run underfits.

30
maxsize int

Maximum expression tree node count (10-40, default 25).

25
max_samples int

Maximum number of rows subsampled for PySR fitting (default 500).

500
show_diagnostics bool

Whether to include residual diagnostics in the evaluation output.

True

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Best formula evaluation, Pareto-front alternatives, and search diagnostics.

format_result_dict classmethod

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

Format PySR's best formula, Pareto-front trade-offs, and retry hints for the Agent.

参数:

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

Result dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Human- and LLM-readable summary of the PySR run.

PropertyPredictorTool

PropertyPredictorTool(context: AgentContext | None = None)

Bases: BaseTool

Neural-network tool for predicting per-variable monotonicity, convexity, periodicity, and multiplicative separability.

execute

execute() -> Dict[str, Any]

Predict heuristic mathematical properties of the target with respect to each variable and pairwise combination.

Uses a pretrained Transformer to estimate: - Monotonicity: increasing, decreasing, constant, or non-monotonic per variable. - Convexity: convex, concave, affine, or non-convex/concave per variable. - Periodicity: heuristic periodicity score per variable (note: modulated terms like x * sin(w * t) may appear non-periodic marginally). - Multiplicative Separability: whether y factors into f(x1) * g(x2) * .... Also evaluates pairwise combinations (xi*xj, xi+xj, xi-xj, xi/xj) to surface hidden composite symmetries.

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Predicted property labels and confidence scores for individual variables and pairwise combinations.

format_result_dict classmethod

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

Format neural property predictions and search hints for the Agent.

参数:

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

Result dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Formatted property report with confidence scores and modeling hints.

WorkspaceShellTool

WorkspaceShellTool(context: AgentContext | None = None)

Bases: BaseTool

Tool for inspecting and manipulating workspace files with a safe, restricted POSIX-like command subset.

get_doc classmethod

get_doc() -> dict[str, str]

Return runtime skill documentation for workspace-shell.

返回:

类型 描述
dict[str, str]

dict[str, str]: Skill metadata, supported command syntax, and pipeline examples.

execute

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

Run a restricted shell command or | pipeline inside the workspace directory.

Supports ls, cat, head, tail, wc, grep, sort, cut, cp, mv, rm, mkdir, gunzip, gzip, unzip, and tar (extract only). Common forms include ls -laL and head -n 20 (or head -20). All paths must stay within the workspace root; shell redirection (>, <), chaining (;, &&, ||), globbing, and unlisted commands are rejected. Call read_skill with "workspace-shell" for full flag syntax.

参数:

名称 类型 描述 默认
command str

Command or |-connected pipeline string, e.g., "ls -la", "cat data.csv | head -n 5", or "unzip archive.zip -d raw".

必需
output_limit_bytes int

Maximum stdout size in bytes retained per pipeline stage (1024-1048576, default 65536).

DEFAULT_OUTPUT_LIMIT_BYTES

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Command execution status, stdout, stderr, and exit_code.

format_result_dict classmethod

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

Format workspace command stdout, stderr, or failure details for the Agent.

参数:

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

Result dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Command output or error message.

execute_single

execute_single(
    command: str, stdin_text: str = ""
) -> Dict[str, Any]

Execute a single command segment (without pipes) given optional stdin text.

参数:

名称 类型 描述 默认
command str

Single command string without | operators.

必需
stdin_text str

Input text piped from a preceding command segment.

''

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Command execution status, stdout, stderr, and exit_code.

SubagentTool

SubagentTool(context: AgentContext | None = None)

Bases: BaseTool

Tool for delegating context-isolated hypothesis generation, candidate critique, residual diagnosis, or search recovery.

execute

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

Invoke an independent, context-isolated scientific critic or hypothesis generator.

Use this tool when an independent perspective helps: proposing distinct formula families before spending search budget, auditing near-tied candidates for redundancy or overfitting, interpreting structured residuals, or breaking out of a stagnated search. The subagent cannot call tools or mutate state; it returns falsifiable recommendations for the main Agent.

参数:

名称 类型 描述 默认
objective str

Specific scientific question or search decision for the subagent to address.

必需
mode str

Subagent role: "hypothesis_generation", "candidate_critique", "residual_diagnosis", or "search_recovery".

'hypothesis_generation'
candidate_formulas List[str]

Optional list of candidate formula strings to audit or compare.

None
evidence str

Compact summary of fit metrics, residual patterns, domain constraints, or prior attempts.

''

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Subagent mode, objective, critique/recommendations text, and token usage.

format_result_dict classmethod

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

Format the subagent's independent analysis for the main Agent.

参数:

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

Result dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Labeled subagent response.

WebFetchTool

WebFetchTool(context: AgentContext | None = None)

Bases: BaseTool

Tool for fetching readable plain text from a public HTTP(S) webpage.

execute

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

Fetch and extract readable text from a public HTTP or HTTPS webpage URL.

Rejects non-public IP addresses, credentials in URLs, and HTTP redirects. If a site blocks automated access (HTTP 401/403/429), returns blocked=True so you can search for an alternative source instead of retrying.

参数:

名称 类型 描述 默认
url str

Absolute public http:// or https:// URL to fetch.

必需
max_characters int

Maximum number of extracted text characters to return (1000-50000, default 30000).

30000

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: URL, extracted text, truncation flag, and block status if access was denied.

WebSearchTool

WebSearchTool(context: AgentContext | None = None)

Bases: BaseTool

Tool for searching the public web for scientific papers, benchmarks, and documentation.

execute

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

Search the public web for scientific literature, documentation, and domain context.

参数:

名称 类型 描述 默认
query str

Specific search query string.

必需
max_results int

Maximum number of search results to return (1-10, default 5).

5

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Search query, provider name, and list of {"title", "url", "snippet"} results.

ValidateContextDataTool

ValidateContextDataTool(
    context: AgentContext | None = None,
)

Bases: BaseTool

Tool for validating a workspace context.data manifest and NPY array collection.

execute

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

Validate a workspace context.data directory and return actionable repair instructions for any errors.

Runs both load_context_data and inspect_context_data without mutating the live :class:AgentContext. A passing check guarantees that InteractiveSession can load the dataset cleanly after the current Agent turn.

参数:

名称 类型 描述 默认
path str

Workspace-relative path to the context-data directory (default "context.data").

'context.data'

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Validation status, variable/axis summaries, warnings, and specific repair actions.

format_result_dict classmethod

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

Format validation diagnostics, variable summaries, and repair steps for the Agent.

参数:

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

Validation report dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Human- and LLM-readable validation report.

PDFReadTool

PDFReadTool(context: AgentContext | None = None)

Bases: BaseTool

Tool for extracting text from local workspace PDFs or public HTTP(S) PDF URLs.

execute

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

Extract text from a page range of a workspace PDF file or public HTTP(S) PDF URL.

参数:

名称 类型 描述 默认
source str

Workspace-relative PDF path or an absolute public http:// / https:// URL.

必需
start_page int

1-indexed first page to extract (default 1).

1
max_pages int

Maximum number of pages to read in one call (1-50, default 10).

10

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Source identifier, total page_count, and extracted pages list.

format_result_dict classmethod

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

Format extracted PDF pages as Markdown sections for the Agent.

参数:

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

Result dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Page-by-page Markdown text.

EICTool

EICTool(context: AgentContext | None = None)

Bases: BaseTool

Tool for computing Effective Information Criterion (EIC) numerical-stability diagnostics across expression subtrees.

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 Effective Information Criterion (EIC) stability diagnostics.

Injects relative Gaussian noise after each non-leaf operator to measure noise amplification and numerical information loss across all subtrees. Lower EIC indicates better numerical stability; high subtree EIC paired with near-zero output impact reveals masked or redundant subtrees.

参数:

名称 类型 描述 默认
f str

Symbolic formula string to diagnose.

必需
noise_level float

Relative Gaussian noise standard deviation injected after each operator (0 < noise_level < 1, default 0.001).

0.001
repeats int

Number of Monte Carlo perturbation runs to average (1-100, default 8).

8
random_state int

Random seed for reproducible noise injection.

0
zero_epsilon float

Positive fallback denominator when a clean subtree output equals zero (default 1e-6).

1e-06

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Formula EIC, root-output EIC, worst subtree path, per-subtree stats, and an annotated expression tree.

format_result_dict classmethod

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

Format EIC stability scores and the annotated expression tree for the Agent.

参数:

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

Result dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Formatted EIC summary and annotated tree.

get_doc classmethod

get_doc() -> dict[str, str]

Return runtime skill documentation for eic-structural-stability.

返回:

类型 描述
dict[str, str]

dict[str, str]: Skill metadata and usage instructions for EIC diagnostics.

ND2Tool

ND2Tool(context: AgentContext | None = None)

Bases: BaseTool

Tool for discovering graph and network-dynamics formulas via ND2 (NDformer + MCTS).

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 Monte Carlo Tree Search (ND2) to discover node or edge dynamics on a network.

Requires adjacency matrix A and/or edge list G in context.data, a 2D target of shape (time, node) or (time, edge), and matching node/edge features. ND2_HOME must point to the ND2 repository and ND2_CHECKPOINT to checkpoint.pth.

参数:

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

Node-level feature names. Inferred from arrays ending in the node dimension when omitted.

None
vars_edge List[str]

Edge-level feature names. Inferred from arrays ending in the edge dimension when omitted.

None
y str

Target variable name. Defaults to context.target.

None
root_type str

Target level to predict, either "node" or "edge".

'node'
binary_operators List[str]

Allowed ND2 binary operator tokens. Defaults to DEFAULT_BINARY.

None
unary_operators List[str]

Allowed ND2 unary/graph operator tokens. Defaults to DEFAULT_UNARY.

None
timeout int

Search wall-time limit in seconds (10-3600, default 60).

60
episode_limit int

Maximum MCTS episodes (1-1000000, default 10000).

10000
beam_size int

Beam width retained per MCTS expansion (1-100, default 10).

10
max_coeff_num int

Maximum number of fitted scalar coefficients (0-20, default 5).

5

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Discovered graph-dynamics formula, train/validation metrics, and ND2 config.

backend_status classmethod

backend_status() -> Dict[str, Any]

Check whether the external ND2 repository and model checkpoint are available.

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Installation status, repository root, and checkpoint path details.

format_result_dict classmethod

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

Format the discovered ND2 formula and train/validation metrics for the Agent.

参数:

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

Result dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Concise summary of the discovered network-dynamics formula and fit metrics.

get_doc classmethod

get_doc() -> dict[str, str]

Return runtime skill documentation for nd2-network-dynamics.

返回:

类型 描述
dict[str, str]

dict[str, str]: Skill metadata and usage instructions for ND2 network dynamics.

SR4MDLTool

SR4MDLTool(context: AgentContext | None = None)

Bases: BaseTool

Symbolic-regression tool using MDLformer-guided Monte Carlo Tree Search (SR4MDL).

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 (SR4MDL) for minimum-description-length symbolic discovery.

Evaluates input expressions x and target y, runs MCTS guided by a pretrained MDLformer network, and evaluates the discovered formula on train/validation splits. Requires SR4MDL_HOME and SR4MDL_CHECKPOINT to be configured.

参数:

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

Binary operators to search over, chosen from ["+", "-", "*", "/"].

必需
unary_operators List[str]

Unary operators to search over, chosen from ["sqrt", "sin", "cos", "neg", "inv", "log", "exp", "square", "cube"].

必需
x List[str]

Input variable names or expressions. Defaults to all numeric non-target variables.

None
y str

Target variable name or expression. Defaults to context.target.

None
timeout int

Soft wall-time budget in seconds (10-600, default 60).

60
maxsize int

Maximum expression tree length (5-100, default 30).

30
max_samples int

Maximum number of samples subsampled for fitting (20-5000, default 500).

500
n_iter int

Maximum MCTS iterations (1-10000, default 100).

100
show_diagnostics bool

Whether to include residual diagnostics in the evaluation output.

True

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Discovered formula evaluation, backend status, and search configuration.

backend_status classmethod

backend_status() -> Dict[str, Any]

Check whether the external SR4MDL repository and checkpoint are installed.

返回:

类型 描述
Dict[str, Any]

Dict[str, Any]: Installation status, repository path, and checkpoint availability.

format_result_dict classmethod

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

Format the SR4MDL evaluation result for the Agent.

参数:

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

Result dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Formatted SR4MDL evaluation output.

get_doc classmethod

get_doc() -> dict[str, str]

Return runtime skill documentation for sr4mdl-search.

返回:

类型 描述
dict[str, str]

dict[str, str]: Skill metadata and usage instructions for SR4MDL search.

ModelTestTool

ModelTestTool(context: AgentContext | None = None)

Bases: BaseTool

Internal connectivity-check tool used to verify LLM tool-calling support.

execute

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

Echo the exact answer string requested by a model connectivity check.

参数:

名称 类型 描述 默认
answer str

Exact string requested by the connectivity test prompt.

必需

返回:

类型 描述
dict[str, str]

dict[str, str]: Dictionary mapping "answer" to answer.

FinishSearchTool

FinishSearchTool(context: AgentContext | None = None)

Bases: BaseTool

Tool for requesting early termination of an interactive symbolic-regression run.

execute

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

Request that the interactive Agent check its stopping policy and finish the search.

参数:

名称 类型 描述 默认
reason str

Concise explanation of why the current search is ready to conclude.

必需

返回:

类型 描述
dict[str, str]

dict[str, str]: Request marker resolved by the interactive Agent loop.

format_result_dict classmethod

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

Format the resolved stop-request status for the Agent.

参数:

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

Resolution dictionary containing status and optional reason.

必需

返回:

名称 类型 描述
str str

Message indicating whether the search stopped or why it must continue.

ReadSourceTool

ReadSourceTool(context: AgentContext | None = None)

Bases: BaseTool

Tool for browsing installed SRHarness source files and querying Python symbol definitions or usages.

execute

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

List a source directory, read a source file, or locate a Python symbol's definitions and usages.

参数:

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

Optional file or directory path relative to src (e.g., "sr_harness/evaluator"). Defaults to the src root.

None
symbol str | None

Optional Python class, function, or method name (e.g., "DefaultEvaluator.evaluate").

None
include_implementation bool

Whether symbol queries return matching AST definitions (default True).

True
include_references bool

Whether symbol queries return matching attribute/name/import references (default False).

False

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Directory listing, file source code, or symbol definitions and references.

format_result_dict classmethod

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

Format a source file, directory tree, or symbol lookup result for the Agent.

参数:

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

Structured dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Formatted source code listing or symbol search results.

ValidateEvaluatorTool

ValidateEvaluatorTool(context: AgentContext | None = None)

Bases: BaseTool

Tool for testing a workspace custom evaluator file against a formula in isolation.

execute

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

Load and test a custom evaluator on a formula without mutating the active AgentContext.

参数:

名称 类型 描述 默认
f str

Symbolic formula string to score with the evaluator.

必需
evaluator_file str | None

Optional workspace-relative Python file (e.g., "context.evaluator/custom_evaluator.py"). Tests the currently attached context evaluator when omitted.

None
y str | None

Optional target variable or expression; defaults to context.target.

None
fit bool

Whether to fit formula parameters on the training split before scoring.

False
show_diagnostics bool

Whether to include residual diagnostics in the evaluation report.

False

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Evaluator class name, source file, and formula evaluation output.

format_result_dict classmethod

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

Format the evaluator identity and formula evaluation summary for the Agent.

参数:

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

Result dictionary returned by :meth:execute.

必需

返回:

名称 类型 描述
str str

Formatted evaluator validation output.

VariableRolesTool

VariableRolesTool(context: AgentContext | None = None)

Bases: BaseTool

Inspect variables; edit roles through the workbench only when explicitly requested.

execute

execute(
    roles: dict[str, str] | None = None,
    user_request: str = "",
) -> dict[str, Any]

List variable descriptions and roles, or apply an explicitly requested role change.

Reading is always allowed. Only change roles when the user explicitly asks to select/configure variables; merely asking to build an evaluator is not authorization. Never select variables to improve a validation score. Unused variables remain in context.data on disk for later selection.

参数:

名称 类型 描述 默认
roles dict[str, str] | None

Omit for read-only inspection. Otherwise map variable names to 'feature', 'target', or 'unused'. Unmentioned roles are preserved; the resulting selection must have exactly one target. Axis coordinates are listed for reference, not assigned model roles.

None
user_request str

For edits, quote the user's explicit role-configuration request verbatim for the audit log; not needed for inspection.

''

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Complete variable metadata, active selection, revision, and whether this call changed roles.

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')

asin module-attribute

asin = arcsin

acos module-attribute

acos = arccos

atan module-attribute

atan = arctan

exp module-attribute

exp = _unary('exp')

log module-attribute

log = _unary('log')

log10 module-attribute

log10 = _unary('log10')

log2 module-attribute

log2 = _unary('log2')

ln module-attribute

ln = log

lg module-attribute

lg = 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",
    "acos",
    "aggr",
    "arccos",
    "arcsin",
    "arctan",
    "asin",
    "atan",
    "cos",
    "cosh",
    "bind_parameters",
    "cot",
    "count_parameters",
    "csc",
    "delay",
    "desugar",
    "evaluate",
    "exp",
    "fit",
    "fold_constants",
    "function",
    "gather",
    "grouped_param",
    "inv",
    "lg",
    "ln",
    "log",
    "log10",
    "log2",
    "param",
    "parameter_values",
    "parse",
    "reduction",
    "render",
    "sec",
    "sech",
    "sigmoid",
    "sign",
    "sin",
    "sinh",
    "sour",
    "sqrt",
    "tan",
    "tanh",
    "targ",
    "unbound_parameters",
]

Aggregate dataclass

Aggregate(relation: Expression, operand: Expression)

Bases: Expression

Shorthand aggr(...) node that desugars into a canonical indexed :class:Reduction.

属性:

名称 类型 描述
relation Expression

Relation expression or product containing it.

operand Expression

Message expression to aggregate by target node.

Binary dataclass

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

Bases: Expression

Binary arithmetic operation node (+, -, *, /, **).

属性:

名称 类型 描述
operator str

Binary operator symbol.

left Expression

Left-hand child expression.

right Expression

Right-hand child expression.

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

Elementwise mathematical or delay function call node (e.g., sin(x), exp(x), delay(x, tau)).

属性:

名称 类型 描述
name str

Canonical function name.

arguments tuple[Expression, ...]

Tuple of argument expression nodes.

Gather dataclass

Gather(relation: Expression, operand: Expression)

Bases: Expression

Edge- or hyperedge-level evaluation node gather(A[i, j], expr) returning relation-aligned values.

属性:

名称 类型 描述
relation Expression

Indexed relation expression defining the active edges or hyperedges.

operand Expression

Expression evaluated at each relation entry.

GroupedParameter dataclass

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

Bases: Expression

Category-specific parameter that fits one scalar value per distinct category of by.

属性:

名称 类型 描述
by Expression

Categorical symbol or expression determining group membership.

name str | None

Optional identifier for the grouped parameter family.

value Mapping[Any, float] | None

Optional mapping from category label to bound/initial float value.

default float | None

Optional fallback value used for unseen categories.

Index dataclass

Index(name: str)

Symbolic index variable (such as i, j, k) used in graph and hypergraph expressions.

属性:

名称 类型 描述
name str

Identifier name of the symbolic index.

Indexed dataclass

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

Bases: Expression

Variable or relation expression annotated with symbolic indices (e.g., x[i] or A[i, j]).

属性:

名称 类型 描述
base Expression

Underlying variable or relation expression.

indices tuple[Index, ...]

Tuple of :class:Index nodes bound to base.

Number dataclass

Number(value: int | float)

Bases: Expression

Constant numeric literal node in a symbolic expression tree.

属性:

名称 类型 描述
value int | float

Integer or floating-point numeric value.

Parameter dataclass

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

Bases: Expression

Named scalar parameter optimized during expression fitting (created via param('name')).

属性:

名称 类型 描述
name str

Shared parameter identifier across the expression.

value float | None

Optional bound or initial numeric value.

Reduction dataclass

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

Bases: Expression

Indexed summation node (e.g., sum[j](A[i, j], x[i] * x[j])).

属性:

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

Tuple of :class:Index variables eliminated by the sum.

operand Expression

Message expression being summed.

relation Expression | None

Optional indexed relation expression (such as A[i, j]) restricting the sum.

RelationLift dataclass

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

Bases: Expression

Shorthand targ(x) or sour(x) projection node used inside :class:Aggregate.

属性:

名称 类型 描述
role str

Projection role ("targ" or "sour").

operand Expression

Node-level expression being projected onto relation endpoints.

relation Expression | None

Optional explicit relation expression.

Symbol dataclass

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

Bases: Expression

Named dataset variable or coordinate axis symbol in a symbolic expression.

属性:

名称 类型 描述
name str

Identifier name of the variable in context.data.

value Any

Optional bound NumPy array or scalar value.

FitResult dataclass

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

Outcome of fitting an expression's free parameters to target observations.

属性:

名称 类型 描述
expression Expression

Copy of the input expression with fitted parameter values bound.

parameters dict[str, Any]

Dictionary mapping parameter names to fitted values.

loss float

Final mean squared error achieved on the training observations.

success bool

Whether the numerical optimizer converged cleanly.

message str

Optimizer status message.

n_iter int

Number of optimizer iterations performed.

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]

Extract a dictionary of all parameter values already bound on nodes in expression.

参数:

名称 类型 描述 默认
expression Expression

Symbolic expression tree to inspect.

必需

返回:

类型 描述
dict[str, Any]

dict[str, Any]: Mapping from parameter or grouped-parameter keys to their bound values.

unbound_parameters

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

Return the names of all parameter nodes in expression that do not yet have bound values.

参数:

名称 类型 描述 默认
expression Expression

Symbolic expression tree to inspect.

必需

返回:

类型 描述
list[str]

list[str]: Unique unbound parameter names in preorder appearance order.

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 a copy of expression with its parameter nodes populated from parameters.

参数:

名称 类型 描述 默认
expression Expression

Symbolic expression containing :class:Parameter or :class:GroupedParameter nodes.

必需
parameters Mapping[str, Any]

Mapping of parameter names to fitted scalar or per-category values.

必需

返回:

名称 类型 描述
Expression Expression

Copy of expression with bound parameter 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.