-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathllms.txt
More file actions
1408 lines (1106 loc) · 49.6 KB
/
llms.txt
File metadata and controls
1408 lines (1106 loc) · 49.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Violit — AI/LLM Code Generation Reference
> **Violit ≈ Streamlit-like authoring + fine-grained reactive updates + built-in app stack**
> If you know Streamlit, start there, but do not assume Violit is only a widget-compatible clone.
> Violit also has built-in ORM, auth, Tailwind-first styling hooks, background jobs, and interval timers.
---
## Quick Mental Model
```
Streamlit: st.xxx() → Violit: app.xxx()
st.session_state → app.state() / app.session_state()
Full script rerun on change → Only affected widgets update (Zero Rerun)
```
## High-Priority Rules For Code Generation
- Always create `app = vl.App(...)` before using widgets.
- Always end runnable examples with `app.run()`.
- Prefer showing run commands as `violit run app.py ...`; `python app.py ...` still works, but the CLI is now the recommended default.
- Prefer `app.state()` over ad-hoc globals or `session_state`-style dict code.
- Remember that `app.state()` is view-local by default. Use `session_state`, `app_state`, and `shared_state` when wider sharing is intentional.
- Pass `State` objects directly to widgets when you want reactivity.
- Input `on_change` callbacks receive the new decoded value directly, not a `State` object.
- `selectbox(...)` uses index-based initial selection semantics. Prefer `index=` for the initial choice; do not invent `value=` for it.
- Use `lambda:` when formatting `state.value` inside strings.
- For complex reactive blocks, prefer `@app.reactivity`.
- For reactive list or conditional rendering driven by changing state, prefer `app.For(...)` and `app.If(...)` before writing manual Python loops around `state.value`.
- Do not generate `@app.fragment`; `fragment` is deprecated.
- After defining a `@app.reactivity` function, call it once to register/render it.
- Buttons do not return booleans. Use `on_click=`.
- `State.subscribe(...)` and `@state.on_change` are for side effects such as logging or persistence, not for normal UI refreshes.
- Use `app.text_input(..., type="password")` for password fields; do not invent `app.password_input(...)`.
- For grouped submit UIs, prefer `with app.form(...):` + `app.form_submit_button(...)`.
- For navigation from callbacks, prefer `app.switch_page(...)`.
- For downloads and links, prefer `app.download_button(...)`, `app.link_button(...)`, and `app.page_link(...)` over hand-written HTML.
- For public examples that need API keys, never hardcode secrets. Prefer `app.text_input(..., type="password")` or environment loading only if the user explicitly asks for it.
- Sidebar content is reactive like main content. Use `State` and `lambda:` normally inside `with app.sidebar:`.
- For plain LLM chat apps, prefer `app.chat_history(...)` + `app.managed_chat_input(messages=..., on_submit=...)` over inventing a custom chat stack.
- For agent-oriented apps, prefer `app.agent_history(...)` + `app.managed_chat_input(messages=..., on_submit=...)`.
- For custom chat transcript layout, prefer `app.chat_thread(...)` + `with app.chat_message(...):` over raw HTML string assembly.
- For primitive custom chat transcripts, prefer `app.render_chat_message_body(...)`; for primitive agent transcripts, use `app.agent_turn(...)` and the shared agent message schema.
- For database apps, prefer `vl.App(db="./app.db")` and `app.db` CRUD.
- For auth, prefer `app.setup_auth(User)` instead of inventing a custom login stack.
- For styling, start with `cls`. Use `style`, `configure_widget()`, `add_css()`, and `part_cls` only as needed.
- For runtime theming and UX toggles, prefer `app.set_theme(...)`, `app.set_animation_mode(...)`, `app.set_primary_color(...)`, and `app.set_selection_mode(...)`.
- For long-running work, prefer `app.background(...)`.
- For polling and live tickers, prefer `app.interval(...)`.
## Common Hallucinations To Avoid
- Do not write `if app.button(...): ...`.
- Do not assume Streamlit's rerun model exists in Violit.
- Do not default to `st.session_state`-style patterns.
- Do not generate `@app.fragment` or `app.fragment(...)`; it is deprecated.
- Do not define `@app.reactivity` blocks and forget to call them.
- Do not use `@app.reactivity` when a direct `State` pass, `lambda:`, `app.If()`, or `app.For()` already solves the problem more simply.
- Do not initialize `app.selectbox(...)` with `value=`; use `index=` for the initial option.
- Do not treat styling as UnoCSS-first or invent framework-specific CSS DSLs.
- Do not assume ORM and auth require external integration first; Violit already has built-in paths.
- Do not generate `app.password_input(...)`; use `app.text_input(..., type="password")`.
- Do not assume `on_change` receives a `State`; it receives the current decoded value.
- Do not assume sidebar content is static or outside the reactive system.
- Do not hand-roll `<a download>` or custom JS download snippets when `app.download_button(...)` already solves it.
- Do not hand-roll modal HTML when `@app.dialog(...)` fits the task.
- Do not hardcode API keys or other secrets into examples intended for GitHub or docs.
- Do not generate `app.chat_messages(...)`; the high-level transcript renderers are `app.chat_history(...)` and `app.agent_history(...)`.
- Do not pass `messages=...` to primitive `app.chat_input(...)`; `messages=` belongs to `app.managed_chat_input(...)`.
- Do not put `app.chat_input(...)` inside a reactive block when its props are static.
- Do not manually append both user and assistant messages when using `app.managed_chat_input(messages=..., on_submit=...)`; return the assistant reply or stream instead.
- Do not mix manual `append_message(...)` / `replace_last_message(...)` transcript mutation with `managed_chat_input(...)` for the same turn.
- Do not invent alternate agent fields such as `steps`, `tool_calls`, or `reasoning_text` when Violit already understands `phase`, `status_text`, `summary`, `trace`, `artifacts`, and `error`.
- Do not forget that primitive attachment/audio submissions arrive as a dict with `text`, `files`, and `audio` keys when enabled.
- Do not manually reimplement streamed chunk rendering inside chat bubbles when `app.render_chat_message_body(...)` already handles text, chunks, and default attachment previews.
---
## 1. Boilerplate (Streamlit vs Violit)
```python
# ❌ Streamlit
import streamlit as st
st.title("Hello")
st.write("World")
# ✅ Violit
import violit as vl
app = vl.App(title="Hello", theme="ocean")
app.title("Hello")
app.write("World")
app.run() # REQUIRED at the end
```
**Key differences:**
- `import violit as vl` (not `import streamlit as st`)
- Must create `app = vl.App(...)` instance first
- All widgets are called on `app` (e.g., `app.title()` not `st.title()`)
- Must call `app.run()` at the end of the script
**App constructor options:**
```python
app = vl.App(
title="My App", # Browser/window title
theme="ocean", # Theme preset (dark, light, ocean, cyberpunk, etc.)
container_width="800px", # Content max-width ("none" for full-width)
mode="ws", # "ws" (WebSocket, default) or "lite" (HTMX; often better for higher concurrency)
)
```
**Running (recommended):**
```bash
violit run app.py # Web mode (default)
violit run app.py --reload --localhost # Hot reload on localhost
violit run app.py --lite --localhost # HTMX-based Lite mode; often better for higher concurrency
violit run app.py --native # Desktop app mode (pywebview)
violit run app.py --host 0.0.0.0 --port 8020 # LAN/server bind
violit run app.py --help # Show runtime flags
```
`python app.py [args]` still works, but `violit run ...` is the preferred default for generated docs and examples.
---
## 2. State — The Core Difference
Streamlit uses `st.session_state` dict + full rerun. Violit uses reactive `State` objects.
```python
# ❌ Streamlit
if "count" not in st.session_state:
st.session_state.count = 0
if st.button("Click"):
st.session_state.count += 1
st.write(st.session_state.count)
# ✅ Violit
count = app.state(0)
app.button("Click", on_click=lambda: count.set(count.value + 1))
app.write(count) # Auto-updates when count changes
```
`app.state()` is the default, view-local state. Violit also supports wider scopes when you need sharing beyond the current browser view.
### State API
```python
# Create
count = app.state(0) # Default: current view only
name = app.state("", key="user_name") # Explicit key
# Recommended explicit wrappers for wider sharing
theme = app.session_state("light", key="theme")
online = app.app_state(0, key="online_users")
messages = app.shared_state([], key="messages", namespace="room:lobby")
# Raw low-level form (same engine underneath)
draft = app.state("", key="draft", scope="view")
room = app.state([], key="messages", scope="shared", namespace="room:lobby")
# Read
count.value # → 0
count() # → 0 (shorthand)
# Write
count.set(5) # Preferred in callbacks
count.value = 5 # Also works
# ⚠️ NEVER reassign the variable
count = 5 # ❌ WRONG — State object is lost!
```
### State Scopes
```python
draft = app.state("", key="draft")
theme = app.session_state("light", key="theme")
online_count = app.app_state(0, key="online_count")
room_messages = app.shared_state([], key="messages", namespace="room:lobby")
```
- `app.state(...)` / `app.view_state(...)`: current browser view only. Best for page-local UI state.
- `app.session_state(...)`: shared across tabs in the same browser session.
- `app.app_state(...)`: shared across all users in the current Violit process.
- `app.shared_state(..., namespace=...)`: shared across all users connected to the same named room / board / workspace.
Important scope notes:
- `app_state()` and `shared_state()` are process-local memory. They do not automatically sync across multiple workers or servers.
- `shared_state()` is a collaboration primitive, not an auth boundary. Your app still decides who may enter or write a namespace.
- App/shared values have a size safety limit, and inactive shared namespaces are cleaned up automatically.
### Passing State to Widgets (Reactivity)
```python
count = app.state(0)
name = app.state("World")
# ✅ Reactive — auto-updates when state changes
app.text(count) # State object directly
app.text(count * 2) # Operator overloading → ComputedState
app.text("Hello, " + name + "!") # String concatenation
app.text(lambda: f"Count: {count.value}") # Lambda for complex formatting
app.metric("Total", count) # State in any widget
# ❌ NOT reactive — value is frozen at call time
app.text(count.value) # Just passes int 0
app.text(f"Count: {count.value}") # Just passes string "Count: 0"
```
**Rule of thumb:**
- Pass State **object** to widgets → reactive
- Pass `state.value` to widgets → frozen (not reactive)
- Use `lambda:` when you need f-string formatting or complex logic
- Use `.value` only in callbacks/calculations, not in widget arguments
### Reactive Lists and Conditional Blocks
When the number of rendered widgets changes with state, do not rely on a top-level Python `for` loop over `state.value`.
Use `app.For(...)`, `app.If(...)`, or `@app.reactivity` so Violit can rerender that block correctly.
```python
messages = app.shared_state([], key="messages", namespace="room:lobby")
app.For(
lambda: messages.value,
render=lambda item, index: app.text(f"{index + 1}. {item}"),
empty=lambda: app.caption("No messages yet."),
)
```
### Complex Reactivity: `@app.reactivity`
Most reactivity in Violit does **not** need a decorator.
Use direct `State` passing, operators, `lambda:`, `app.If()`, or `app.For()` first.
Use `@app.reactivity` when you need a **reactive block with normal Python control flow**, especially `if` / `for` logic that should rerender as a unit.
```python
count = app.state(0)
@app.reactivity
def summary_block():
if count.value > 5:
app.success("Big!")
else:
app.info("Small")
summary_block() # REQUIRED: call once to register and render
```
**Important rules:**
- Prefer `@app.reactivity` over deprecated `@app.fragment`
- The decorated function must be called once after definition
- Use it for grouped reactive control flow, not for every simple text binding
- For simple output, `app.text(state)` or `app.text(lambda: ...)` is usually better
**Decorator vs context manager:**
- `@app.reactivity`: preferred for a function-wrapped reactive block and partial rerender of that block
- `with app.reactivity():`: valid, but think of it as an inline reactive scope; use only when the inline form is clearly better
**Deprecated pattern:**
```python
@app.fragment
def old_block():
app.text("Do not generate this")
```
Do not generate that pattern in new Violit code.
### State Side Effects
State already updates dependent widgets automatically. Use subscriptions only when you need side effects outside normal rendering.
```python
count = app.state(0)
def log_change(new_value, old_value):
print(f"count changed: {old_value} -> {new_value}")
subscription = count.subscribe(log_change)
@count.on_change
def _(new_value):
print("new count:", new_value)
# Later, if needed
subscription.cancel()
```
- `subscribe(callback)` supports `callback(new_value)` or `callback(new_value, old_value)`.
- `@state.on_change` is decorator sugar for `subscribe(...)`.
- Prefer subscriptions for logging, persistence, analytics, or background coordination, not for normal UI redraws.
---
## 3. Input Widgets — Return State, Not Values
In Streamlit, input widgets return the current value directly.
In Violit, input widgets return a **State object**.
```python
# ❌ Streamlit
name = st.text_input("Name") # name is str
if st.button("Greet"):
st.write(f"Hello {name}")
# ✅ Violit
name = app.text_input("Name") # name is State[str]
app.button("Greet", on_click=lambda: app.toast(f"Hello {name.value}"))
app.text("Hello, " + name) # Reactive display
```
### All Input Widgets (same names as Streamlit)
```python
name = app.text_input("Name", value="default")
bio = app.text_area("Bio", height=5)
age = app.number_input("Age", value=0, min_value=0, max_value=120, step=1)
score = app.slider("Score", min_value=0, max_value=100, value=50)
agree = app.checkbox("I agree", value=False)
dark = app.toggle("Dark mode", value=False)
size = app.radio("Size", options=["S", "M", "L"], index=0)
lang = app.selectbox("Language", options=["Python", "JS"], index=0)
tags = app.multiselect("Tags", options=["A", "B", "C"], default=["A"])
color = app.color_picker("Color", value="#ff0000")
date = app.date_input("Date")
time = app.time_input("Time")
file = app.file_uploader("Upload", accept=".csv,.txt", multiple=False)
```
All return `State` objects. Access current value via `.value`.
### Important Input Details
```python
query = app.text_input(
"Search",
placeholder="Type and press Enter",
on_change=lambda value: app.debug_print(value),
on_submit=lambda value: app.toast(f"Searching: {value}"),
help="Press Enter to submit",
)
secret = app.text_input("Password", type="password")
priority = app.select_slider("Priority", options=["Low", "Medium", "High"])
files = app.file_uploader("Upload files", multiple=True, accept=".csv,.txt")
```
- `on_change` callbacks receive the new value directly.
- `selectbox(...)` should be initialized with `index=...`, not `value=...`.
- `text_input(...)` supports `on_submit`, `type="password"`, `label_visibility`, and `help`.
- When `on_submit` is provided, `text_input(...)` submits on Enter by default.
- `slider(..., live_update=True)` updates continuously while dragging.
- `select_slider(...)` is for discrete options, not numeric ranges.
- `file_uploader(...)` returns `UploadedFile` objects with `.name`, `.type`, `.size`, and `.read()` support.
### Forms, Links, and File Actions
```python
with app.form("login", clear_on_submit=False, enter_to_submit=True):
username = app.text_input("Username")
password = app.text_input("Password", type="password")
app.form_submit_button("Sign in", on_click=do_login)
app.download_button("Export CSV", data=csv_text, file_name="report.csv", mime="text/csv")
app.link_button("Open Docs", "https://doc.violit.cloud")
app.page_link("Settings", label="Go to Settings")
app.button("Back Home", on_click=lambda: app.switch_page("Home"))
```
- Use `app.form(...)` for grouped submit flows.
- Use `app.form_submit_button(...)` inside the form instead of a plain button when you want form submission semantics.
- `app.switch_page(...)` accepts a `Page` object, page function, page title, url path slug, or hash string.
- Use `download_button`, `link_button`, and `page_link` before inventing custom HTML anchors.
---
## 4. Button — on_click Pattern (NOT if-block)
```python
# ❌ Streamlit pattern (if-block triggers rerun)
if st.button("Save"):
save_data()
# ✅ Violit pattern (on_click callback, no rerun)
app.button("Save", on_click=save_data)
app.button("Save", on_click=lambda: save_data())
# Button variants
app.button("OK", variant="primary") # default
app.button("Cancel", variant="neutral")
app.button("Delete", variant="danger")
app.button("Large", size="large")
```
**Important:** Violit buttons do NOT return a boolean.
Use `on_click=` to define what happens when clicked.
---
## 5. Layout — Same as Streamlit
```python
# Columns
col1, col2 = app.columns(2)
with col1:
app.text("Left")
with col2:
app.text("Right")
# Columns with ratio
c1, c2, c3 = app.columns([2, 1, 1])
# Container
with app.container(border=True):
app.text("Inside a card")
# Tabs
tab1, tab2 = app.tabs(["Tab A", "Tab B"])
with tab1:
app.text("Content A")
with tab2:
app.text("Content B")
# Expander
with app.expander("Details", expanded=False):
app.text("Hidden content")
app.button("Default button in expander") # full width by default
# Reactive expander title
count = app.state(3)
with app.expander(lambda: f"Details ({count.value})", expanded=True):
app.text(lambda: f"Current count: {count.value}")
# Sidebar
app.configure_sidebar(width=320, min_width=240, max_width=520, resizable=True)
theme_name = app.state("ocean")
with app.sidebar:
app.text("Sidebar content")
app.badge(lambda: f"{theme_name.value.title()} Theme")
```
- Sidebar content participates in normal reactive updates.
- Nested widgets inside sidebar `container(...)`, `columns(...)`, and `expander(...)` are supported and should be written like main-area widgets.
### Widget placement guidance
For simple layout, start with `columns(...)`, `container(...)`, and widget label options before reaching for custom CSS.
```python
# Vertical placement inside each column
left, right = app.columns([1, 2], gap="medium", equal_height=True, justify="center")
# Horizontal placement inside each column
left, right = app.columns([1, 2], gap="medium", align="center")
# Local override for one side only
left, right = app.columns([1, 2], gap="medium", equal_height=True)
with left:
with app.container(fill_height=True, justify="bottom"):
app.text("Bottom only on the left")
# Selectbox label placement without extra columns
app.selectbox("Language", ["Python", "JS"], label_position="left")
app.selectbox("Mode", ["A", "B"], label_visibility="collapsed")
# Button width: default full-width, explicit override when needed
app.button("Default button") # full width by default
app.button("Fixed width button", style="width: 280px;")
app.button("Relative width button", style="width: 60%;")
with app.expander("Actions", expanded=True):
app.button("Default button in expander") # also full width by default
app.button("Fixed width in expander", style="width: 280px;")
app.button("Relative width in expander", style="width: 60%;")
```
**Placement rules of thumb:**
- Use `columns(..., justify=...)` for top/center/bottom placement of each column's child box.
- Use `columns(..., align=...)` for start/center/end placement across the horizontal axis inside each column.
- Use `equal_height=True` when vertical placement needs real extra height to be visible.
- Use `container(fill_height=True, justify=...)` when only one side of a row needs local vertical adjustment.
- Re-entering the same column or tab object multiple times in one render is a valid pattern. This is supported for layouts like `for item in items: with left: ...; with right: ...`.
- Use widget-native options like `label_position` and `label_visibility` before adding extra layout wrappers around forms.
- Default button placement should assume full-width behavior in normal vertical layout containers, including inside `app.expander(...)`.
- If a widget should be narrower than the container, prefer an explicit `style="width: ...;"` override instead of assuming special-case layout behavior inside expander or container blocks.
- When a widget label, title, or summary depends on state, pass the `State` object directly or use `lambda:`. Do not eagerly freeze it with `f"...{state.value}..."` unless a static snapshot is intentional.
- For reactive placement/content, prefer `app.text(state)` or `app.text(lambda: ...)` over `app.text(state.value)` or eager f-strings.
- For reactive expander headers, use `with app.expander(lambda: f"...{state.value}..."):`. The summary/title updates live while preserving the expander body content.
- `justify` aligns the outer child box, not the exact visual baseline of every widget. Different widgets can still look slightly off because their internal control heights, padding, or label areas differ.
- If exact visual alignment matters, add a shared inner frame with the same width/min-height on both sides, or apply small `cls` / `style` adjustments intentionally.
```python
items = app.session_state([{"text": "text"}, {"text": "another text"}], key="items")
@app.reactivity
def render_rows():
left, right = app.columns(2)
for item in items.value:
with left:
app.text(item["text"])
with right:
app.selectbox("value", ["test"])
render_rows()
```
---
## 6. Data & Charts — Same as Streamlit
```python
import pandas as pd
import plotly.express as px
df = pd.DataFrame({"x": [1, 2, 3], "y": [10, 20, 30]})
app.dataframe(df) # AG Grid (interactive)
app.table(df) # Static HTML table
app.metric("Revenue", "$54,230", "+12%") # Metric card
app.json({"key": "value"}) # JSON viewer
# Filtered master-detail UIs should keep detail selection aligned with visible rows
visible_rows = df[df["y"] >= 20].reset_index(drop=True)
selected_row = app.state({}, key="selected_row")
if visible_rows.empty:
selected_row.set({})
else:
visible_records = visible_rows.to_dict("records")
matching_row = next((row for row in visible_records if row.get("x") == selected_row.value.get("x")), None)
selected_row.set(matching_row or visible_records[0])
# Charts
fig = px.line(df, x="x", y="y")
app.plotly_chart(fig) # Plotly chart
app.line_chart(df) # Quick charts
app.bar_chart(df)
app.area_chart(df)
app.scatter_chart(df)
```
---
## 7. Status & Feedback
```python
app.success("Saved!")
app.info("FYI")
app.warning("Caution")
app.error("Failed")
app.toast("Done!", variant="success", icon="circle-check")
app.spinner("Loading...")
app.progress(75) # Progress bar (0-100)
app.balloons()
app.snow()
app.callout("Use `app.text()` for escaped output.", variant="info")
app.callout_warning("This action cannot be undone.")
app.callout_success("Deployment finished.")
```
`app.callout(...)` and the shortcut helpers (`callout_info`, `callout_warning`, `callout_success`, etc.) are the preferred way to generate admonition-style documentation UI.
---
## 8. Chat Interface
```python
from typing import Any, cast
messages = app.state([
{"role": "assistant", "content": "Hello. Ask anything."}
], key="chat_messages")
api_key = app.state("", key="chat_api_key")
mode = app.state("streaming", key="chat_mode")
reactivity = cast(Any, app.reactivity)
def _reply_non_streaming():
return "Assistant reply"
def _reply_streaming():
def stream():
yield "Assistant "
yield "reply"
return stream()
def reply(_prompt: str):
key = api_key.value.strip()
if not key:
raise RuntimeError("Paste your API key above.")
if mode.value == "streaming":
return _reply_streaming()
return _reply_non_streaming()
app.text_input("API_KEY", value=api_key.value, key="chat_api_key", type="password")
app.selectbox(
"Mode",
["streaming", "non-streaming"],
index=0 if mode.value == "streaming" else 1,
key="chat_mode",
)
@reactivity
def render_chat():
app.chat_history(messages, height="60vh")
render_chat()
app.managed_chat_input(
"Type a message...",
messages=messages,
on_submit=reply,
pinned=False,
auto_scroll="bottom",
stream_speed="smooth",
)
```
**Preferred chat rules:**
- Use `messages = app.state([...])` and pass it to `app.chat_history(...)` or `app.agent_history(...)` plus `app.managed_chat_input(...)`.
- Let `app.managed_chat_input(messages=..., on_submit=...)` own the normal turn lifecycle: append the user turn, create the assistant placeholder, and apply returned text/events.
- `on_submit` may return a `str`, an iterable yielding `str` chunks, or agent event dicts when building an agent-oriented transcript.
- Keep `app.chat_history(...)` or `app.agent_history(...)` inside `@app.reactivity` when you want only the transcript to rerender.
- Keep `app.managed_chat_input(...)` outside the reactive block when its props are static.
- For provider-specific demos, splitting `Gemini` and `OpenAI` into separate files is often clearer than one large branching file.
**Choose the right chat surface:**
- Plain high-level chat: `app.chat_history(...)` + `app.managed_chat_input(...)`
- Agent high-level chat: `app.agent_history(...)` + `app.managed_chat_input(...)`
- Plain primitive chat: `app.chat_thread(...)` + `app.chat_message(...)` + `app.render_chat_message_body(...)` + `app.chat_input(...)`
- Agent primitive chat: `app.chat_thread(...)` + `app.agent_turn(...)` + `app.render_chat_message_body(...)` + `app.chat_input(...)`
**Primitive chat example:**
```python
from typing import Any, cast
messages = app.state([
{"role": "assistant", "content": "Hello. Ask anything.", "content_format": "markdown"}
], key="primitive_chat_messages")
busy = app.state(False, key="primitive_chat_busy")
reactivity = cast(Any, app.reactivity)
def append_message(message: dict[str, Any]) -> None:
messages.set([*messages.value, dict(message)])
def replace_last_message(message: dict[str, Any]) -> None:
items = [dict(item) for item in messages.value]
items[-1] = dict(message)
messages.set(items)
def run_reply(prompt: str) -> None:
chunks = ["Assistant ", "reply"]
streamed: list[str] = []
for chunk in chunks:
streamed.append(chunk)
replace_last_message({
"role": "assistant",
"content": "".join(streamed),
"phase": "running",
"content_format": "markdown",
})
replace_last_message({
"role": "assistant",
"content": "".join(streamed),
"phase": "done",
"content_format": "markdown",
})
def submit_prompt(prompt: str) -> None:
cleaned = str(prompt or "").strip()
if not cleaned or busy.value:
return
append_message({"role": "user", "content": cleaned, "content_format": "text"})
append_message({
"role": "assistant",
"content": "",
"phase": "thinking",
"thinking_label": "Thinking...",
"content_format": "markdown",
})
busy.set(True)
app.background(
lambda prompt=cleaned: run_reply(prompt),
on_complete=lambda: busy.set(False),
on_error=lambda exc: busy.set(False),
).start()
@reactivity
def render_chat():
with app.chat_thread(height="60vh"):
for index, message in enumerate(messages.value):
with app.chat_message(
message.get("role", "assistant"),
phase=message.get("phase") or None,
thinking=(
message.get("role") == "assistant"
and not str(message.get("content", "") or "").strip()
and str(message.get("phase", "") or "") in {"thinking", "running"}
),
thinking_label=message.get("thinking_label", "Thinking..."),
status=message.get("status_text", ""),
key=message.get("key") or f"msg_{index}",
):
app.render_chat_message_body(message)
render_chat()
app.chat_input("Ask...", on_submit=submit_prompt, disabled=bool(busy.value), pinned=False)
```
**Agent message schema that Violit already understands:**
```python
{
"role": "assistant",
"content": "Final answer",
"content_format": "markdown", # optional: "markdown" or "text"
"phase": "thinking", # optional: thinking | running | done | error
"status_text": "Searching docs",# optional short live status
"summary": "Checked 3 files.", # optional agent summary
"trace": [ # optional step list
{"kind": "tool", "title": "search_workspace", "text": "Found 2 matches."}
],
"artifacts": [ # optional output cards
{"kind": "file", "title": "doc/llms.txt", "text": "Updated prompt guidance."}
],
"error": "", # optional agent error text
"files": [], # optional uploaded file list
"audio": None, # optional uploaded audio
}
```
`app.agent_history(...)` and primitive `app.agent_turn(...)` are designed around that schema. Reuse these field names instead of inventing a parallel protocol.
**When to use manual chat rendering instead:**
- Use manual rendering when you need per-turn control, custom placeholders, explicit background orchestration, or you want to surface attachments/audio before reply generation.
- Otherwise, prefer the built-in high-level chat widgets.
**Custom transcript widgets:**
```python
with app.chat_thread(height="60vh"):
with app.chat_message("assistant"):
app.markdown("Hello. Ask anything.")
with app.chat_message("user"):
app.markdown("Show me the latest report.")
```
Use `chat_thread()` and `chat_message()` when you want custom message composition but still want Violit's built-in chat styling. When rendering message dicts from state, prefer `app.render_chat_message_body(...)` so streamed chunks, attachments, and content format are handled consistently.
---
## 9. Multi-Page Navigation
```python
import violit as vl
app = vl.App(title="Multi-Page")
def home():
app.title("Home")
app.text("Welcome!")
def settings():
app.title("Settings")
theme = app.selectbox("Theme", ["light", "dark", "ocean"])
app.button("Apply", on_click=lambda: app.set_theme(theme.value))
# Sidebar with optional content
with app.sidebar:
app.markdown("## My App")
app.divider()
app.navigation([
vl.Page(home, title="Home", icon="house"),
vl.Page(settings, title="Settings", icon="gear"),
])
app.button("Go Home", on_click=lambda: app.switch_page("Home"))
app.page_link("Settings", label="Open Settings")
app.run()
```
---
## 10. Theme
```python
# Set at init
app = vl.App(theme="cyberpunk")
# Change at runtime
app.set_theme("ocean")
app.set_animation_mode("hard")
app.set_selection_mode(True)
app.set_primary_color("#2563eb")
# Available themes:
# dark, light, ocean, sunset, forest, dracula, monokai, nord,
# cyberpunk, terminal, vaporwave, blueprint, neo_brutalism,
# soft_neu, hand_drawn, win95, bauhaus, editorial, glass,
# pastel, retro, ant, bootstrap, material,
# violit_light, violit_light_jewel, violit_dark, rgb_gamer, ...
```
---
## 11. Styling (Tailwind-first)
Violit styling is currently **Tailwind-first**.
Start with `cls`, then use `style`, `add_css()`, `configure_widget()`, and `part_cls` when you need more control.
```python
app.text("Big", style="font-size: 2rem; font-weight: 800;")
app.button("Wide", cls="w-full rounded-full bg-sky-500 text-white", variant="primary")
app.card(cls="glass", style="padding: 2rem;")
# Global CSS
app.add_css("""
.glass {
background: rgba(255,255,255,0.85);
backdrop-filter: blur(16px);
}
""")
# Widget type defaults
app.configure_widget("button", cls="font-semibold rounded-full")
app.configure_widget("card", style="border-radius: 1rem;")
# Shadow DOM part styling
app.button(
"Save",
part_cls={"base": "shadow-lg rounded-full"},
)
```
**Styling rules of thumb:**
- `cls`: first choice for utilities and layout
- `style`: direct CSS values or CSS variables
- `configure_widget()`: defaults for a widget family
- `add_css()`: global reusable classes and `::part()` selectors
- `part_cls`: advanced Shadow DOM part overrides
For micro-adjustments after the main layout is already correct, `cls` is the preferred final step.
```python
app.selectbox("Mode", ["A", "B"], cls="mt-4")
app.selectbox("Mode", ["A", "B"], cls="translate-y-[10px]")
app.selectbox("Mode", ["A", "B"], cls="relative top-[8px]")
app.selectbox("Mode", ["A", "B"], cls="ml-[8%] w-[82%]")
```
Use these as intentional fine-tuning, not as a substitute for fixing the parent `columns(...)` / `container(...)` structure first.
## Background Tasks & Interval Timers
Use these instead of inventing your own thread/timer scaffolding unless you have a strong reason not to.
```python
import time
progress = app.state(0)
status = app.state("idle")
def work():
status.set("running")
for step in range(1, 6):
time.sleep(0.35)
progress.set(step * 20)
status.set("completed")
task = app.background(
work,
on_complete=lambda: app.toast("Finished", variant="success"),
on_error=lambda exc: app.toast(f"Error: {exc}", variant="danger"),
singleton=True,
)
timer = app.interval(
lambda: app.toast("tick", duration=800),
ms=5000,
condition=lambda: status.value == "running",
autostart=False,
)
app.button("Start job", on_click=task.start)
app.button("Pause timer", on_click=timer.pause)
app.button("Resume timer", on_click=timer.resume)
app.progress(progress)
```
**When to use which:**
- `app.background(...)`: long-running Python work
- `app.interval(...)`: periodic callbacks, polling, dashboards, timers
- `app.background(...)` supports `on_complete`, `on_error`, `singleton`, and returns a handle with `start()` / `cancel()` / `is_running`.
- `app.interval(...)` supports `condition=...`, `autostart=...`, and returns a handle with `pause()` / `resume()` / `stop()`.
---
## 12. Dialog
```python
@app.dialog("Confirm")
def confirm_dialog():
app.text("Are you sure?")
app.button("Yes", on_click=do_action)
app.button("Open Dialog", on_click=confirm_dialog)
```
Use `@app.dialog(...)` when you need a modal. Prefer it over hand-written modal HTML.
---
## 13. Conditional & Loop Rendering
```python
count = app.state(0)
# Conditional rendering (reactive)
app.If(
lambda: count.value > 5,
then=lambda: app.success("Big!"),
else_=lambda: app.info("Small"),
)
# Loop rendering (reactive)
items = app.state(["Apple", "Banana"])
app.For(
items,
render=lambda item: app.text(f"- {item}"),
empty=lambda: app.info("No items"),
)
```
---
## Common Mistakes to Avoid
```python
# ❌ WRONG: Using Streamlit's if-block pattern for buttons
if app.button("Click"): # Buttons don't return bool in Violit
do_something()
# ✅ CORRECT:
app.button("Click", on_click=do_something)
# ❌ WRONG: Forgetting app.run()
app.title("Hello")
# Script ends without app.run()
# ✅ CORRECT:
app.title("Hello")
app.run()
# ❌ WRONG: Passing .value to widgets (not reactive)
app.text(count.value)
# ✅ CORRECT: Pass State object directly
app.text(count)
# ❌ WRONG: Using f-string directly (not reactive)
app.text(f"Count: {count.value}")
# ✅ CORRECT: Use lambda or operator
app.text(lambda: f"Count: {count.value}")
app.text("Count: " + count)
# ❌ WRONG: Inventing a widget that does not exist
app.password_input("Password")
# ✅ CORRECT:
app.text_input("Password", type="password")
# ❌ WRONG: Assuming on_change gets a State object
app.text_input("Search", on_change=lambda s: print(s.value))
# ✅ CORRECT:
app.text_input("Search", on_change=lambda value: print(value))
# ❌ WRONG: Reassigning state variable
count = count.value + 1
# ✅ CORRECT:
count.set(count.value + 1)
```
---
## Complete Example: Dashboard
```python
import violit as vl