or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced.mdauthentication.mdcallbacks.mdindex.mdinput-widgets.mdintegrations.mdmessaging.mdui-elements.mduser-management.md

ui-elements.mddocs/

0

# UI Elements

1

2

Rich UI components for enhancing chat interfaces with media, data visualizations, interactive elements, and task management. These elements can be attached to messages or sent independently to create engaging conversational experiences.

3

4

## Capabilities

5

6

### Media Display Elements

7

8

Display images, audio, video, and files within the chat interface with flexible sizing and positioning options.

9

10

```python { .api }

11

import chainlit as cl

12

13

class Image:

14

"""

15

Display images in the chat interface with flexible sizing and positioning.

16

17

Args:

18

name: str - Element identifier

19

path: Optional[str] - Local file path to image

20

content: Optional[bytes] - Image bytes data

21

url: Optional[str] - Remote image URL

22

display: ElementDisplay - Display mode ("inline", "side", "page")

23

size: ElementSize - Image size ("small", "medium", "large")

24

25

Returns:

26

Image element instance

27

"""

28

def __init__(

29

self,

30

name: str,

31

path: Optional[str] = None,

32

content: Optional[bytes] = None,

33

url: Optional[str] = None,

34

display: ElementDisplay = "inline",

35

size: ElementSize = "medium"

36

): ...

37

38

async def send(self) -> "Image":

39

"""Send the image element to the UI."""

40

41

class Audio:

42

"""

43

Audio playback element with auto-play control.

44

45

Args:

46

name: str - Element identifier

47

path: Optional[str] - Local audio file path

48

content: Optional[bytes] - Audio bytes data

49

url: Optional[str] - Remote audio URL

50

display: ElementDisplay - Display mode

51

auto_play: bool - Auto-play audio (default: False)

52

53

Returns:

54

Audio element instance

55

"""

56

def __init__(

57

self,

58

name: str,

59

path: Optional[str] = None,

60

content: Optional[bytes] = None,

61

url: Optional[str] = None,

62

display: ElementDisplay = "inline",

63

auto_play: bool = False

64

): ...

65

66

async def send(self) -> "Audio":

67

"""Send the audio element to the UI."""

68

69

class Video:

70

"""

71

Video playback element with ReactPlayer configuration support.

72

73

Args:

74

name: str - Element identifier

75

path: Optional[str] - Local video file path

76

content: Optional[bytes] - Video bytes data

77

url: Optional[str] - Remote video URL

78

display: ElementDisplay - Display mode

79

size: ElementSize - Video size (default: "medium")

80

player_config: Optional[dict] - ReactPlayer configuration options

81

82

Returns:

83

Video element instance

84

"""

85

def __init__(

86

self,

87

name: str,

88

path: Optional[str] = None,

89

content: Optional[bytes] = None,

90

url: Optional[str] = None,

91

display: ElementDisplay = "inline",

92

size: ElementSize = "medium",

93

player_config: Optional[dict] = None

94

): ...

95

96

async def send(self) -> "Video":

97

"""Send the video element to the UI."""

98

99

class File:

100

"""

101

Generic file download element for any file type.

102

103

Args:

104

name: str - Element identifier and display name

105

path: Optional[str] - Local file path

106

content: Optional[bytes] - File bytes data

107

url: Optional[str] - Remote file URL

108

display: ElementDisplay - Display mode

109

110

Returns:

111

File element instance

112

"""

113

def __init__(

114

self,

115

name: str,

116

path: Optional[str] = None,

117

content: Optional[bytes] = None,

118

url: Optional[str] = None,

119

display: ElementDisplay = "inline"

120

): ...

121

122

async def send(self) -> "File":

123

"""Send the file element to the UI."""

124

```

125

126

Usage examples for media elements:

127

128

