Skip to content

SimpleAgent

SimpleAgent

A simple agent with env, tools, mcps, and context manager, wrapped on openai-agents.

Source code in utu/agents/simple_agent.py
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
class SimpleAgent:
    """A simple agent with env, tools, mcps, and context manager, wrapped on openai-agents."""

    def __init__(
        self,
        *,
        config: AgentConfig | str | None = None,  # use config to pass agent configs
        name: str | None = None,
        instructions: str | Callable | None = None,
        model: str | Model | None = None,
        model_settings: ModelSettings | None = None,
        tools: list[Tool] = None,  # config tools
        toolkits: list[str] | None = None,  # load tools from toolkit configs
        output_type: type[Any] | AgentOutputSchemaBase | None = None,
        tool_use_behavior: Literal["run_llm_again", "stop_on_first_tool"] | StopAtTools = "run_llm_again",
    ):
        assert not (tools and toolkits), "You can't pass both tools and toolkits."
        self.config = self._get_config(config)
        if name:
            self.config.agent.name = name
        if instructions:
            self.config.agent.instructions = instructions
        self.model = self._get_model(self.config, model)
        self.model_settings = self._get_model_settings(self.config, model_settings)
        self.tools: list[Tool] = tools or []
        self.toolkits: list[str] = toolkits or []
        self.output_type: type[Any] | AgentOutputSchemaBase | None = output_type
        self.tool_use_behavior: Literal["run_llm_again", "stop_on_first_tool"] | StopAtTools = tool_use_behavior
        self.context_manager: BaseContextManager = None
        self.env: BaseEnv = None
        self.workspace_dir: str = ""
        self.current_agent: Agent[TContext] = None  # move to task recorder?
        self.input_items: list[TResponseInputItem] = []
        self.run_hooks: RunHooks = get_run_hooks(self.config)

        self._mcp_servers: list[MCPServer] = []
        self._toolkits: dict[str, AsyncBaseToolkit] = {}
        self._mcps_exit_stack = AsyncExitStack()
        self._initialized = False

    def _get_config(self, config: AgentConfig | str | None) -> AgentConfig:
        if isinstance(config, AgentConfig):
            return config
        return ConfigLoader.load_agent_config(config or "simple/base")

    def _get_model(self, config: AgentConfig, model: str | Model | None = None) -> Model:
        if isinstance(model, Model):
            return model
        model_provider_config = config.model.model_provider.model_dump()
        if isinstance(model, str):
            model_provider_config["model"] = model
        return AgentsUtils.get_agents_model(**model_provider_config)

    def _get_model_settings(self, config: AgentConfig, model_settings: ModelSettings | None = None) -> ModelSettings:
        if isinstance(model_settings, ModelSettings):
            return model_settings
        return config.model.model_settings

    async def __aenter__(self) -> "SimpleAgent":
        await self.build()
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.cleanup()

    async def build(self, trace_id: str = None):
        """Build the agent"""
        if self._initialized:
            logger.info("Agent already initialized! Skipping build.")
            return
        self.env = await get_env(self.config, trace_id or AgentsUtils.gen_trace_id())  # Pass trace_id
        await self.env.build()
        self.current_agent = Agent(
            name=self.config.agent.name,
            instructions=self.config.agent.instructions,
            model=self.model,
            model_settings=self.model_settings,
            tools=await self.get_tools(),
            output_type=self.output_type,
            tool_use_behavior=self.tool_use_behavior,
            mcp_servers=self._mcp_servers,
        )
        self.context_manager = build_context_manager(self.config)
        self._initialized = True

    async def cleanup(self):
        """Cleanup"""
        logger.info("Cleaning up MCP servers...")
        await self._mcps_exit_stack.aclose()
        self._mcp_servers = []
        logger.info("Cleaning up tools...")
        self._toolkits = {}
        logger.info("Cleaning up env...")
        await self.env.cleanup()
        self._initialized = False

    def setup_workspace(self, workspace_dir: str | pathlib.Path):
        """Setup workspace for toolkits that need it"""
        assert pathlib.Path(workspace_dir).exists()
        self.workspace_dir = str(workspace_dir)
        self._setup_workspace_for_toolkits()

    def _setup_workspace_for_toolkits(self):
        for toolkit in self._toolkits.values():
            if hasattr(toolkit, "setup_workspace"):
                toolkit.setup_workspace(self.workspace_dir)

    async def get_tools(self) -> list[Tool]:
        if self.tools:
            return self.tools

        if self.toolkits:
            await self._load_toolkits_config()
        else:
            tools_list: list[Tool] = []
            tools_list += await self.env.get_tools()  # add env tools
            # TODO: handle duplicate tool names
            for _, toolkit_config in self.config.toolkits.items():
                toolkit = await self._load_toolkit(toolkit_config)
                if toolkit_config.mode in ["customized", "builtin"]:
                    tools_list.extend(toolkit.get_tools_in_agents())
            tool_names = [tool.name for tool in tools_list]
            logger.info(f"Loaded {len(tool_names)} tools: {tool_names}")
            self.tools = tools_list
        # setup workspace if needed
        if self.workspace_dir:
            self._setup_workspace_for_toolkits()
        return self.tools

    async def _load_toolkits_config(self):
        assert isinstance(self.toolkits, list) and all(isinstance(tool, str) for tool in self.toolkits)
        parsed_tools = []
        for tool_name in self.toolkits:
            config = ConfigLoader.load_toolkit_config(tool_name)
            toolkit = await self._load_toolkit(config)
            if config.mode in ["customized", "builtin"]:
                parsed_tools.extend(toolkit.get_tools_in_agents())
        self.tools = parsed_tools

    async def _load_toolkit(self, toolkit_config: ToolkitConfig) -> AsyncBaseToolkit | MCPServer:
        if toolkit_config.mode == "builtin":
            return await self._load_builtin_toolkit(toolkit_config)
        elif toolkit_config.mode == "customized":
            return await self._load_customized_toolkit(toolkit_config)
        elif toolkit_config.mode == "mcp":
            return await self._load_mcp_server(toolkit_config)
        else:
            raise ValueError(f"Unknown toolkit mode: {toolkit_config.mode}")

    async def _load_builtin_toolkit(self, toolkit_config: ToolkitConfig) -> AsyncBaseToolkit:
        logger.info(f"Loading builtin toolkit `{toolkit_config.name}` with config {toolkit_config}")
        toolkit = TOOLKIT_MAP[toolkit_config.name](toolkit_config)
        self._toolkits[toolkit_config.name] = toolkit
        return toolkit

    async def _load_customized_toolkit(self, toolkit_config: ToolkitConfig) -> AsyncBaseToolkit:
        logger.info(f"Loading customized toolkit `{toolkit_config.name}` with config {toolkit_config}")
        assert toolkit_config.customized_filepath is not None and toolkit_config.customized_classname is not None
        toolkit_class = load_class_from_file(toolkit_config.customized_filepath, toolkit_config.customized_classname)
        toolkit = toolkit_class(toolkit_config)
        self._toolkits[toolkit_config.name] = toolkit
        return toolkit

    async def _load_mcp_server(self, toolkit_config: ToolkitConfig) -> MCPServer:
        logger.info(f"Loading MCP server `{toolkit_config.name}` with params {toolkit_config.config}")
        mcp_server = get_mcp_server(toolkit_config)
        server = await self._mcps_exit_stack.enter_async_context(mcp_server)
        self._mcp_servers.append(server)
        return server

    def _get_run_config(self) -> RunConfig:
        run_config = RunConfig(
            model=self.current_agent.model,
            model_settings=self.config.model.model_settings,
            workflow_name=self.config.agent.name,
        )
        return run_config

    def _get_context(self) -> dict:
        return {
            "context_manager": self.context_manager,
            "env": self.env,
            "agent_config": self.config,
        }

    def _prepare_run_kwargs(self, input: str | list[TResponseInputItem]) -> dict:
        return {
            "starting_agent": self.current_agent,
            "input": input,
            "context": self._get_context(),
            "max_turns": self.config.max_turns,
            "hooks": self.run_hooks,
            "run_config": self._get_run_config(),
        }

    # wrap `Runner` apis in @openai-agents
    async def run(
        self, input: str | list[TResponseInputItem], trace_id: str = None, save: bool = False
    ) -> TaskRecorder:
        """Entrypoint for running the agent

        Args:
            trace_id: str to identify the run
            save: whether to update massage history (use `input_items`)
        """
        recorder = self.run_streamed(input, trace_id)
        async for _ in recorder.stream_events():
            pass
        return recorder

    def run_streamed(
        self, input: str | list[TResponseInputItem], trace_id: str = None, save: bool = False, log_to_db: bool = True
    ) -> TaskRecorder:
        """Entrypoint for running the agent streamly

        Args:
            trace_id: str to identify the run
        """
        trace_id = trace_id or AgentsUtils.gen_trace_id()
        logger.info(f"> trace_id: {trace_id}")

        if isinstance(input, list):
            assert isinstance(input[-1], dict) and "content" in input[-1], "invalid input format!"
            task = input[-1]["content"]
        else:
            assert isinstance(input, str), "input should be str or list of TResponseInputItem!"
            task = input
        recorder = TaskRecorder(task=task, input=input, trace_id=trace_id)
        recorder._run_impl_task = asyncio.create_task(self._start_streaming(recorder, save, log_to_db))
        return recorder

    async def _start_streaming(self, recorder: TaskRecorder, save: bool = False, log_to_db: bool = True):
        if not self._initialized:
            await self.build(recorder.trace_id)
        try:
            input = recorder.input
            if isinstance(input, str):  # only add history when input is str?
                input = self.input_items + [{"content": input, "role": "user"}]
            run_kwargs = self._prepare_run_kwargs(input)
            if AgentsUtils.get_current_trace():
                run_streamed_result = Runner.run_streamed(**run_kwargs)
            else:
                with trace(workflow_name="simple_agent", trace_id=recorder.trace_id):
                    run_streamed_result = Runner.run_streamed(**run_kwargs)
            async for event in run_streamed_result.stream_events():
                recorder._event_queue.put_nowait(event)
            # save final output and trajectory
            recorder.add_run_result(run_streamed_result)
            if save:
                self.input_items = run_streamed_result.to_input_list()
                # NOTE: acturally, there are only one agent in SimpleAgent
                self.current_agent = run_streamed_result.last_agent
            # log to db
            if log_to_db:
                DBService.add(TrajectoryModel.from_task_recorder(recorder))
        except Exception as e:
            logger.error(f"Error processing task: {str(e)}")
            recorder._event_queue.put_nowait(QueueCompleteSentinel())
            recorder._is_complete = True
            raise e
        finally:
            recorder._event_queue.put_nowait(QueueCompleteSentinel())
            recorder._is_complete = True

    # util apis
    async def chat(self, input: str) -> TaskRecorder:
        # TODO: set "session-level" tracing for multi-turn chat
        recorder = await self.run(input, save=True)
        run_result = recorder.get_run_result()
        AgentsUtils.print_new_items(run_result.new_items)
        return run_result

    async def chat_streamed(self, input: str) -> TaskRecorder:
        recorder = self.run_streamed(input, save=True)
        await AgentsUtils.print_stream_events(recorder.stream_events())
        return recorder

    def set_instructions(self, instructions: str):
        logger.warning("WARNING: reset instructions is dangerous!")
        self.current_agent.instructions = instructions

    def clear_input_items(self):
        # reset chat history
        self.input_items = []

