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

program.py

1"""Connect a prepared Agent to Runtime work without prescribing its internal loop."""23from __future__ import annotations45from inspect import signature6from typing import TYPE_CHECKING, Any, Dict, Optional, Union, cast7from sim_platform.domain.models import ContractError8from sim_platform.models.contracts import ProviderError9from sim_platform.agents.tools.client.collection import built_in_tools10from .agent import TradingAgent11from .client import AgentClient12from .model import ResponsesModel1314if TYPE_CHECKING:  # Annotation only.15    from sim_platform.agents.hosting.client import AgentProcessClient16    from sim_platform.sdk.context import AgentContext, AgentFactory, ResidentAgent, ScheduledAgent1718DEFAULT_TASK = 'Evaluate current trading opportunities using the available tools. Finish or wait when done; no trade is required.'192021def create_agent(context: AgentContext) -> TradingAgent:22    """Default factory; users can supply another factory without inheriting this template."""23    settings = context.settings24    return TradingAgent(25        model=context.model,26        tools=context.tools.values(),27        instructions=settings['initial_prompt'],28        parameters=settings['parameters'],29    )303132class ConfiguredAgentProgram:33    """Prepare one Agent before Play, then delegate scheduled tasks or a resident loop.3435    factory is a trusted spawn-picklable Python callable, not an import loader.36    Credentials are configured separately after initialization and before Play.37    """3839    def __init__(self, factory: Optional[AgentFactory] = None) -> None:40        self._factory: AgentFactory = factory or create_agent41        self._requires_model = factory is None4243    def prepare(44        self, transport: AgentProcessClient, configuration: Dict[str, Any]45    ) -> PreparedAgent:46        """Build the Agent with its context and check its run() fits the carrier kind."""47        from sim_platform.sdk.context import AgentContext4849        client = AgentClient(transport, configuration, preparing=True)50        context = AgentContext(51            client, ResponsesModel(client), built_in_tools(client), configuration['template']52        )53        agent = self._factory(context)54        resident = configuration.get('integration') == 'python_carrier'55        method = getattr(agent, 'run', None)56        if not callable(method):57            raise ContractError('create_agent(context) must return an Agent with run()')58        try:59            signature(method).bind(*(() if resident else (object(),)))60        except (TypeError, ValueError) as exc:61            raise ContractError(62                'Agent run signature does not match its configured carrier'63            ) from exc64        return PreparedAgent(client, agent, context, resident, self._requires_model)6566    def __call__(self, transport: AgentProcessClient, configuration: Dict[str, Any]) -> None:67        """Convenience for trusted in-process tests; the process host prepares before Play."""68        self.prepare(transport, configuration).run()697071class PreparedAgent:72    """Own one execution's Agent state; nothing is shared with another experiment.7374    Created by ConfiguredAgentProgram.prepare in the Agent child; run() is called75    once after Play and returns when the Agent stops.76    """7778    def __init__(79        self,80        client: AgentClient,81        agent: Union[ScheduledAgent, ResidentAgent],82        context: AgentContext,83        resident: bool,84        requires_model: bool,85    ) -> None:86        self.client, self.agent, self.context, self.resident = client, agent, context, resident87        self.requires_model = requires_model8889    def run(self) -> None:90        self.client.activate()91        try:92            if self.requires_model:93                self.client.prepare_model()94            # prepare() checked that run() matches the carrier kind.95            if self.resident:96                cast('ResidentAgent', self.agent).run()97            else:98                while True:99                    cast('ScheduledAgent', self.agent).run(self.context.next_task(DEFAULT_TASK))100        except ProviderError as error:101            self.client.fail(error.code)102        except ContractError:103            if not self.client.stopping:104                raise