```python

129

import chainlit as cl

130

131

@cl.on_message

132

async def handle_media(message: cl.Message):

133

# Display an image from file path

134

await cl.Image(

135

name="chart",

136

path="./chart.png",

137

size="large"

138

).send()

139

140

# Display image from bytes

141

with open("image.jpg", "rb") as f:

142

image_bytes = f.read()

143

144

await cl.Image(

145

name="photo",

146

content=image_bytes,

147

display="side"

148

).send()

149

150

# Audio with auto-play

151

await cl.Audio(

152

name="notification",

153

path="./notification.mp3",

154

auto_play=True

155

).send()

156

157

# Video with custom player config

158

await cl.Video(

159

name="demo",

160

url="https://example.com/video.mp4",

161

player_config={"controls": True, "volume": 0.5}

162

).send()

163

164

# File download

165

await cl.File(

166

name="report.pdf",

167

path="./generated_report.pdf"

168

).send()

169

```

170

171

### Data Visualization Elements

172

173

Display formatted text, interactive charts, DataFrames, and PDF documents for rich data presentation.

174

175

```python { .api }

176

class Text:

177

"""

178

Display formatted text with optional syntax highlighting (not a message).

179

180

Args:

181

name: str - Element identifier

182

content: str - Text content to display

183

language: Optional[str] - Syntax highlighting language

184

display: ElementDisplay - Display mode

185

186

Returns:

187

Text element instance

188

"""

189

def __init__(

190

self,

191

name: str,

192

content: str,

193

language: Optional[str] = None,

194

display: ElementDisplay = "inline"

195

): ...

196

197

async def send(self) -> "Text":

198

"""Send the text element to the UI."""

199

200

class Plotly:

201

"""

202

Interactive Plotly charts with automatic JSON conversion.

203

204

Args:

205

name: str - Element identifier

206

figure: Any - Plotly figure object (plotly.graph_objects.Figure)

207

size: ElementSize - Chart size (default: "medium")

208

display: ElementDisplay - Display mode

209

210

Returns:

211

Plotly element instance

212

213

Note:

214

Automatically converts figure to JSON format for display

215

"""

216

def __init__(

217

self,

218

name: str,

219

figure: Any,

220

size: ElementSize = "medium",

221

display: ElementDisplay = "inline"

222

): ...

223

224

async def send(self) -> "Plotly":

225

"""Send the Plotly chart to the UI."""

226

227

class Pyplot:

228

"""

229

Matplotlib pyplot charts with automatic PNG conversion.

230

231

Args:

232

name: str - Element identifier

233

figure: Any - Matplotlib Figure object

234

size: ElementSize - Chart size (default: "medium")

235

display: ElementDisplay - Display mode

236

237

Returns:

238

Pyplot element instance

239

240

Note:

241

Automatically converts to PNG format for display

242

"""

243

def __init__(

244

self,

245

name: str,

246

figure: Any,

247

size: ElementSize = "medium",

248

display: ElementDisplay = "inline"

249

): ...

250

251

async def send(self) -> "Pyplot":

252

"""Send the matplotlib chart to the UI."""

253

254

class Dataframe:

255

"""

256

Display pandas DataFrames with automatic JSON conversion.

257

258

Args:

259

name: str - Element identifier

260

data: Any - Pandas DataFrame object

261

size: ElementSize - Display size (default: "large")

262

display: ElementDisplay - Display mode

263

264

Returns:

265

Dataframe element instance

266

267

Note:

268

Automatically converts DataFrame to JSON format for display

269

"""

270

def __init__(

271

self,

272

name: str,

273

data: Any,

274

size: ElementSize = "large",

275

display: ElementDisplay = "inline"

276

): ...

277

278

async def send(self) -> "Dataframe":

279

"""Send the DataFrame to the UI."""

280

281

class Pdf:

282

"""

283

PDF document viewer with page navigation support.

284

285

Args:

286

name: str - Element identifier

287

path: Optional[str] - Local PDF file path

288

content: Optional[bytes] - PDF bytes data

289

url: Optional[str] - Remote PDF URL

290

display: ElementDisplay - Display mode

291

page: Optional[int] - Initial page to display

292

mime: str - MIME type (default: "application/pdf")

293

294

Returns:

295

Pdf element instance

296

"""

297

def __init__(

298

self,

299

name: str,

300

path: Optional[str] = None,

301

content: Optional[bytes] = None,

302

url: Optional[str] = None,

303

display: ElementDisplay = "inline",

304

page: Optional[int] = None,

305

mime: str = "application/pdf"

306

): ...

307

308

async def send(self) -> "Pdf":

309

"""Send the PDF viewer to the UI."""

310

```