build async

build(trace_id: str = None)

Build the agent

Source code in utu/agents/simple_agent.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
async def build(self, trace_id: str = None):
    """Build the agent"""
    if self._initialized:
        logger.info("Agent already initialized! Skipping build.")
        return
    self.env = await get_env(self.config, trace_id or AgentsUtils.gen_trace_id())  # Pass trace_id
    await self.env.build()
    self.current_agent = Agent(
        name=self.config.agent.name,
        instructions=self.config.agent.instructions,
        model=self.model,
        model_settings=self.model_settings,
        tools=await self.get_tools(),
        output_type=self.output_type,
        tool_use_behavior=self.tool_use_behavior,
        mcp_servers=self._mcp_servers,
    )
    self.context_manager = build_context_manager(self.config)
    self._initialized = True

cleanup async

cleanup()

Cleanup

Source code in utu/agents/simple_agent.py
121
122
123
124
125
126
127
128
129
130
async def cleanup(self):
    """Cleanup"""
    logger.info("Cleaning up MCP servers...")
    await self._mcps_exit_stack.aclose()
    self._mcp_servers = []
    logger.info("Cleaning up tools...")
    self._toolkits = {}
    logger.info("Cleaning up env...")
    await self.env.cleanup()
    self._initialized = False

setup_workspace

