User Input Required Async

This example demonstrates how to use the requires_user_input parameter with asynchronous operations. It shows how to collect specific user input fields in an async environment.

Create a Python file

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