311

312

Usage examples for data visualization:

313

314

```python

315

import chainlit as cl

316

import plotly.graph_objects as go

317

import matplotlib.pyplot as plt

318

import pandas as pd

319

320

@cl.on_message

321

async def show_visualizations(message: cl.Message):

322

# Display formatted code

323

code = "def hello():\n return 'world'"

324

await cl.Text(

325

name="code_sample",

326

content=code,

327

language="python"

328

).send()

329

330

# Interactive Plotly chart

331

fig = go.Figure()

332

fig.add_trace(go.Scatter(x=[1, 2, 3, 4], y=[10, 11, 12, 13]))

333

fig.update_layout(title="Sample Chart")

334

335

await cl.Plotly(

336

name="interactive_chart",

337

figure=fig,

338

size="large"

339

).send()

340

341

# Matplotlib chart

342

plt.figure(figsize=(10, 6))

343

plt.plot([1, 2, 3, 4], [1, 4, 2, 3])

344

plt.title("Matplotlib Chart")

345

346

await cl.Pyplot(

347

name="static_chart",

348

figure=plt.gcf()

349

).send()

350

plt.close()

351

352

# DataFrame display

353

df = pd.DataFrame({

354

'Name': ['Alice', 'Bob', 'Charlie'],

355

'Age': [25, 30, 35],

356

'City': ['NY', 'LA', 'Chicago']

357

})

358

359

await cl.Dataframe(

360

name="user_data",

361

data=df

362

).send()

363

364

# PDF viewer

365

await cl.Pdf(

366

name="documentation",

367

path="./user_guide.pdf",

368

page=1

369

).send()

370

```

371

372

### Interactive Elements and Actions

373

374

Create custom interactive components and action buttons that trigger callbacks.

375

376

```python { .api }

377

class CustomElement:

378

"""

379

Custom UI component with arbitrary properties for advanced interactions.

380

381

Args:

382

name: str - Element identifier

383

props: Dict - Custom properties for the element

384

display: ElementDisplay - Display mode

385

mime: str - MIME type (default: "application/json")

386

387

Returns:

388

CustomElement instance

389

"""

390

def __init__(

391

self,

392

name: str,

393

props: Dict,

394

display: ElementDisplay = "inline",

395

mime: str = "application/json"

396

): ...

397

398

async def update(self, props: Dict) -> "CustomElement":

399

"""Update element properties dynamically."""

400

401

async def send(self) -> "CustomElement":

402

"""Send the custom element to the UI."""

403

404

class Action:

405

"""

406

Interactive buttons that trigger callbacks when clicked.

407

408

Args:

409

name: str - Action identifier for callbacks

410

payload: Dict - Data passed to callback when triggered

411

label: str - Button text displayed to user

412

tooltip: str - Hover tooltip text

413

icon: Optional[str] - Lucide icon name

414

415

Returns:

416

Action instance

417

"""

418

def __init__(

419

self,

420

name: str,

421

payload: Dict,

422

label: str,

423

tooltip: str = "",

424

icon: Optional[str] = None

425

): ...

426

427

async def send(self, for_id: Optional[str] = None) -> "Action":

428

"""Send action button, optionally for a specific message."""

429

430

async def remove(self) -> None:

431

"""Remove the action button from the UI."""

432

```

433

434

Usage examples for interactive elements:

435

436

