Skip to content

SRHarness Core Abstractions

To add a custom tool or adapt SRHarness to a new model output format, you only need to work with two base classes:

  • BaseTool: Defines how a tool declares its parameters, accesses runtime data, and returns structured results;
  • BaseParser: Normalizes tool calls across native function-calling APIs, JSON outputs, and plain-text completions.

See Formula Evaluation and Custom Evaluators for the formula evaluation protocol, Structured Data and context.data for the dataset storage format, SRHarness Agent Workflow for how the Agent coordinates these components, and the API Reference for full class and method signatures.

Tool Base Class: BaseTool

Every callable tool in SRHarness inherits from BaseTool. In most cases, you only need to declare metadata and implement execute(); parameter validation, timing, error handling, and output formatting are handled by the base class.

from typing import Any

from sr_harness.tools import BaseTool, ToolMetadata


@BaseTool.register("example_tool")
class ExampleTool(BaseTool):
    metadata = ToolMetadata(name="example_tool")

    def execute(self, expression: str, limit: int = 10) -> dict[str, Any]:
        """Inspect an expression.

        Args:
            expression: Expression supplied by the model.
            limit: Maximum number of returned items.

        Returns:
            Structured inspection results.
        """
        parsed = self.parse_formula(expression)
        return {"expression": parsed.to_str(), "limit": limit}

Input conventions

  • Keep parameters simple and typed: Because arguments to execute() are generated by the language model, use simple JSON-serializable types and complete type annotations.
  • Read runtime state from self.context: Datasets, the active Evaluator, workspace paths, and run settings live on self.context (AgentContext). Never require the model to pass environment objects in tool calls.
  • Automatic schema inference: You can set metadata.description and the JSON parameter schema explicitly, or let BaseTool infer them automatically from the execute() signature, type hints, and Google-style docstring.
  • Selective exposure: Tools registered via @BaseTool.register are available in the global registry, but the Agent only exposes the subset enabled for the current run.

Output and error handling

  • Separate machine data from model-facing text:
  • execute() returns a structured Python dict used for run logging and candidate extraction.
  • format_result_dict() turns that dict into concise, readable text (result_str) for the language model. You can override format_result_dict() to customize what the model sees without changing the logged data structure.
  • Uniform invocation wrapper: Calling a tool invokes BaseTool.__call__(), which records execution time and returns ToolCallResult(ok, result, result_str, meta_data). While result keeps the full structured dictionary, result_str is length-bounded so large outputs cannot overflow the model context window.
  • Recoverable errors vs. control-flow aborts: Ordinary exceptions (including tool timeouts) are caught and returned as ok=False tool results so the model can read the error message and self-correct on the next turn. By contrast, ToolRunAbort—used to halt control flow—propagates upward without being swallowed.
  • Cooperative cancellation: Long-running tools can implement cancel() and check the runtime cancellation signal at safe intervals so user-initiated stops take effect promptly.

Formula-related tools can also reuse built-in BaseTool helper methods for expression normalization, parsing, Evaluator invocation, and metric formatting.

Tool-Call Parser: BaseParser

Note: BaseParser parses model tool calls (which tool to run and with what arguments), whereas mathematical formulas themselves are parsed by the restricted expression parser in SRHarness Engine.

Different model providers express tool calls differently—some support native OpenAI-style function calling, while others emit JSON blocks, XML tags, or structured plain text. BaseParser hides these differences so the SRAgent loop always works with uniform ToolCall and ToolCallResult objects.

BaseParser handles three conversions:

  1. Tool declarations (Tools → Prompt / Schema): Formats enabled tool names, descriptions, and parameter schemas for the model;
  2. Call extraction (Model Output → ToolCall): Parses model responses into zero or more normalized ToolCall objects;
  3. Result formatting (ToolCallResult → Messages): Formats tool execution results as conversation messages for the next turn.

In practice:

  • In openai mode, providers with native function calling receive JSON schemas directly, and BaseAPI converts native tool calls into ToolCall objects.
  • For models without native function calling, text, json, or xml mode injects tool instructions into the prompt and extracts structured ToolCall objects from the generated text.

When a model reply contains only natural-language reasoning without any tool calls, the Parser simply returns an empty list [] rather than fabricating a call or raising a parse error.