User Input Required for Tool Execution

This example demonstrates how to create tools that require user input before execution, allowing for dynamic data collection during agent runs.

Create a Python file

1from typing import List
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.tools.function import UserInputField
8from kern.utils import pprint
9
10
11# You can either specify the user_input_fields leave empty for all fields to be provided by the user
12@tool(requires_user_input=True, user_input_fields=["to_address"])
13def send_email(subject: str, body: str, to_address: str) -> str:
14 """
15 Send an email.
16
17 Args:
18 subject (str): The subject of the email.
19 body (str): The body of the email.
20 to_address (str): The address to send the email to.
21 """
22 return f"Sent email to {to_address} with subject {subject} and body {body}"
23
24
25agent = Agent(
26 model=OpenAIResponses(id="gpt-5.2"),
27 tools=[send_email],
28 markdown=True,
29 db=SqliteDb(db_file="tmp/example.db"),
30)
31
32run_response = agent.run(
33 "Send an email with the subject 'Hello' and the body 'Hello, world!'"
34)
35
36for requirement in run_response.active_requirements:
37 if requirement.needs_user_input:
38 input_schema: List[UserInputField] = requirement.user_input_schema # type: ignore
39
40 for field in input_schema:
41 # Get user input for each field in the schema
42 field_type = field.field_type
43 field_description = field.description
44
45 # Display field information to the user
46 print(f"\nField: {field.name}")
47 print(f"Description: {field_description}")
48 print(f"Type: {field_type}")
49
50 # Get user input
51 if field.value is None:
52 user_value = input(f"Please enter a value for {field.name}: ")
53 else:
54 print(f"Value: {field.value}")
55 user_value = field.value
56
57 # Update the field value
58 field.value = user_value
59
60run_response = agent.continue_run(
61 run_id=run_response.run_id,
62 requirements=run_response.requirements,
63) # or agent.continue_run(run_response=run_response)
64pprint.pprint_run_response(run_response)
65
66# Or for simple debug flow
67# agent.print_response("Send an email with the subject 'Hello' and the body 'Hello, world!'")

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