m/market labResearch, with a record.
Source on GitHub ↗

base.py

1"""Tool interfaces for local computation and remote platform operations."""23from __future__ import annotations45from abc import ABC, abstractmethod6from inspect import signature, Parameter7from typing import Any, Dict, Optional, Protocol, Tuple89from sim_platform.domain.json_values import copy_json10from sim_platform.domain.models import ContractError11from ..protocol.errors import ToolError1213ToolResponse = Dict[str, Any]141516class ToolClient(Protocol):17    """What a platform tool proxy needs: the Agent client's call_tool."""1819    def call_tool(self, name: str, arguments: dict) -> ToolResponse:20        """Send a tool operation under the client's active work identity."""21        ...222324def text(description: str) -> Dict[str, Any]:25    """JSON schema for a string argument."""26    return dict(type='string', description=description)272829def counter(description: str) -> Dict[str, Any]:30    """JSON schema for a canonical decimal counter string."""31    return dict(type='string', pattern=r'^(0|[1-9][0-9]*)$', description=description)323334def integer(description: str, minimum: int = 1, maximum: Optional[int] = None) -> Dict[str, Any]:35    """JSON schema for an integer argument with bounds."""36    value: Dict[str, Any] = dict(type='integer', minimum=minimum, description=description)37    if maximum is not None:38        value['maximum'] = maximum39    return value404142SYMBOL = text('The experiment stock symbol, such as AAPL.')43CURSOR = text('A next_cursor returned by this tool; omit on the first page.')44LIMIT = integer('Maximum items in this page.')454647class Tool(ABC):48    """Keep one tool's name, description, arguments and callable behavior together.4950    Subclasses implement a typed run() method. Required arguments come from that51    signature; optional arguments have Python defaults. Both direct code and model52    calls use run(). Local tools execute in the Agent process and return finite53    JSON values. They do not need a platform client or a platform result envelope.54    """5556    name: str57    description: str58    parameters: dict = {}59    category = 'read'60    ends_work = False6162    @classmethod63    def required_arguments(cls) -> Tuple[str, ...]:64        return tuple(65            name66            for name, value in signature(cls.run).parameters.items()67            if name != 'self' and value.default is Parameter.empty68        )6970    @classmethod71    def optional_arguments(cls) -> Tuple[str, ...]:72        return tuple(73            name74            for name, value in signature(cls.run).parameters.items()75            if name != 'self' and value.default is not Parameter.empty76        )7778    @property79    def function_name(self) -> str:80        return self.name.replace('.', '_')8182    def input_schema(self, limits: dict) -> dict:83        """Describe this tool's arguments with the experiment's granted bounds."""84        properties = copy_json(self.parameters)85        return dict(86            type='object',87            properties=properties,88            required=list(self.required_arguments()),89            additionalProperties=False,90        )9192    def invoke(self, arguments: dict) -> Any:93        """Call run() with model-supplied arguments, rejecting missing or extra fields."""94        if type(arguments) is not dict:95            raise ToolError('INVALID_SCHEMA', 'tool arguments must be an object')96        if any(value is None for value in arguments.values()):97            raise ToolError('INVALID_SCHEMA', 'omit optional tool arguments instead of using null')98        try:99            signature(self.run).bind(**arguments)100        except TypeError as exc:101            raise ToolError('INVALID_SCHEMA', 'invalid arguments for ' + self.name) from exc102        try:103            result = self.run(**arguments)104        except ContractError:105            raise106        except (ValueError, TypeError, ArithmeticError) as exc:107            raise ToolError('TOOL_EXECUTION_FAILED', 'tool failed: ' + self.name) from exc108        try:109            return copy_json(result)110        except ContractError as exc:111            raise ToolError('TOOL_RESULT_INVALID', 'tool must return finite JSON') from exc112113    @abstractmethod114    def run(self, *positional: Any, **arguments: Any) -> Any:115        """Execute locally and return a JSON value, such as a number, list or object."""116        raise NotImplementedError117118119class PlatformTool(Tool):120    """Proxy one granted platform operation through the existing Agent client.121122    The server validates permissions, time boundaries and financial rules. A proxy123    does not read platform storage or execute financial logic in the Agent process.124    """125126    # Mutable account/state and financial operations require the financial owner.127    execution_route = 'owner'128129    def __init__(self, client: ToolClient) -> None:130        self.client = client131132    def input_schema(self, limits: dict) -> dict:133        schema = super().input_schema(limits)134        for field, limit in (135            ('limit', 'page_items'),136            ('order_limit', 'page_items'),137            ('levels', 'depth_levels'),138        ):139            if field in schema['properties']:140                schema['properties'][field]['maximum'] = limits[limit]141        return schema