agent.py
1"""A small task-oriented trading Agent; scheduling and transport live outside it."""23from __future__ import annotations45from typing import TYPE_CHECKING, Any, Dict, Iterable, Optional, Sequence, Tuple, Union67from sim_platform.domain.models import ContractError8from sim_platform.agents.tools.protocol.errors import ToolError9from sim_platform.agents.tools.client.base import PlatformTool10from sim_platform.agents.tools.client.collection import TOOL_TYPES11from .conversation import Conversation12from .task import Task1314if TYPE_CHECKING: # Annotation only.15 from sim_platform.agents.tools.client.base import Tool16 from sim_platform.sdk.context import AgentModel17 from .model import ToolCall181920def tool_error(code: str, message: str) -> Dict[str, Any]:21 """A tool result in the platform's error shape, for errors raised before a tool ran."""22 return dict(status='error', error=dict(code=code, message=message))232425class TradingAgent:26 """Run a task using a model and callable Tool objects, retaining this run's history.2728 Construct this once for an experiment, then call run(task) for each scheduled29 task. Tools own their interfaces; the model adapter owns provider formatting.30 The Agent only performs the model -> tools -> model loop. An ordinary text31 reply does not finish a task: a successful completion Tool must end it.3233 ``label`` names the role (for example 'news analyst'); evaluations report model34 calls and tokens per label. ``finish_tools`` names local tools whose call also ends the task, returning that35 tool's result. Use it for a role inside a larger Agent, such as an analyst that ends36 by submitting a report, so the role never needs the platform's finish or wait.37 """3839 def __init__(40 self,41 model: AgentModel,42 tools: Iterable[Tool],43 instructions: str,44 parameters: Optional[Dict[str, Any]] = None,45 finish_tools: Iterable[str] = (),46 label: Optional[str] = None,47 ) -> None:48 self.model = model49 tools = tuple(tools)50 self.tools = {tool.function_name: tool for tool in tools}51 if len(self.tools) != len(tools):52 raise ContractError('agent tools must have distinct names')53 reserved = {name.replace('.', '_') for name in TOOL_TYPES}54 if any(55 tool.function_name in reserved and not isinstance(tool, PlatformTool) for tool in tools56 ):57 raise ContractError('local tools cannot replace platform tool names')58 self.conversation = Conversation(instructions, parameters or {})59 if label is not None and (60 not isinstance(label, str) or not 0 < len(label) <= 64 or not label.isprintable()61 ):62 raise ContractError('label must be printable text of at most 64 characters')63 self.conversation.label = label64 self.finish_tools = frozenset(name.replace('.', '_') for name in finish_tools)65 unknown = self.finish_tools - {66 name for name, tool in self.tools.items() if not isinstance(tool, PlatformTool)67 }68 if unknown:69 raise ContractError('finish_tools must name local tools given to this agent')7071 def _execute(self, call: ToolCall) -> Tuple[Any, bool]:72 """Run one tool call; return its result and whether it ended the task."""73 tool = self.tools.get(call.name)74 if tool is None:75 return tool_error('TOOL_UNAVAILABLE', 'tool is not available to this agent'), False76 try:77 result = tool.invoke(call.arguments())78 except ToolError as error:79 return tool_error(error.code, str(error)), False80 # An uncertain transport error propagates; the Agent never retries a trade.81 if call.name in self.finish_tools:82 return result, True83 return (84 result,85 isinstance(tool, PlatformTool) and tool.ends_work and result.get('status') == 'ok',86 )8788 def _mixed_completion(self, calls: Sequence[ToolCall]) -> bool:89 """Whether a finish/wait tool was requested together with other calls."""90 return len(calls) > 1 and any(91 call.name in self.finish_tools92 or (93 isinstance(self.tools.get(call.name), PlatformTool)94 and self.tools[call.name].ends_work95 )96 for call in calls97 )9899 def run(self, task: Union[str, Task]) -> dict:100 """Perform a task until finish/wait succeeds, returning that completion result.101102 Pass a string for a direct task, or Task to include a scheduler notification.103 Context is retained between calls on this Agent. Each tool result is appended104 before asking the model again; zero trades is a valid completed task.105 """106 task = Task(task) if isinstance(task, str) else task107 if not isinstance(task, Task):108 raise ContractError('agent.run requires task text or a Task')109 self.conversation.start_task(task)110 while True:111 calls = self.model.respond(self.conversation, list(self.tools.values()))112 if not calls:113 self.conversation.continue_work()114 continue115 mixed = self._mixed_completion(calls)116 for call in calls:117 if mixed:118 result = tool_error('INVALID_ARGUMENT', 'finish and wait must be called alone')119 finished = False120 else:121 result, finished = self._execute(call)122 self.conversation.tool_result(call, result)123 if finished:124 return result