External Tool Execution
This example demonstrates how to execute tools outside of the agent using external tool execution. This pattern allows you to control tool execution externally while maintaining agent functionality.
Create a Python file
1import subprocess23from kern.agent import Agent4from kern.db.sqlite import SqliteDb5from kern.models.openai import OpenAIResponses6from kern.tools import tool7from kern.utils import pprint8910# We have to create a tool with the correct name, arguments and docstring for the agent to know what to call.11@tool(external_execution=True)12def execute_shell_command(command: str) -> str:13 """Execute a shell command.1415 Args:16 command (str): The shell command to execute1718 Returns:19 str: The output of the shell command20 """21 if command.startswith("ls"):22 return subprocess.check_output(command, shell=True).decode("utf-8")23 else:24 raise Exception(f"Unsupported command: {command}")252627agent = Agent(28 model=OpenAIResponses(id="gpt-5.2"),29 tools=[execute_shell_command],30 markdown=True,31 db=SqliteDb(session_table="test_session", db_file="tmp/example.db"),32)3334run_response = agent.run("What files do I have in my current directory?")3536if 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 = agent.continue_run(51 run_id=run_response.run_id,52 requirements=run_response.requirements,53)54pprint.pprint_run_response(run_response)5556# Or for simple debug flow57# 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.py