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 subprocess
2
3from kern.agent import Agent
4from kern.db.sqlite import SqliteDb
5from kern.models.openai import OpenAIResponses
6from kern.tools import tool
7from kern.utils import pprint
8
9
10# 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.
14
15 Args:
16 command (str): The shell command to execute
17
18 Returns:
19 str: The output of the shell command
20 """
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}")
25
26
27agent = 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)
33
34run_response = agent.run("What files do I have in my current directory?")
35
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_args
46 ) # type: ignore
47 # We have to set the result on the tool execution object so that the agent can continue
48 requirement.set_external_execution_result(result)
49
50run_response = agent.continue_run(
51 run_id=run_response.run_id,
52 requirements=run_response.requirements,
53)
54pprint.pprint_run_response(run_response)
55
56# Or for simple debug flow
57# agent.print_response("What files do I have in my current directory?")

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.py