Build production-ready conversational AI applications in minutes with rich UI components and LLM integrations
npx @tessl/cli install tessl/pypi-chainlit@2.7.00
# Chainlit
1
2
A comprehensive Python framework for building production-ready conversational AI applications in minutes. Chainlit provides rich UI components, seamless LLM integrations, and powerful observability features that enable developers to create interactive chat applications, AI agents, and conversational workflows with minimal boilerplate code.
3
4
## Package Information
5
6
- **Package Name**: chainlit
7
- **Language**: Python
8
- **Installation**: `pip install chainlit`
9
10
## Core Imports
11
12
```python
13
import chainlit as cl
14
```
15
16
For specific components:
17
18
```python
19
from chainlit import Message, Step, User, Action
20
from chainlit.input_widget import Slider, Switch, Select
21
```
22
23
## Basic Usage
24
25
```python
26
import chainlit as cl
27
28
@cl.on_chat_start
29
async def start():
30
"""Initialize the chat session"""
31
await cl.Message("Hello! I'm your AI assistant. How can I help you today?").send()
32
33
@cl.on_message
34
async def main(message: cl.Message):
35
"""Handle incoming user messages"""
36
# Process the user's message
37
user_input = message.content
38
39
# Send a response
40
response = f"You said: {user_input}"
41
await cl.Message(response).send()
42
43
# Add an image element
44
await cl.Image(
45
name="example",
46
path="./image.png",
47
display="inline"
48
).send()
49
50
# Run the app with: chainlit run app.py
51
```
52
53
## Architecture
54
55
Chainlit's architecture centers around four key concepts that work together to create rich conversational experiences:
56
57
- **Messages**: The primary communication unit between users and AI, supporting rich content, attachments, and interactive elements
58
- **Steps**: Execution tracking and observability components that provide transparency into AI processing workflows
59
- **Elements**: Rich media and data visualization components (images, videos, charts, files) that enhance message content
60
- **Callbacks**: Event-driven hooks that handle user interactions, application lifecycle, and system events
61
62
This design enables building complex conversational AI applications with full observability, rich multimedia support, and seamless integration with popular ML/AI frameworks like OpenAI, LangChain, and LlamaIndex.
63
64
## Capabilities
65
66
### Core Messaging
67
68
Send messages with rich content, attachments, and interactive elements. Handle user input through text, file uploads, and custom interactions.
69
70
```python { .api }
71
class Message:
72
def __init__(
73
self,
74
content: Union[str, Dict] = "",
75
author: Optional[str] = None,
76
elements: Optional[List[Element]] = None,
77
actions: Optional[List[Action]] = None
78
): ...
79
80
async def send(self) -> "Message": ...
81
async def update(self) -> "Message": ...
82
async def stream_token(self, token: str) -> None: ...
83
84
class AskUserMessage:
85
def __init__(self, content: str, timeout: int = 60): ...
86
async def send(self) -> Optional[Dict]: ...
87
88
class AskFileMessage:
89
def __init__(
90
self,
91
content: str,
92
accept: Union[List[str], Dict[str, List[str]]],
93
max_size_mb: int = 2,
94
max_files: int = 1
95
): ...
96
async def send(self) -> Optional[List]: ...
97
```
98
99
[Messaging](./messaging.md)
100
101
### Step Management and Observability
102
103
Track execution steps and provide transparency into AI processing workflows with automatic timing, input/output capture, and nested step hierarchies.
104
105
```python { .api }
106
class Step:
107
def __init__(
108
self,
109
name: str,
110
type: str = "run",
111
show_input: Union[bool, str] = "json"
112
): ...
113
114
async def send(self) -> "Step": ...
115
async def update(self) -> "Step": ...
116
async def __aenter__(self) -> "Step": ...
117
async def __aexit__(self, *args) -> None: ...
118
119
def step(
120
name: Optional[str] = None,
121
type: str = "run",
122
show_input: Union[bool, str] = "json"
123
): ...
124
```
125
126
[Messaging](./messaging.md)
127
128
### Rich UI Elements
129
130
Display images, videos, audio, charts, DataFrames, PDFs, and custom components within the chat interface.
131
132
```python { .api }
133
class Image:
134
def __init__(
135
self,
136
name: str,
137
path: Optional[str] = None,
138
content: Optional[bytes] = None,
139
display: str = "inline",
140
size: str = "medium"
141
): ...
142
143
class Plotly:
144
def __init__(self, name: str, figure: Any, size: str = "medium"): ...
145
146
class Dataframe:
147
def __init__(self, name: str, data: Any, size: str = "large"): ...
148
149
class File:
150
def __init__(
151
self,
152
name: str,
153
path: Optional[str] = None,
154
content: Optional[bytes] = None
155
): ...
156
157
class ElementSidebar:
158
def __init__(self): ...
159
# Methods for managing sidebar element display
160
```
161
162
[UI Elements](./ui-elements.md)
163
164
### User Management and Sessions
165
166
Manage user authentication, sessions, and persistent data across conversations.
167
168
```python { .api }
169
class User:
170
def __init__(
171
self,
172
identifier: str,
173
display_name: Optional[str] = None,
174
metadata: Dict = {}
175
): ...
176
177
user_session: UserSession
178
# Methods: get(), set(), create_accessor()
179
```
180
181
[User Management](./user-management.md)
182
183
### Event Callbacks
184
185
Handle application lifecycle, user interactions, and system events through decorators.
186
187
```python { .api }
188
@cl.on_chat_start
189
async def start(): ...
190
191
@cl.on_message
192
async def handle_message(message: cl.Message): ...
193
194
@cl.on_audio_chunk
195
async def handle_audio(chunk: InputAudioChunk): ...
196
197
@cl.password_auth_callback
198
async def auth(username: str, password: str) -> Optional[cl.User]: ...
199
200
@cl.action_callback("button_name")
201
async def handle_action(action: cl.Action): ...
202
```
203
204
[Callbacks](./callbacks.md)
205
206
### Dynamic Input Widgets
207
208
Create interactive settings panels with sliders, switches, text inputs, dropdowns, and custom widgets.
209
210
```python { .api }
211
from chainlit.input_widget import Slider, Switch, Select, TextInput
212
213
class Slider:
214
def __init__(
215
self,
216
id: str,
217
label: str,
218
initial: float = 0,
219
min: float = 0,
220
max: float = 10
221
): ...
222
223
class ChatSettings:
224
def __init__(self, widgets: List[InputWidget]): ...
225
```
226
227
[Input Widgets](./input-widgets.md)
228
229
### ML/AI Framework Integrations
230
231
Seamless integration with popular AI frameworks including automatic step tracking and observability.
232
233
```python { .api }
234
# OpenAI Integration
235
def instrument_openai() -> None: ...
236
237
# LangChain Integration
238
class LangchainCallbackHandler: ...
239
class AsyncLangchainCallbackHandler: ...
240
241
# LlamaIndex Integration
242
class LlamaIndexCallbackHandler: ...
243
244
# Mistral AI Integration
245
def instrument_mistralai() -> None: ...
246
```
247
248
[Integrations](./integrations.md)
249
250
### Authentication and OAuth
251
252
Implement secure authentication with password, header, and OAuth providers.
253
254
```python { .api }
255
@cl.password_auth_callback
256
async def password_auth(username: str, password: str) -> Optional[cl.User]: ...
257
258
@cl.header_auth_callback
259
async def header_auth(headers: Headers) -> Optional[cl.User]: ...
260
261
@cl.oauth_callback
262
async def oauth_callback(
263
provider_id: str,
264
token: str,
265
raw_user_data: Dict,
266
default_user: cl.User,
267
id_token: Optional[str] = None
268
) -> Optional[cl.User]: ...
269
```
270
271
[Authentication](./authentication.md)
272
273
### Advanced Features
274
275
Caching, async utilities, MCP (Model Context Protocol) support, and server functionality for production deployments.
276
277
```python { .api }
278
@cl.cache
279
def expensive_function(arg: str) -> str: ...
280
281
async def make_async(func: Callable) -> Callable: ...
282
def run_sync(coro: Awaitable) -> Any: ...
283
async def sleep(duration: int) -> None: ...
284
285
@cl.on_mcp_connect
286
async def mcp_connect(connection: McpConnection, session: ClientSession): ...
287
288
class CopilotFunction:
289
name: str
290
args: Dict[str, Any]
291
async def acall(self) -> Any: ...
292
293
# Context and session management
294
context: ChainlitContext
295
chat_context: ChatContextManager
296
297
# Version information
298
__version__: str
299
```
300
301
[Advanced Features](./advanced.md)
302
303
## Core Types
304
305
```python { .api }
306
from typing import Union, Optional, List, Dict, Any
307
308
# Element display modes
309
ElementDisplay = Union["inline", "side", "page"]
310
ElementSize = Union["small", "medium", "large"]
311
312
# Step types
313
TrueStepType = Union[
314
"run", "llm", "tool", "embedding", "retrieval",
315
"rerank", "undefined", "assistant_message", "user_message"
316
]
317
318
# Message types
319
MessageStepType = Union["assistant_message", "user_message"]
320
321
# Task status
322
TaskStatus = Union["ready", "running", "failed", "done"]
323
324
# Audio chunk data
325
@dataclass
326
class InputAudioChunk:
327
isStart: bool
328
mimeType: str
329
elapsedTime: float
330
data: bytes
331
332
# Chat profile configuration
333
@dataclass
334
class ChatProfile:
335
name: str
336
markdown_description: str
337
icon: Optional[str] = None
338
default: bool = False
339
340
# Conversation starter
341
@dataclass
342
class Starter:
343
label: str
344
message: str
345
command: Optional[str] = None
346
icon: Optional[str] = None
347
```