```python

437

import chainlit as cl

438

439

@cl.on_message

440

async def interactive_demo(message: cl.Message):

441

# Custom element with interactive properties

442

custom_props = {

443

"type": "rating",

444

"max_rating": 5,

445

"current_rating": 0,

446

"allow_half": True

447

}

448

449

rating_element = cl.CustomElement(

450

name="user_rating",

451

props=custom_props

452

)

453

await rating_element.send()

454

455

# Action buttons

456

actions = [

457

cl.Action(

458

name="approve",

459

label="Approve",

460

payload={"action": "approve", "id": 123},

461

icon="check"

462

),

463

cl.Action(

464

name="reject",

465

label="Reject",

466

payload={"action": "reject", "id": 123},

467

icon="x"

468

)

469

]

470

471

# Send message with actions

472

msg = await cl.Message(

473

"Please review this request:",

474

actions=actions

475

).send()

476

477

@cl.action_callback("approve")

478

async def handle_approval(action: cl.Action):

479

await cl.Message(f"Request {action.payload['id']} approved!").send()

480

481

@cl.action_callback("reject")

482

async def handle_rejection(action: cl.Action):

483

await cl.Message(f"Request {action.payload['id']} rejected.").send()

484

```

485

486

### Task Management

487

488

Create and manage dynamic task lists with status tracking for complex workflows.

489

490

```python { .api }

491

class Task:

492

"""

493

Individual task item for TaskList with status tracking.

494

495

Args:

496

title: str - Task description text

497

status: TaskStatus - Current status ("ready", "running", "failed", "done")

498

forId: Optional[str] - Associated message or step ID

499

500

Returns:

501

Task instance

502

"""

503

def __init__(

504

self,

505

title: str,

506

status: TaskStatus = "ready",

507

forId: Optional[str] = None

508

): ...

509

510

class TaskStatus:

511

"""Task status enumeration for task state management."""

512

READY = "ready"

513

RUNNING = "running"

514

FAILED = "failed"

515

DONE = "done"

516

517

class TaskList:

518

"""

519

Dynamic task list with status tracking for complex workflows.

520

521

Args:

522

tasks: List[Task] - Initial list of tasks

523

status: str - Overall status message (default: "Ready")

524

525

Returns:

526

TaskList instance

527

"""

528

def __init__(

529

self,

530

tasks: List[Task],

531

status: str = "Ready"

532

): ...

533

534

def add_task(self, task: Task) -> None:

535

"""Add a new task to the list."""

536

537

async def update(self) -> "TaskList":

538

"""Update the task list in the UI."""

539

540

async def send(self) -> "TaskList":

541

"""Send the task list to the UI."""

542

```

543

544

Usage example for task management:

545

546

```python

547

import chainlit as cl

548

549

@cl.on_message

550

async def workflow_demo(message: cl.Message):

551

# Create task list for a complex workflow

552

tasks = [

553

cl.Task(title="Parse user input", status="ready"),

554

cl.Task(title="Fetch external data", status="ready"),

555

cl.Task(title="Process with AI model", status="ready"),

556

cl.Task(title="Generate response", status="ready")

557

]

558

559

task_list = cl.TaskList(tasks=tasks, status="Starting workflow...")

560

await task_list.send()

561

562

# Execute tasks with status updates

563

for i, task in enumerate(tasks):

564

task.status = "running"

565

await task_list.update()

566

567

# Simulate work

568

await cl.sleep(2)

569

570

# Complete task

571

task.status = "done"

572

await task_list.update()

573

574

# Update overall status

575

task_list.status = "Workflow completed!"

576

await task_list.update()

577

578

await cl.Message("All tasks completed successfully!").send()

579

```

580

581

## Core Types

582

583

```python { .api }

584

from typing import Union, Optional, List, Dict, Any

585

from enum import Enum

586

587

# Display and sizing options

588

ElementDisplay = Union["inline", "side", "page"]

589

ElementSize = Union["small", "medium", "large"]

590

591

# Task status enumeration

592

TaskStatus = Union["ready", "running", "failed", "done"]

593

594

# Base element interface

595

class ElementBased:

596

name: str

597

display: ElementDisplay

598

size: Optional[ElementSize]

599

600

# Action payload type

601

ActionPayload = Dict[str, Any]

602

```