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

model.py

1"""Translate Responses model items into tool calls for the provider-neutral Agent loop."""23from __future__ import annotations45from dataclasses import dataclass6import json7from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Sequence, Set8from sim_platform.domain.json_values import copy_json9from sim_platform.domain.models import ContractError10from sim_platform.models.contracts import ProviderError11from sim_platform.agents.tools.protocol.errors import ToolError12from .conversation import INSTRUCTIONS1314if TYPE_CHECKING:  # Annotation only.15    from sim_platform.agents.tools.client.base import Tool16    from .client import AgentClient17    from .conversation import Conversation181920@dataclass(frozen=True)21class ToolCall:22    """A requested tool invocation; the original provider item stays in the conversation."""2324    call_id: str25    name: str26    arguments_json: str2728    def arguments(self) -> Dict[str, Any]:29        try:30            value = copy_json(json.loads(self.arguments_json))31        except (ValueError, RecursionError, TypeError, ContractError) as exc:32            raise ToolError('INVALID_JSON', 'tool arguments must be finite JSON') from exc33        if type(value) is not dict:34            raise ToolError('INVALID_SCHEMA', 'tool arguments must be an object')35        return value363738def validate_response(response: Any, previous_call_ids: Set[str]) -> None:39    """Reject malformed/reused call identities before an attempt succeeds or tools run."""40    if type(response) is not dict or type(response.get('output')) is not list:41        raise ProviderError('FORMAT_ERROR')42    seen: Set[str] = set()43    for item in response['output']:44        if type(item) is not dict or item.get('type') not in (45            'message',46            'reasoning',47            'function_call',48        ):49            raise ProviderError('FORMAT_ERROR')50        if item.get('status') not in (None, 'completed'):51            raise ProviderError('FORMAT_ERROR')52        if item['type'] != 'function_call':53            continue54        identity = item.get('call_id')55        if (56            not isinstance(identity, str)57            or not identity58            or identity in seen59            or identity in previous_call_ids60            or not isinstance(item.get('name'), str)61            or not isinstance(item.get('arguments'), str)62        ):63            raise ProviderError('FORMAT_ERROR')64        seen.add(identity)656667class ResponsesModel:68    """Keep provider payloads and function-call decoding out of TradingAgent.6970    Model IO and attempts still use AgentClient and the existing Runtime policy.71    The adapter retains all original output items, including reasoning. It does72    not rerun tools, summarize context or decide when a task is finished.73    """7475    def __init__(self, client: AgentClient) -> None:76        self.client = client7778    @staticmethod79    def payload(80        conversation: Conversation, tools: Iterable[Tool], limits: Dict[str, Any]81    ) -> Dict[str, Any]:82        """The Responses request for the conversation and the tools' JSON schemas."""83        return dict(84            input=copy_json(conversation.items),85            instructions=INSTRUCTIONS,86            tools=[87                dict(88                    type='function',89                    name=tool.function_name,90                    description=tool.description,91                    parameters=tool.input_schema(limits),92                    strict=False,93                )94                for tool in tools95            ],96            parallel_tool_calls=False,97        )9899    def respond(self, conversation: Conversation, tools: Sequence[Tool]) -> List[ToolCall]:100        """Ask the model once; keep its output in the conversation and return its tool calls."""101102        def validate(value: Any) -> None:103            validate_response(value, conversation.call_ids)104105        response = self.client.request_model(106            self.payload(conversation, tools, self.client.limits),107            validate_response=validate,108            label=getattr(conversation, 'label', None),109        )110        validate(response)111        conversation.accept_response(response['output'])112        return [113            ToolCall(item['call_id'], item['name'], item['arguments'])114            for item in response['output']115            if item['type'] == 'function_call'116        ]