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 subprocess
2from kern.agent import Agent
3from kern.db.sqlite import SqliteDb
4from kern.models.openai import OpenAIResponses
5from kern.tools.toolkit import Toolkit
6from kern.utils import pprint
7
8
9class 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 )
17
18 def list_dir(self, directory: str):
19 """
20 Lists the contents of a directory.
21
22 Args:
23 directory: The directory to list.
24
25 Returns:
26 A string containing the contents of the directory.
27 """
28 return subprocess.check_output(f"ls {directory}", shell=True).decode("utf-8")
29
30
31tools = ShellTools()
32
33agent = 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)
39
40run_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: ignore
50 # We have to set the result on the tool execution object so that the agent can continue
51 requirement.set_external_execution_result(result)
52
53 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.12
2source .venv/bin/activate
1uv venv --python 3.12
2.venv\Scripts\activate

Install dependencies

1uv pip install -U kern-ai openai

Export 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