setup_workspace(workspace_dir: str | Path)

Setup workspace for toolkits that need it

Source code in utu/agents/simple_agent.py
132
133
134
135
136
def setup_workspace(self, workspace_dir: str | pathlib.Path):
    """Setup workspace for toolkits that need it"""
    assert pathlib.Path(workspace_dir).exists()
    self.workspace_dir = str(workspace_dir)
    self._setup_workspace_for_toolkits()

run async

run(
    input: str | list[TResponseInputItem],
    trace_id: str = None,
    save: bool = False,
) -> TaskRecorder

Entrypoint for running the agent

Parameters:

Name Type Description Default
trace_id str

str to identify the run

None
save bool

whether to update massage history (use input_items)

False
Source code in utu/agents/simple_agent.py
232
233
234
235
236
237
238
239
240
241
242
243
244
async def run(
    self, input: str | list[TResponseInputItem], trace_id: str = None, save: bool = False
) -> TaskRecorder:
    """Entrypoint for running the agent

    Args:
        trace_id: str to identify the run
        save: whether to update massage history (use `input_items`)
    """
    recorder = self.run_streamed(input, trace_id)
    async for _ in recorder.stream_events():
        pass
    return recorder

run_streamed

run_streamed(
    input: str | list[TResponseInputItem],
    trace_id: str = None,
    save: bool = False,
    log_to_db: bool = True,
) -> TaskRecorder

Entrypoint for running the agent streamly

Parameters:

Name Type Description Default
trace_id str

str to identify the run

None
Source code in utu/agents/simple_agent.py
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
def run_streamed(
    self, input: str | list[TResponseInputItem], trace_id: str = None, save: bool = False, log_to_db: bool = True
) -> TaskRecorder:
    """Entrypoint for running the agent streamly

    Args:
        trace_id: str to identify the run
    """
    trace_id = trace_id or AgentsUtils.gen_trace_id()
    logger.info(f"> trace_id: {trace_id}")

    if isinstance(input, list):
        assert isinstance(input[-1], dict) and "content" in input[-1], "invalid input format!"
        task = input[-1]["content"]
    else:
        assert isinstance(input, str), "input should be str or list of TResponseInputItem!"
        task = input
    recorder = TaskRecorder(task=task, input=input, trace_id=trace_id)
    recorder._run_impl_task = asyncio.create_task(self._start_streaming(recorder, save, log_to_db))
    return recorder