External Tool Execution Async
This example demonstrates how to execute tools outside of the agent using external tool execution in an asynchronous environment. This pattern allows you to control tool execution externally while maintaining agent functionality with async operations.
Create a Python file
1import asyncio2import subprocess34from kern.agent import Agent5from kern.db.sqlite import SqliteDb6from kern.models.openai import OpenAIResponses7from kern.tools import tool8from kern.utils import pprint91011# We have to create a tool with the correct name, arguments and docstring for the agent to know what to call.12@tool(external_execution=True)13def execute_shell_command(command: str) -> str:14 """Execute a shell command.1516 Args:17 command (str): The shell command to execute1819 Returns:20 str: The output of the shell command21 """22 if command.startswith("ls"):23 return subprocess.check_output(command, shell=True).decode("utf-8")24 else:25 raise Exception(f"Unsupported command: {command}")262728agent = Agent(29 model=OpenAIResponses(id="gpt-5.2"),30 tools=[execute_shell_command],31 markdown=True,32 db=SqliteDb(session_table="test_session", db_file="tmp/example.db"),33)3435run_response = asyncio.run(agent.arun("What files do I have in my current directory?"))36if run_response.is_paused:37 for requirement in run_response.active_requirements:38 if requirement.needs_external_execution:39 if requirement.tool_execution.tool_name == execute_shell_command.name:40 print(41 f"Executing {requirement.tool_execution.tool_name} with args {requirement.tool_execution.tool_args} externally"42 )43 # We execute the tool ourselves. You can also execute something completely external here.44 result = execute_shell_command.entrypoint(45 **requirement.tool_execution.tool_args46 ) # type: ignore47 # We have to set the result on the tool execution object so that the agent can continue48 requirement.set_external_execution_result(result)4950run_response = asyncio.run(51 agent.acontinue_run(52 run_id=run_response.run_id,53 requirements=run_response.requirements,54 )55)56pprint.pprint_run_response(run_response)575859# Or for simple debug flow60# agent.print_response("What files do I have in my current directory?")Set up your virtual environment
1uv venv --python 3.122source .venv/bin/activate1uv venv --python 3.122.venv\Scripts\activateInstall dependencies
1uv pip install -U kern-ai openaiExport your OpenAI API key
1export OPENAI_API_KEY="your_openai_api_key_here"1$Env:OPENAI_API_KEY="your_openai_api_key_here"Run Agent
1python external_tool_execution_async.py