0
# Input Widgets
1
2
Interactive input components for creating dynamic chat settings and user preference panels. These widgets enable users to configure application behavior through sliders, switches, dropdowns, text inputs, and custom controls.
3
4
## Capabilities
5
6
### Widget Base Classes
7
8
Foundation classes for creating interactive settings panels with validation and dynamic updates.
9
10
```python { .api }
11
import chainlit as cl
12
from chainlit.input_widget import Slider, Switch, Select, TextInput, NumberInput, Tags
13
14
class InputWidget:
15
"""
16
Base class for all input widgets used in chat settings panels.
17
18
Args:
19
id: str - Unique widget identifier for accessing values
20
label: str - Display label shown to users
21
tooltip: Optional[str] - Hover tooltip text
22
description: Optional[str] - Help text displayed below widget
23
24
Returns:
25
InputWidget base instance
26
"""
27
def __init__(
28
self,
29
id: str,
30
label: str,
31
tooltip: Optional[str] = None,
32
description: Optional[str] = None
33
): ...
34
35
class ChatSettings:
36
"""
37
Container for input widgets that creates a settings panel in the UI.
38
39
Args:
40
widgets: List[InputWidget] - List of widgets to display in panel
41
42
Returns:
43
ChatSettings instance for managing user preferences
44
"""
45
def __init__(self, widgets: List[InputWidget]): ...
46
```
47
48
### Boolean Controls
49
50
Toggle switches for binary settings and feature toggles.
51
52
```python { .api }
53
class Switch:
54
"""
55
Boolean toggle switch for binary settings and feature flags.
56
57
Args:
58
id: str - Widget identifier for accessing the boolean value
59
label: str - Display label for the switch
60
initial: bool - Default value (default: False)
61
tooltip: Optional[str] - Hover tooltip text
62
description: Optional[str] - Help text explaining the setting
63
64
Returns:
65
Switch widget instance
66
"""
67
def __init__(
68
self,
69
id: str,
70
label: str,
71
initial: bool = False,
72
tooltip: Optional[str] = None,
73
description: Optional[str] = None
74
): ...
75
```
76
77
### Numeric Controls
78
79
Sliders and number inputs for numeric configuration values.
80
81
```python { .api }
82
class Slider:
83
"""
84
Numeric slider input with range constraints and step control.
85
86
Args:
87
id: str - Widget identifier for accessing the numeric value
88
label: str - Display label for the slider
89
initial: float - Default value (default: 0)
90
min: float - Minimum allowed value (default: 0)
91
max: float - Maximum allowed value (default: 10)
92
step: float - Step size for value increments (default: 1)
93
tooltip: Optional[str] - Hover tooltip text
94
description: Optional[str] - Help text explaining the setting
95
96
Returns:
97
Slider widget instance
98
"""
99
def __init__(
100
self,
101
id: str,
102
label: str,
103
initial: float = 0,
104
min: float = 0,
105
max: float = 10,
106
step: float = 1,
107
tooltip: Optional[str] = None,
108
description: Optional[str] = None
109
): ...
110
111
class NumberInput:
112
"""
113
Numeric input field with keyboard entry support.
114
115
Args:
116
id: str - Widget identifier for accessing the numeric value
117
label: str - Display label for the input field
118
initial: Optional[float] - Default number value
119
placeholder: Optional[str] - Placeholder text when empty
120
tooltip: Optional[str] - Hover tooltip text
121
description: Optional[str] - Help text explaining the setting
122
123
Returns:
124
NumberInput widget instance
125
"""
126
def __init__(
127
self,
128
id: str,
129
label: str,
130
initial: Optional[float] = None,
131
placeholder: Optional[str] = None,
132
tooltip: Optional[str] = None,
133
description: Optional[str] = None
134
): ...
135
```
136
137
### Selection Controls
138
139
Dropdowns and selection widgets for choosing from predefined options.
140
141
```python { .api }
142
class Select:
143
"""
144
Dropdown selection widget with predefined options.
145
146
Args:
147
id: str - Widget identifier for accessing selected value
148
label: str - Display label for the dropdown
149
values: Optional[List[str]] - Simple string options for selection
150
items: Optional[Dict[str, str]] - Label-value pairs (label -> value)
151
initial_index: Optional[int] - Default selection by index position
152
initial_value: Optional[str] - Default selection by value
153
tooltip: Optional[str] - Hover tooltip text
154
description: Optional[str] - Help text explaining the options
155
156
Returns:
157
Select widget instance
158
159
Note:
160
Use either 'values' for simple strings or 'items' for label-value pairs
161
"""
162
def __init__(
163
self,
164
id: str,
165
label: str,
166
values: Optional[List[str]] = None,
167
items: Optional[Dict[str, str]] = None,
168
initial_index: Optional[int] = None,
169
initial_value: Optional[str] = None,
170
tooltip: Optional[str] = None,
171
description: Optional[str] = None
172
): ...
173
```
174
175
### Text Input Controls
176
177
Text fields for string input with multiline support and validation.
178
179
```python { .api }
180
class TextInput:
181
"""
182
Text input field with single-line and multi-line support.
183
184
Args:
185
id: str - Widget identifier for accessing text value
186
label: str - Display label for the input field
187
initial: Optional[str] - Default text content
188
placeholder: Optional[str] - Placeholder text when empty
189
multiline: bool - Enable multi-line input (default: False)
190
tooltip: Optional[str] - Hover tooltip text
191
description: Optional[str] - Help text explaining the input
192
193
Returns:
194
TextInput widget instance
195
"""
196
def __init__(
197
self,
198
id: str,
199
label: str,
200
initial: Optional[str] = None,
201
placeholder: Optional[str] = None,
202
multiline: bool = False,
203
tooltip: Optional[str] = None,
204
description: Optional[str] = None
205
): ...
206
```
207
208
### Tag and Array Controls
209
210
Tag input widgets for managing lists of values and categorical data.
211
212
```python { .api }
213
class Tags:
214
"""
215
Tag input widget for managing arrays of string values.
216
217
Args:
218
id: str - Widget identifier for accessing tag array
219
label: str - Display label for the tag input
220
initial: List[str] - Default tag values (default: empty list)
221
values: Optional[List[str]] - Predefined tag options for autocomplete
222
tooltip: Optional[str] - Hover tooltip text
223
description: Optional[str] - Help text explaining tag usage
224
225
Returns:
226
Tags widget instance
227
"""
228
def __init__(
229
self,
230
id: str,
231
label: str,
232
initial: List[str] = [],
233
values: Optional[List[str]] = None,
234
tooltip: Optional[str] = None,
235
description: Optional[str] = None
236
): ...
237
```
238
239
## Usage Examples
240
241
### Basic Settings Panel
242
243
Create a simple settings panel with various input types:
244
245
```python
246
import chainlit as cl
247
from chainlit.input_widget import Slider, Switch, Select, TextInput
248
249
@cl.on_chat_start
250
async def setup_settings():
251
"""Create a settings panel for user preferences"""
252
settings = cl.ChatSettings([
253
# AI Model Configuration
254
Select(
255
id="model",
256
label="AI Model",
257
values=["gpt-3.5-turbo", "gpt-4", "claude-3-sonnet"],
258
initial_value="gpt-3.5-turbo",
259
tooltip="Choose the AI model for responses"
260
),
261
262
# Response Parameters
263
Slider(
264
id="temperature",
265
label="Response Creativity",
266
initial=0.7,
267
min=0.0,
268
max=2.0,
269
step=0.1,
270
description="Higher values make responses more creative"
271
),
272
273
Slider(
274
id="max_tokens",
275
label="Maximum Response Length",
276
initial=150,
277
min=50,
278
max=500,
279
step=25,
280
tooltip="Maximum number of tokens in responses"
281
),
282
283
# Feature Toggles
284
Switch(
285
id="stream_response",
286
label="Stream Responses",
287
initial=True,
288
description="Show responses as they're generated"
289
),
290
291
Switch(
292
id="show_thinking",
293
label="Show AI Thinking",
294
initial=False,
295
description="Display AI reasoning steps"
296
),
297
298
# User Preferences
299
TextInput(
300
id="system_prompt",
301
label="Custom System Prompt",
302
multiline=True,
303
placeholder="Enter custom instructions for the AI...",
304
description="Custom instructions to guide AI behavior"
305
)
306
])
307
308
await settings.send()
309
310
@cl.on_settings_update
311
async def handle_settings_update(settings: Dict[str, Any]):
312
"""Handle changes to chat settings"""
313
# Access individual settings
314
model = settings.get("model", "gpt-3.5-turbo")
315
temperature = settings.get("temperature", 0.7)
316
max_tokens = settings.get("max_tokens", 150)
317
stream_response = settings.get("stream_response", True)
318
show_thinking = settings.get("show_thinking", False)
319
system_prompt = settings.get("system_prompt", "")
320
321
# Store in session for use in message handling
322
cl.user_session.set("ai_settings", {
323
"model": model,
324
"temperature": temperature,
325
"max_tokens": max_tokens,
326
"stream_response": stream_response,
327
"show_thinking": show_thinking,
328
"system_prompt": system_prompt
329
})
330
331
await cl.Message(
332
f"Settings updated! Using {model} with temperature {temperature}"
333
).send()
334
```
335
336
### Advanced Configuration Panel
337
338
Create a comprehensive settings panel for a data analysis application:
339
340
```python
341
import chainlit as cl
342
from chainlit.input_widget import Slider, Switch, Select, TextInput, NumberInput, Tags
343
344
@cl.on_chat_start
345
async def setup_advanced_settings():
346
"""Create comprehensive settings for data analysis"""
347
settings = cl.ChatSettings([
348
# Data Processing Settings
349
Select(
350
id="data_source",
351
label="Data Source",
352
items={
353
"CSV Upload": "csv",
354
"Database Connection": "database",
355
"API Endpoint": "api",
356
"Sample Dataset": "sample"
357
},
358
initial_value="csv",
359
description="Choose your data source type"
360
),
361
362
# Analysis Parameters
363
NumberInput(
364
id="sample_size",
365
label="Sample Size",
366
initial=1000,
367
placeholder="Enter sample size...",
368
description="Number of rows to analyze (0 = all rows)"
369
),
370
371
Slider(
372
id="confidence_level",
373
label="Confidence Level",
374
initial=0.95,
375
min=0.80,
376
max=0.99,
377
step=0.01,
378
tooltip="Statistical confidence level for analysis"
379
),
380
381
# Chart Configuration
382
Select(
383
id="chart_style",
384
label="Chart Style",
385
values=["seaborn", "matplotlib", "plotly", "bokeh"],
386
initial_index=0,
387
description="Preferred charting library"
388
),
389
390
Tags(
391
id="analysis_types",
392
label="Analysis Types",
393
initial=["descriptive", "correlation"],
394
values=[
395
"descriptive", "correlation", "regression",
396
"clustering", "time_series", "anomaly_detection"
397
],
398
description="Select types of analysis to perform"
399
),
400
401
# Processing Options
402
Switch(
403
id="auto_clean",
404
label="Automatic Data Cleaning",
405
initial=True,
406
description="Automatically handle missing values and outliers"
407
),
408
409
Switch(
410
id="generate_report",
411
label="Generate PDF Report",
412
initial=False,
413
tooltip="Create downloadable analysis report"
414
),
415
416
# Output Preferences
417
TextInput(
418
id="report_title",
419
label="Report Title",
420
initial="Data Analysis Report",
421
placeholder="Enter report title...",
422
description="Title for generated reports"
423
),
424
425
Tags(
426
id="export_formats",
427
label="Export Formats",
428
initial=["png"],
429
values=["png", "pdf", "svg", "html", "json"],
430
description="Chart and report export formats"
431
)
432
])
433
434
await settings.send()
435
436
@cl.on_settings_update
437
async def handle_analysis_settings(settings: Dict[str, Any]):
438
"""Process analysis settings updates"""
439
# Extract and validate settings
440
data_source = settings.get("data_source", "csv")
441
sample_size = settings.get("sample_size", 1000)
442
confidence_level = settings.get("confidence_level", 0.95)
443
chart_style = settings.get("chart_style", "seaborn")
444
analysis_types = settings.get("analysis_types", ["descriptive"])
445
auto_clean = settings.get("auto_clean", True)
446
generate_report = settings.get("generate_report", False)
447
report_title = settings.get("report_title", "Data Analysis Report")
448
export_formats = settings.get("export_formats", ["png"])
449
450
# Store comprehensive settings
451
cl.user_session.set("analysis_config", {
452
"data_source": data_source,
453
"sample_size": max(0, int(sample_size)) if sample_size else 0,
454
"confidence_level": confidence_level,
455
"chart_style": chart_style,
456
"analysis_types": analysis_types,
457
"auto_clean": auto_clean,
458
"generate_report": generate_report,
459
"report_title": report_title,
460
"export_formats": export_formats
461
})
462
463
# Provide feedback on configuration
464
analysis_summary = f"""
465
**Analysis Configuration Updated:**
466
- Data Source: {data_source}
467
- Sample Size: {'All rows' if sample_size == 0 else f'{sample_size:,} rows'}
468
- Analysis Types: {', '.join(analysis_types)}
469
- Chart Style: {chart_style}
470
- Auto-clean Data: {'Yes' if auto_clean else 'No'}
471
"""
472
473
await cl.Message(analysis_summary).send()
474
```
475
476
### Dynamic Settings with Conditional Logic
477
478
Create settings that change based on user selections:
479
480
```python
481
import chainlit as cl
482
from chainlit.input_widget import Slider, Switch, Select, TextInput
483
484
@cl.on_settings_update
485
async def dynamic_settings_handler(settings: Dict[str, Any]):
486
"""Handle settings with dynamic updates"""
487
mode = settings.get("mode", "basic")
488
489
# Create different settings based on selected mode
490
if mode == "basic":
491
new_settings = cl.ChatSettings([
492
Select(
493
id="mode",
494
label="Mode",
495
values=["basic", "advanced", "expert"],
496
initial_value="basic"
497
),
498
Slider(
499
id="temperature",
500
label="Creativity",
501
initial=0.7,
502
min=0.0,
503
max=1.0,
504
step=0.1
505
)
506
])
507
508
elif mode == "advanced":
509
new_settings = cl.ChatSettings([
510
Select(
511
id="mode",
512
label="Mode",
513
values=["basic", "advanced", "expert"],
514
initial_value="advanced"
515
),
516
Slider(
517
id="temperature",
518
label="Temperature",
519
initial=0.7,
520
min=0.0,
521
max=2.0,
522
step=0.1
523
),
524
Slider(
525
id="top_p",
526
label="Top P",
527
initial=0.9,
528
min=0.0,
529
max=1.0,
530
step=0.05
531
),
532
Switch(
533
id="enable_plugins",
534
label="Enable Plugins",
535
initial=True
536
)
537
])
538
539
else: # expert mode
540
new_settings = cl.ChatSettings([
541
Select(
542
id="mode",
543
label="Mode",
544
values=["basic", "advanced", "expert"],
545
initial_value="expert"
546
),
547
# All advanced settings plus expert options
548
Slider(id="temperature", label="Temperature", initial=0.7, min=0.0, max=2.0, step=0.01),
549
Slider(id="top_p", label="Top P", initial=0.9, min=0.0, max=1.0, step=0.01),
550
Slider(id="top_k", label="Top K", initial=50, min=1, max=100, step=1),
551
Slider(id="frequency_penalty", label="Frequency Penalty", initial=0.0, min=-2.0, max=2.0, step=0.1),
552
Slider(id="presence_penalty", label="Presence Penalty", initial=0.0, min=-2.0, max=2.0, step=0.1),
553
Switch(id="enable_plugins", label="Enable Plugins", initial=True),
554
Switch(id="debug_mode", label="Debug Mode", initial=False),
555
TextInput(id="custom_stop_sequences", label="Stop Sequences", placeholder="Enter comma-separated stop sequences...")
556
])
557
558
await new_settings.send()
559
560
# Store current settings
561
cl.user_session.set("current_settings", settings)
562
```
563
564
### Settings Integration with Message Processing
565
566
Use settings values in message handling:
567
568
```python
569
import chainlit as cl
570
571
@cl.on_message
572
async def process_with_settings(message: cl.Message):
573
"""Process messages using current settings"""
574
# Get current settings from session
575
ai_settings = cl.user_session.get("ai_settings", {})
576
analysis_config = cl.user_session.get("analysis_config", {})
577
578
# Use settings in processing
579
model = ai_settings.get("model", "gpt-3.5-turbo")
580
temperature = ai_settings.get("temperature", 0.7)
581
stream_response = ai_settings.get("stream_response", True)
582
show_thinking = ai_settings.get("show_thinking", False)
583
584
# Show thinking process if enabled
585
if show_thinking:
586
async with cl.Step(name="AI Thinking", type="llm") as thinking_step:
587
thinking_step.input = f"Processing message with {model} (temp: {temperature})"
588
# Simulate thinking process
589
await cl.sleep(1)
590
thinking_step.output = "Analyzing user request and formulating response..."
591
592
# Process message with configured settings
593
response = await generate_response(
594
message.content,
595
model=model,
596
temperature=temperature,
597
stream=stream_response
598
)
599
600
if stream_response:
601
# Stream the response token by token
602
msg = cl.Message("")
603
await msg.send()
604
605
for token in response:
606
await msg.stream_token(token)
607
else:
608
# Send complete response
609
await cl.Message(response).send()
610
```
611
612
## Core Types
613
614
```python { .api }
615
from typing import List, Dict, Any, Optional, Union
616
617
# Widget type definitions
618
InputWidgetType = Union[Slider, Switch, Select, TextInput, NumberInput, Tags]
619
620
# Settings update callback type
621
SettingsUpdateCallback = Callable[[Dict[str, Any]], Any]
622
623
# Widget value types
624
WidgetValue = Union[str, int, float, bool, List[str]]
625
SettingsDict = Dict[str, WidgetValue]
626
```