User Input Required

Human-in-the-Loop: Allowing users to provide input externally.

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

Run the Example

1# Clone and setup repo
2git clone https://github.com/kern-ai/kern.git
3cd kern/cookbook/02_agents/10_human_in_the_loop
4
5# Create and activate virtual environment
6./scripts/demo_setup.sh
7source .venvs/demo/bin/activate
8
9python user_input_required.py