User Input Required
Human-in-the-Loop: Allowing users to provide input externally.
1"""2User Input Required3=============================45Human-in-the-Loop: Allowing users to provide input externally.6"""78from typing import List910from kern.agent import Agent11from kern.db.sqlite import SqliteDb12from kern.models.openai import OpenAIResponses13from kern.tools import tool14from kern.tools.function import UserInputField15from kern.utils import pprint161718# You can either specify the user_input_fields leave empty for all fields to be provided by the user19@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.2324 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}"303132# ---------------------------------------------------------------------------33# Create Agent34# ---------------------------------------------------------------------------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)4142# ---------------------------------------------------------------------------43# Run Agent44# ---------------------------------------------------------------------------45if __name__ == "__main__":46 run_response = agent.run(47 "Send an email with the subject 'Hello' and the body 'Hello, world!'"48 )4950 for requirement in run_response.active_requirements:51 if requirement.needs_user_input:52 input_schema: List[UserInputField] = requirement.user_input_schema # type: ignore5354 for field in input_schema:55 # Get user input for each field in the schema56 field_type = field.field_type57 field_description = field.description5859 # Display field information to the user60 print(f"\nField: {field.name}")61 print(f"Description: {field_description}")62 print(f"Type: {field_type}")6364 # Get user input65 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.value7071 # Update the field value72 field.value = user_value7374 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)7980 # Or for simple debug flow81 # agent.print_response("Send an email with the subject 'Hello' and the body 'Hello, world!'")Run the Example
1# Clone and setup repo2git clone https://github.com/kern-ai/kern.git3cd kern/cookbook/02_agents/10_human_in_the_loop45# Create and activate virtual environment6./scripts/demo_setup.sh7source .venvs/demo/bin/activate89python user_input_required.py