External Tool Execution Toolkit
This example demonstrates how to execute toolkit-based tools outside of the agent using external tool execution. It shows how to create a custom toolkit with tools that require external execution.
Create a Python file
1import subprocess2from kern.agent import Agent3from kern.db.sqlite import SqliteDb4from kern.models.openai import OpenAIResponses5from kern.tools.toolkit import Toolkit6from kern.utils import pprint789class ShellTools(Toolkit):10 def __init__(self, *args, **kwargs):11 super().__init__(12 tools=[self.list_dir],13 external_execution_required_tools=["list_dir"],14 *args,15 **kwargs,16 )1718 def list_dir(self, directory: str):19 """20 Lists the contents of a directory.2122 Args:23 directory: The directory to list.2425 Returns:26 A string containing the contents of the directory.27 """28 return subprocess.check_output(f"ls {directory}", shell=True).decode("utf-8")293031tools = ShellTools()3233agent = Agent(34 model=OpenAIResponses(id="gpt-5.2"),35 tools=[tools],36 markdown=True,37 db=SqliteDb(session_table="test_session", db_file="tmp/example.db"),38)3940run_response = agent.run("What files do I have in my current directory?")41if run_response.is_paused:42 for requirement in run_response.active_requirements:43 if requirement.needs_external_execution:44 if requirement.tool_execution.tool_name == "list_dir":45 print(46 f"Executing {requirement.tool_execution.tool_name} with args {requirement.tool_execution.tool_args} externally"47 )48 # We execute the tool ourselves. You can also execute something completely external here.49 result = tools.list_dir(**requirement.tool_execution.tool_args) # type: ignore50 # We have to set the result on the tool execution object so that the agent can continue51 requirement.set_external_execution_result(result)5253 run_response = agent.continue_run(54 run_id=run_response.run_id,55 requirements=run_response.requirements,56 )57 pprint.pprint_run_response(run_response)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_toolkit.py