Spaces:
Running
Running
File size: 55,895 Bytes
d45098d 3d1636d |
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 |
Layout in Mesop is very similar to using HTML and CSS for styling, so you can use your expertise in HTML / CSS to layout Mesop apps. Note that there are some limitations and differences. You will need to use me.box as a replacement for HTML tags such as divs, span, header, aside, etc. The me.box component behaves most close to a div. Mesop also relies on inline styles. It also does not support all css styles yet, so you will need to check the me.Style API for what is supported. Here is an example of a layout in HTML/CSS. First the CSS: ```css <style> .container { display: flex; flex-direction: column; height: 100vh; } .header { background-color: #333; color: white; padding: 1rem; } .content { display: flex; flex: 1; } .sidebar { background-color: #f0f0f0; width: 200px; padding: 1rem; } .main { flex: 1; padding: 1rem; } </style> ``` Next the HTML: ```html <div class="container"> <div class="header"> <h1>My Website</h1> </div> <div class="content"> <div class="sidebar"> <h2>Sidebar</h2> <p>Sidebar content</p> </div> <div class="main"> <h2>Main Content</h2> <p>This is the main content area. You can add your page-specific content here.</p> </div> </div> </div> ``` In Mesop, this looks like: ```python import mesop as me STYLE_CONTAINER = me.Style( display="flex", flex_direction="column", height="100vh", ) STYLE_HEADER = me.Style( background="#333", color="white", padding=me.Padding.all("1rem"), ) STYLE_CONTENT = me.Style( display="flex", flex_grow=1, ) STYLE_SIDEBAR = me.Style( background="#f0f0f0", width="200px", padding=me.Padding.all("1rem"), ) STYLE_MAIN = me.Style( flex_grow=1, padding=me.Padding.all("1rem"), ) @me.page() def app(): with me.box(style=STYLE_CONTAINER): with me.box(style=STYLE_HEADER): me.text("My Website", type="headline-4") with me.box(style=STYLE_CONTENT): with me.box(style=STYLE_SIDEBAR): me.text("Sidebar", type="headline-5") me.text("Sidebar content") with me.box(style=STYLE_MAIN): me.text("Main Content", type="headline-5") me.text("This is the main content area. You can add your page-specific content here") ``` This section provides examples of Mesop code usage. Each example is wrapped in <example> tags. <example> import random import time from dataclasses import dataclass from typing import Literal import mesop as me Role = Literal["user", "assistant"] @dataclass(kw_only=True) class ChatMessage: """Chat message metadata.""" role: Role = "user" content: str = "" edited: bool = False @me.stateclass class State: input: str output: list[ChatMessage] in_progress: bool rewrite: str rewrite_message_index: int preview_rewrite: str preview_original: str modal_open: bool @me.page( security_policy=me.SecurityPolicy( allowed_iframe_parents=["https://google.github.io"] ), path="/llm_rewriter", title="LLM Rewriter", ) def page(): state = me.state(State) # Modal with me.box(style=_make_modal_background_style(state.modal_open)): with me.box(style=_STYLE_MODAL_CONTAINER): with me.box(style=_STYLE_MODAL_CONTENT): me.textarea( label="Rewrite", style=_STYLE_INPUT_WIDTH, value=state.rewrite, on_input=on_rewrite_input, ) with me.box(): me.button( "Submit Rewrite", color="primary", type="flat", on_click=on_click_submit_rewrite, ) me.button( "Cancel", on_click=on_click_cancel_rewrite, ) with me.box(style=_STYLE_PREVIEW_CONTAINER): with me.box(style=_STYLE_PREVIEW_ORIGINAL): me.text("Original Message", type="headline-6") me.markdown(state.preview_original) with me.box(style=_STYLE_PREVIEW_REWRITE): me.text("Preview Rewrite", type="headline-6") me.markdown(state.preview_rewrite) # Chat UI with me.box(style=_STYLE_APP_CONTAINER): with me.box(style=_make_style_chat_ui_container(bool(_TITLE))): me.text(_TITLE, type="headline-5", style=_STYLE_TITLE) with me.box(style=_STYLE_CHAT_BOX): for index, msg in enumerate(state.output): with me.box( style=_make_style_chat_bubble_wrapper(msg.role), key=f"msg-{index}", on_click=on_click_rewrite_msg, ): if msg.role == _ROLE_ASSISTANT: me.text( _display_username(_BOT_USER_DEFAULT, msg.edited), style=_STYLE_CHAT_BUBBLE_NAME, ) with me.box(style=_make_chat_bubble_style(msg.role, msg.edited)): if msg.role == _ROLE_USER: me.text(msg.content, style=_STYLE_CHAT_BUBBLE_PLAINTEXT) else: me.markdown(msg.content) with me.tooltip(message="Rewrite response"): me.icon(icon="edit_note") if state.in_progress: with me.box(key="scroll-to", style=me.Style(height=300)): pass with me.box(style=_STYLE_CHAT_INPUT_BOX): with me.box(style=me.Style(flex_grow=1)): me.input( label=_LABEL_INPUT, # Workaround: update key to clear input. key=f"input-{len(state.output)}", on_input=on_chat_input, on_enter=on_click_submit_chat_msg, style=_STYLE_CHAT_INPUT, ) with me.content_button( color="primary", type="flat", disabled=state.in_progress, on_click=on_click_submit_chat_msg, style=_STYLE_CHAT_BUTTON, ): me.icon( _LABEL_BUTTON_IN_PROGRESS if state.in_progress else _LABEL_BUTTON ) # Event Handlers def on_chat_input(e: me.InputEvent): """Capture chat text input.""" state = me.state(State) state.input = e.value def on_rewrite_input(e: me.InputEvent): """Capture rewrite text input.""" state = me.state(State) state.preview_rewrite = e.value def on_click_rewrite_msg(e: me.ClickEvent): """Shows rewrite modal when a message is clicked. Edit this function to persist rewritten messages. """ state = me.state(State) index = int(e.key.replace("msg-", "")) message = state.output[index] if message.role == _ROLE_USER or state.in_progress: return state.modal_open = True state.rewrite = message.content state.rewrite_message_index = index state.preview_original = message.content state.preview_rewrite = message.content def on_click_submit_rewrite(e: me.ClickEvent): """Submits rewrite message.""" state = me.state(State) state.modal_open = False message = state.output[state.rewrite_message_index] if message.content != state.preview_rewrite: message.content = state.preview_rewrite message.edited = True state.rewrite_message_index = 0 state.rewrite = "" state.preview_original = "" state.preview_rewrite = "" def on_click_cancel_rewrite(e: me.ClickEvent): """Hides rewrite modal.""" state = me.state(State) state.modal_open = False state.rewrite_message_index = 0 state.rewrite = "" state.preview_original = "" state.preview_rewrite = "" def on_click_submit_chat_msg(e: me.ClickEvent | me.InputEnterEvent): """Handles submitting a chat message.""" state = me.state(State) if state.in_progress or not state.input: return input = state.input state.input = "" yield output = state.output if output is None: output = [] output.append(ChatMessage(role=_ROLE_USER, content=input)) state.in_progress = True yield me.scroll_into_view(key="scroll-to") time.sleep(0.15) yield start_time = time.time() output_message = respond_to_chat(input, state.output) assistant_message = ChatMessage(role=_ROLE_ASSISTANT) output.append(assistant_message) state.output = output for content in output_message: assistant_message.content += content # TODO: 0.25 is an abitrary choice. In the future, consider making this adjustable. if (time.time() - start_time) >= 0.25: start_time = time.time() yield state.in_progress = False yield # Transform function for processing chat messages. def respond_to_chat(input: str, history: list[ChatMessage]): """Displays random canned text. Edit this function to process messages with a real chatbot/LLM. """ lines = [ ( "Lorem ipsum dolor sit amet, consectetur adipiscing elit, " "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." ), "Laoreet sit amet cursus sit amet dictum sit amet.", "At lectus urna duis convallis.", "A pellentesque sit amet porttitor eget.", "Mauris nunc congue nisi vitae suscipit tellus mauris a diam.", "Aliquet lectus proin nibh nisl condimentum id.", "Integer malesuada nunc vel risus commodo viverra maecenas accumsan.", "Tempor id eu nisl nunc mi.", "Id consectetur purus ut faucibus pulvinar.", "Mauris pharetra et ultrices neque ornare.", "Facilisis magna etiam tempor orci.", "Mauris pharetra et ultrices neque.", "Sit amet facilisis magna etiam tempor orci.", "Amet consectetur adipiscing elit pellentesque habitant morbi tristique.", "Egestas erat imperdiet sed euismod.", "Tincidunt praesent semper feugiat nibh sed pulvinar proin gravida.", "Habitant morbi tristique senectus et netus et malesuada.", ] for line in random.sample(lines, random.randint(3, len(lines) - 1)): yield line + " " # Constants _TITLE = "LLM Rewriter" _ROLE_USER = "user" _ROLE_ASSISTANT = "assistant" _BOT_USER_DEFAULT = "mesop-bot" # Styles _COLOR_BACKGROUND = "#f0f4f8" _COLOR_CHAT_BUBBLE_YOU = "#f2f2f2" _COLOR_CHAT_BUBBLE_BOT = "#ebf3ff" _COLOR_CHAT_BUUBBLE_EDITED = "#f2ebff" _DEFAULT_PADDING = me.Padding.all(20) _DEFAULT_BORDER_SIDE = me.BorderSide( width="1px", style="solid", color="#ececec" ) _LABEL_BUTTON = "send" _LABEL_BUTTON_IN_PROGRESS = "pending" _LABEL_INPUT = "Enter your prompt" _STYLE_INPUT_WIDTH = me.Style(width="100%") _STYLE_APP_CONTAINER = me.Style( background=_COLOR_BACKGROUND, display="grid", height="100vh", grid_template_columns="repeat(1, 1fr)", ) _STYLE_TITLE = me.Style(padding=me.Padding(left=10)) _STYLE_CHAT_BOX = me.Style( height="100%", overflow_y="scroll", padding=_DEFAULT_PADDING, margin=me.Margin(bottom=20), border_radius="10px", border=me.Border( left=_DEFAULT_BORDER_SIDE, right=_DEFAULT_BORDER_SIDE, top=_DEFAULT_BORDER_SIDE, bottom=_DEFAULT_BORDER_SIDE, ), ) _STYLE_CHAT_INPUT = me.Style(width="100%") _STYLE_CHAT_INPUT_BOX = me.Style( padding=me.Padding(top=30), display="flex", flex_direction="row" ) _STYLE_CHAT_BUTTON = me.Style(margin=me.Margin(top=8, left=8)) _STYLE_CHAT_BUBBLE_NAME = me.Style( font_weight="bold", font_size="12px", padding=me.Padding(left=15, right=15, bottom=5), ) _STYLE_CHAT_BUBBLE_PLAINTEXT = me.Style(margin=me.Margin.symmetric(vertical=15)) _STYLE_MODAL_CONTAINER = me.Style( background="#fff", margin=me.Margin.symmetric(vertical="0", horizontal="auto"), width="min(1024px, 100%)", box_sizing="content-box", height="100vh", overflow_y="scroll", box_shadow=("0 3px 1px -2px #0003, 0 2px 2px #00000024, 0 1px 5px #0000001f"), ) _STYLE_MODAL_CONTENT = me.Style(margin=me.Margin.all(20)) _STYLE_PREVIEW_CONTAINER = me.Style( display="grid", grid_template_columns="repeat(2, 1fr)", ) _STYLE_PREVIEW_ORIGINAL = me.Style(color="#777", padding=_DEFAULT_PADDING) _STYLE_PREVIEW_REWRITE = me.Style( background=_COLOR_CHAT_BUUBBLE_EDITED, padding=_DEFAULT_PADDING ) def _make_style_chat_ui_container(has_title: bool) -> me.Style: """Generates styles for chat UI container depending on if there is a title or not. Args: has_title: Whether the Chat UI is display a title or not. """ return me.Style( display="grid", grid_template_columns="repeat(1, 1fr)", grid_template_rows="1fr 14fr 1fr" if has_title else "5fr 1fr", margin=me.Margin.symmetric(vertical=0, horizontal="auto"), width="min(1024px, 100%)", height="100vh", background="#fff", box_shadow=( "0 3px 1px -2px #0003, 0 2px 2px #00000024, 0 1px 5px #0000001f" ), padding=me.Padding(top=20, left=20, right=20), ) def _make_style_chat_bubble_wrapper(role: Role) -> me.Style: """Generates styles for chat bubble position. Args: role: Chat bubble alignment depends on the role """ align_items = "end" if role == _ROLE_USER else "start" return me.Style( display="flex", flex_direction="column", align_items=align_items, ) def _make_chat_bubble_style(role: Role, edited: bool) -> me.Style: """Generates styles for chat bubble. Args: role: Chat bubble background color depends on the role edited: Whether chat message was edited or not. """ background = _COLOR_CHAT_BUBBLE_YOU if role == _ROLE_ASSISTANT: background = _COLOR_CHAT_BUBBLE_BOT if edited: background = _COLOR_CHAT_BUUBBLE_EDITED return me.Style( width="80%", font_size="13px", background=background, border_radius="15px", padding=me.Padding(right=15, left=15, bottom=3), margin=me.Margin(bottom=10), border=me.Border( left=_DEFAULT_BORDER_SIDE, right=_DEFAULT_BORDER_SIDE, top=_DEFAULT_BORDER_SIDE, bottom=_DEFAULT_BORDER_SIDE, ), ) def _make_modal_background_style(modal_open: bool) -> me.Style: """Makes style for modal background. Args: modal_open: Whether the modal is open. """ return me.Style( display="block" if modal_open else "none", position="fixed", z_index=1000, width="100%", height="100%", overflow_x="auto", overflow_y="auto", background="rgba(0,0,0,0.4)", ) def _display_username(username: str, edited: bool = False) -> str: """Displays the username Args: username: Name of the user edited: Whether the message has been edited. """ edited_text = " (edited)" if edited else "" return username + edited_text <example> <example> import random import time from typing import Callable import mesop as me _TEMPERATURE_MIN = 0.0 _TEMPERATURE_MAX = 2.0 _TOKEN_LIMIT_MIN = 1 _TOKEN_LIMIT_MAX = 8192 @me.stateclass class State: title: str = "LLM Playground" # Prompt / Response input: str response: str # Tab open/close prompt_tab: bool = True response_tab: bool = True # Model configs selected_model: str = "gemini-1.5" selected_region: str = "us-east4" temperature: float = 1.0 temperature_for_input: float = 1.0 token_limit: int = _TOKEN_LIMIT_MAX token_limit_for_input: int = _TOKEN_LIMIT_MAX stop_sequence: str = "" stop_sequences: list[str] # Modal modal_open: bool = False # Workaround for clearing inputs clear_prompt_count: int = 0 clear_sequence_count: int = 0 @me.page( security_policy=me.SecurityPolicy( allowed_iframe_parents=["https://google.github.io"] ), path="/llm_playground", title="LLM Playground", ) def page(): state = me.state(State) # Modal with modal(modal_open=state.modal_open): me.text("Get code", type="headline-5") if "gemini" in state.selected_model: me.text( "Use the following code in your application to request a model response." ) with me.box(style=_STYLE_CODE_BOX): me.markdown( _GEMINI_CODE_TEXT.format( content=state.input.replace('"', '\\"'), model=state.selected_model, region=state.selected_region, stop_sequences=make_stop_sequence_str(state.stop_sequences), token_limit=state.token_limit, temperature=state.temperature, ) ) else: me.text( "You can use the following code to start integrating your current prompt and settings into your application." ) with me.box(style=_STYLE_CODE_BOX): me.markdown( _GPT_CODE_TEXT.format( content=state.input.replace('"', '\\"').replace("\n", "\\n"), model=state.selected_model, stop_sequences=make_stop_sequence_str(state.stop_sequences), token_limit=state.token_limit, temperature=state.temperature, ) ) me.button(label="Close", type="raised", on_click=on_click_modal) # Main content with me.box(style=_STYLE_CONTAINER): # Main Header with me.box(style=_STYLE_MAIN_HEADER): with me.box(style=_STYLE_TITLE_BOX): me.text( state.title, type="headline-6", style=me.Style(line_height="24px", margin=me.Margin(bottom=0)), ) # Toolbar Header with me.box(style=_STYLE_CONFIG_HEADER): icon_button( icon="code", tooltip="Code", label="CODE", on_click=on_click_show_code ) # Main Content with me.box(style=_STYLE_MAIN_COLUMN): # Prompt Tab with tab_box(header="Prompt", key="prompt_tab"): me.textarea( label="Write your prompt here, insert media and then click Submit", # Workaround: update key to clear input. key=f"prompt-{state.clear_prompt_count}", on_input=on_prompt_input, style=_STYLE_INPUT_WIDTH, ) me.button(label="Submit", type="flat", on_click=on_click_submit) me.button(label="Clear", on_click=on_click_clear) # Response Tab with tab_box(header="Response", key="response_tab"): if state.response: me.markdown(state.response) else: me.markdown( "The model will generate a response after you click Submit." ) # LLM Config with me.box(style=_STYLE_CONFIG_COLUMN): me.select( options=[ me.SelectOption(label="Gemini 1.5", value="gemini-1.5"), me.SelectOption(label="Chat-GPT Turbo", value="gpt-3.5-turbo"), ], label="Model", style=_STYLE_INPUT_WIDTH, on_selection_change=on_model_select, value=state.selected_model, ) if "gemini" in state.selected_model: me.select( options=[ me.SelectOption(label="us-central1 (Iowa)", value="us-central1"), me.SelectOption( label="us-east4 (North Virginia)", value="us-east4" ), ], label="Region", style=_STYLE_INPUT_WIDTH, on_selection_change=on_region_select, value=state.selected_region, ) me.text("Temperature", style=_STYLE_SLIDER_LABEL) with me.box(style=_STYLE_SLIDER_INPUT_BOX): with me.box(style=_STYLE_SLIDER_WRAP): me.slider( min=_TEMPERATURE_MIN, max=_TEMPERATURE_MAX, step=0.1, style=_STYLE_SLIDER, on_value_change=on_slider_temperature, value=state.temperature, ) me.input( style=_STYLE_SLIDER_INPUT, value=str(state.temperature_for_input), on_input=on_input_temperature, ) me.text("Output Token Limit", style=_STYLE_SLIDER_LABEL) with me.box(style=_STYLE_SLIDER_INPUT_BOX): with me.box(style=_STYLE_SLIDER_WRAP): me.slider( min=_TOKEN_LIMIT_MIN, max=_TOKEN_LIMIT_MAX, style=_STYLE_SLIDER, on_value_change=on_slider_token_limit, value=state.token_limit, ) me.input( style=_STYLE_SLIDER_INPUT, value=str(state.token_limit_for_input), on_input=on_input_token_limit, ) with me.box(style=_STYLE_STOP_SEQUENCE_BOX): with me.box(style=_STYLE_STOP_SEQUENCE_WRAP): me.input( label="Add stop sequence", style=_STYLE_INPUT_WIDTH, on_input=on_stop_sequence_input, # Workaround: update key to clear input. key=f"input-sequence-{state.clear_sequence_count}", ) with me.content_button( style=me.Style(margin=me.Margin(left=10)), on_click=on_click_add_stop_sequence, ): with me.tooltip(message="Add stop Sequence"): me.icon(icon="add_circle") # Stop sequence "chips" for index, sequence in enumerate(state.stop_sequences): me.button( key=f"sequence-{index}", label=sequence, on_click=on_click_remove_stop_sequence, type="raised", style=_STYLE_STOP_SEQUENCE_CHIP, ) # HELPER COMPONENTS @me.component def icon_button(*, icon: str, label: str, tooltip: str, on_click: Callable): """Icon button with text and tooltip.""" with me.content_button(on_click=on_click): with me.tooltip(message=tooltip): with me.box(style=me.Style(display="flex")): me.icon(icon=icon) me.text( label, style=me.Style(line_height="24px", margin=me.Margin(left=5)) ) @me.content_component def tab_box(*, header: str, key: str): """Collapsible tab box""" state = me.state(State) tab_open = getattr(state, key) with me.box(style=me.Style(width="100%", margin=me.Margin(bottom=20))): # Tab Header with me.box( key=key, on_click=on_click_tab_header, style=me.Style(padding=_DEFAULT_PADDING, border=_DEFAULT_BORDER), ): with me.box(style=me.Style(display="flex")): me.icon( icon="keyboard_arrow_down" if tab_open else "keyboard_arrow_right" ) me.text( header, style=me.Style( line_height="24px", margin=me.Margin(left=5), font_weight="bold" ), ) # Tab Content with me.box( style=me.Style( padding=_DEFAULT_PADDING, border=_DEFAULT_BORDER, display="block" if tab_open else "none", ) ): me.slot() @me.content_component def modal(modal_open: bool): """Basic modal box.""" with me.box(style=_make_modal_background_style(modal_open)): with me.box(style=_STYLE_MODAL_CONTAINER): with me.box(style=_STYLE_MODAL_CONTENT): me.slot() # EVENT HANDLERS def on_click_clear(e: me.ClickEvent): """Click event for clearing prompt text.""" state = me.state(State) state.clear_prompt_count += 1 state.input = "" state.response = "" def on_prompt_input(e: me.InputEvent): """Capture prompt input.""" state = me.state(State) state.input = e.value def on_model_select(e: me.SelectSelectionChangeEvent): """Event to select model.""" state = me.state(State) state.selected_model = e.value def on_region_select(e: me.SelectSelectionChangeEvent): """Event to select GCP region (Gemini models only).""" state = me.state(State) state.selected_region = e.value def on_slider_temperature(e: me.SliderValueChangeEvent): """Event to adjust temperature slider value.""" state = me.state(State) state.temperature = float(e.value) state.temperature_for_input = state.temperature def on_input_temperature(e: me.InputEvent): """Event to adjust temperature slider value by input.""" state = me.state(State) try: temperature = float(e.value) if _TEMPERATURE_MIN <= temperature <= _TEMPERATURE_MAX: state.temperature = temperature except ValueError: pass def on_slider_token_limit(e: me.SliderValueChangeEvent): """Event to adjust token limit slider value.""" state = me.state(State) state.token_limit = int(e.value) state.token_limit_for_input = state.token_limit def on_input_token_limit(e: me.InputEvent): """Event to adjust token limit slider value by input.""" state = me.state(State) try: token_limit = int(e.value) if _TOKEN_LIMIT_MIN <= token_limit <= _TOKEN_LIMIT_MAX: state.token_limit = token_limit except ValueError: pass def on_stop_sequence_input(e: me.InputEvent): """Capture stop sequence input.""" state = me.state(State) state.stop_sequence = e.value def on_click_add_stop_sequence(e: me.ClickEvent): """Save stop sequence. Will create "chip" for the sequence in the input.""" state = me.state(State) if state.stop_sequence: state.stop_sequences.append(state.stop_sequence) state.clear_sequence_count += 1 def on_click_remove_stop_sequence(e: me.ClickEvent): """Click event that removes the stop sequence that was clicked.""" state = me.state(State) index = int(e.key.replace("sequence-", "")) del state.stop_sequences[index] def on_click_tab_header(e: me.ClickEvent): """Open and closes tab content.""" state = me.state(State) setattr(state, e.key, not getattr(state, e.key)) def on_click_show_code(e: me.ClickEvent): """Opens modal to show generated code for the given model configuration.""" state = me.state(State) state.modal_open = True def on_click_modal(e: me.ClickEvent): """Allows modal to be closed.""" state = me.state(State) if state.modal_open: state.modal_open = False def on_click_submit(e: me.ClickEvent): """Submits prompt to test model configuration. This example returns canned text. A real implementation would call APIs against the given configuration. """ state = me.state(State) for line in transform(state.input): state.response += line yield def transform(input: str): """Transform function that returns canned responses.""" for line in random.sample(LINES, random.randint(3, len(LINES) - 1)): time.sleep(0.3) yield line + " " LINES = [ "Mesop is a Python-based UI framework designed to simplify web UI development for engineers without frontend experience.", "It leverages the power of the Angular web framework and Angular Material components, allowing rapid construction of web demos and internal tools.", "With Mesop, developers can enjoy a fast build-edit-refresh loop thanks to its hot reload feature, making UI tweaks and component integration seamless.", "Deployment is straightforward, utilizing standard HTTP technologies.", "Mesop's component library aims for comprehensive Angular Material component coverage, enhancing UI flexibility and composability.", "It supports custom components for specific use cases, ensuring developers can extend its capabilities to fit their unique requirements.", "Mesop's roadmap includes expanding its component library and simplifying the onboarding processs.", ] # HELPERS _GEMINI_CODE_TEXT = """ ```python import base64 import vertexai from vertexai.generative_models import GenerativeModel, Part, FinishReason import vertexai.preview.generative_models as generative_models def generate(): vertexai.init(project="<YOUR-PROJECT-ID>", location="{region}") model = GenerativeModel("{model}") responses = model.generate_content( [\"\"\"{content}\"\"\"], generation_config=generation_config, safety_settings=safety_settings, stream=True, ) for response in responses: print(response.text, end="") generation_config = {{ "max_output_tokens": {token_limit}, "stop_sequences": [{stop_sequences}], "temperature": {temperature}, "top_p": 0.95, }} safety_settings = {{ generative_models.HarmCategory.HARM_CATEGORY_HATE_SPEECH: generative_models.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE, generative_models.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: generative_models.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE, generative_models.HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: generative_models.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE, generative_models.HarmCategory.HARM_CATEGORY_HARASSMENT: generative_models.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE, }} generate() ``` """.strip() _GPT_CODE_TEXT = """ ```python from openai import OpenAI client = OpenAI() response = client.chat.completions.create( model="{model}", messages=[ {{ "role": "user", "content": "{content}" }} ], temperature={temperature}, max_tokens={token_limit}, top_p=1, frequency_penalty=0, presence_penalty=0, stop=[{stop_sequences}] ) ``` """.strip() def make_stop_sequence_str(stop_sequences: list[str]) -> str: """Formats stop sequences for code output (list of strings).""" return ",".join(map(lambda s: f'"{s}"', stop_sequences)) # STYLES def _make_modal_background_style(modal_open: bool) -> me.Style: """Makes style for modal background. Args: modal_open: Whether the modal is open. """ return me.Style( display="block" if modal_open else "none", position="fixed", z_index=1000, width="100%", height="100%", overflow_x="auto", overflow_y="auto", background="rgba(0,0,0,0.4)", ) _DEFAULT_PADDING = me.Padding.all(15) _DEFAULT_BORDER = me.Border.all( me.BorderSide(color="#e0e0e0", width=1, style="solid") ) _STYLE_INPUT_WIDTH = me.Style(width="100%") _STYLE_SLIDER_INPUT_BOX = me.Style(display="flex", flex_wrap="wrap") _STYLE_SLIDER_WRAP = me.Style(flex_grow=1) _STYLE_SLIDER_LABEL = me.Style(padding=me.Padding(bottom=10)) _STYLE_SLIDER = me.Style(width="90%") _STYLE_SLIDER_INPUT = me.Style(width=75) _STYLE_STOP_SEQUENCE_BOX = me.Style(display="flex") _STYLE_STOP_SEQUENCE_WRAP = me.Style(flex_grow=1) _STYLE_CONTAINER = me.Style( display="grid", grid_template_columns="5fr 2fr", grid_template_rows="auto 5fr", height="100vh", ) _STYLE_MAIN_HEADER = me.Style( border=_DEFAULT_BORDER, padding=me.Padding.all(15) ) _STYLE_MAIN_COLUMN = me.Style( border=_DEFAULT_BORDER, padding=me.Padding.all(15), overflow_y="scroll", ) _STYLE_CONFIG_COLUMN = me.Style( border=_DEFAULT_BORDER, padding=me.Padding.all(15), overflow_y="scroll", ) _STYLE_TITLE_BOX = me.Style(display="inline-block") _STYLE_CONFIG_HEADER = me.Style( border=_DEFAULT_BORDER, padding=me.Padding.all(10) ) _STYLE_STOP_SEQUENCE_CHIP = me.Style(margin=me.Margin.all(3)) _STYLE_MODAL_CONTAINER = me.Style( background="#fff", margin=me.Margin.symmetric(vertical="0", horizontal="auto"), width="min(1024px, 100%)", box_sizing="content-box", height="100vh", overflow_y="scroll", box_shadow=("0 3px 1px -2px #0003, 0 2px 2px #00000024, 0 1px 5px #0000001f"), ) _STYLE_MODAL_CONTENT = me.Style(margin=me.Margin.all(30)) _STYLE_CODE_BOX = me.Style( font_size=13, margin=me.Margin.symmetric(vertical=10, horizontal=0), padding=me.Padding.all(10), border=me.Border.all(me.BorderSide(color="#e0e0e0", width=1, style="solid")), ) <example> <example> import time from dataclasses import dataclass from typing import Callable, Generator, Literal import mesop as me Role = Literal["user", "assistant"] _ROLE_USER = "user" _ROLE_ASSISTANT = "assistant" _BOT_USER_DEFAULT = "mesop-bot" _COLOR_BACKGROUND = me.theme_var("background") _COLOR_CHAT_BUBBLE_YOU = me.theme_var("surface-container-low") _COLOR_CHAT_BUBBLE_BOT = me.theme_var("secondary-container") _DEFAULT_PADDING = me.Padding.all(20) _DEFAULT_BORDER_SIDE = me.BorderSide( width="1px", style="solid", color=me.theme_var("secondary-fixed") ) _LABEL_BUTTON = "send" _LABEL_BUTTON_IN_PROGRESS = "pending" _LABEL_INPUT = "Enter your prompt" _STYLE_APP_CONTAINER = me.Style( background=_COLOR_BACKGROUND, display="grid", height="100vh", grid_template_columns="repeat(1, 1fr)", ) _STYLE_TITLE = me.Style(padding=me.Padding(left=10)) _STYLE_CHAT_BOX = me.Style( height="100%", overflow_y="scroll", padding=_DEFAULT_PADDING, margin=me.Margin(bottom=20), border_radius="10px", border=me.Border( left=_DEFAULT_BORDER_SIDE, right=_DEFAULT_BORDER_SIDE, top=_DEFAULT_BORDER_SIDE, bottom=_DEFAULT_BORDER_SIDE, ), ) _STYLE_CHAT_INPUT = me.Style(width="100%") _STYLE_CHAT_INPUT_BOX = me.Style( padding=me.Padding(top=30), display="flex", flex_direction="row" ) _STYLE_CHAT_BUTTON = me.Style(margin=me.Margin(top=8, left=8)) _STYLE_CHAT_BUBBLE_NAME = me.Style( font_weight="bold", font_size="13px", padding=me.Padding(left=15, right=15, bottom=5), ) _STYLE_CHAT_BUBBLE_PLAINTEXT = me.Style(margin=me.Margin.symmetric(vertical=15)) def _make_style_chat_ui_container(has_title: bool) -> me.Style: """Generates styles for chat UI container depending on if there is a title or not. Args: has_title: Whether the Chat UI is display a title or not. """ return me.Style( display="grid", grid_template_columns="repeat(1, 1fr)", grid_template_rows="1fr 14fr 1fr" if has_title else "5fr 1fr", margin=me.Margin.symmetric(vertical=0, horizontal="auto"), width="min(1024px, 100%)", height="100vh", background=_COLOR_BACKGROUND, box_shadow=( "0 3px 1px -2px #0003, 0 2px 2px #00000024, 0 1px 5px #0000001f" ), padding=me.Padding(top=20, left=20, right=20), ) def _make_style_chat_bubble_wrapper(role: Role) -> me.Style: """Generates styles for chat bubble position. Args: role: Chat bubble alignment depends on the role """ align_items = "end" if role == _ROLE_USER else "start" return me.Style( display="flex", flex_direction="column", align_items=align_items, ) def _make_chat_bubble_style(role: Role) -> me.Style: """Generates styles for chat bubble. Args: role: Chat bubble background color depends on the role """ background = ( _COLOR_CHAT_BUBBLE_YOU if role == _ROLE_USER else _COLOR_CHAT_BUBBLE_BOT ) return me.Style( width="80%", font_size="16px", line_height="1.5", background=background, border_radius="15px", padding=me.Padding(right=15, left=15, bottom=3), margin=me.Margin(bottom=10), border=me.Border( left=_DEFAULT_BORDER_SIDE, right=_DEFAULT_BORDER_SIDE, top=_DEFAULT_BORDER_SIDE, bottom=_DEFAULT_BORDER_SIDE, ), ) @dataclass(kw_only=True) class ChatMessage: """Chat message metadata.""" role: Role = "user" content: str = "" @me.stateclass class State: input: str output: list[ChatMessage] in_progress: bool = False def on_blur(e: me.InputBlurEvent): state = me.state(State) state.input = e.value def chat( transform: Callable[ [str, list[ChatMessage]], Generator[str, None, None] | str ], *, title: str | None = None, bot_user: str = _BOT_USER_DEFAULT, ): """Creates a simple chat UI which takes in a prompt and chat history and returns a response to the prompt. This function creates event handlers for text input and output operations using the provided function `transform` to process the input and generate the output. Args: transform: Function that takes in a prompt and chat history and returns a response to the prompt. title: Headline text to display at the top of the UI. bot_user: Name of your bot / assistant. """ state = me.state(State) def on_click_submit(e: me.ClickEvent): yield from submit() def on_input_enter(e: me.InputEnterEvent): state = me.state(State) state.input = e.value yield from submit() me.focus_component(key=f"input-{len(state.output)}") yield def submit(): state = me.state(State) if state.in_progress or not state.input: return input = state.input state.input = "" yield output = state.output if output is None: output = [] output.append(ChatMessage(role=_ROLE_USER, content=input)) state.in_progress = True yield me.scroll_into_view(key="scroll-to") time.sleep(0.15) yield start_time = time.time() output_message = transform(input, state.output) assistant_message = ChatMessage(role=_ROLE_ASSISTANT) output.append(assistant_message) state.output = output for content in output_message: assistant_message.content += content # TODO: 0.25 is an abitrary choice. In the future, consider making this adjustable. if (time.time() - start_time) >= 0.25: start_time = time.time() yield state.in_progress = False me.focus_component(key=f"input-{len(state.output)}") yield def toggle_theme(e: me.ClickEvent): if me.theme_brightness() == "light": me.set_theme_mode("dark") else: me.set_theme_mode("light") with me.box(style=_STYLE_APP_CONTAINER): with me.content_button( type="icon", style=me.Style(position="absolute", right=4, top=8), on_click=toggle_theme, ): me.icon("light_mode" if me.theme_brightness() == "dark" else "dark_mode") with me.box(style=_make_style_chat_ui_container(bool(title))): if title: me.text(title, type="headline-5", style=_STYLE_TITLE) with me.box(style=_STYLE_CHAT_BOX): for msg in state.output: with me.box(style=_make_style_chat_bubble_wrapper(msg.role)): if msg.role == _ROLE_ASSISTANT: me.text(bot_user, style=_STYLE_CHAT_BUBBLE_NAME) with me.box(style=_make_chat_bubble_style(msg.role)): if msg.role == _ROLE_USER: me.text(msg.content, style=_STYLE_CHAT_BUBBLE_PLAINTEXT) else: me.markdown(msg.content) if state.in_progress: with me.box(key="scroll-to", style=me.Style(height=300)): pass with me.box(style=_STYLE_CHAT_INPUT_BOX): with me.box(style=me.Style(flex_grow=1)): me.input( label=_LABEL_INPUT, # Workaround: update key to clear input. key=f"input-{len(state.output)}", on_blur=on_blur, on_enter=on_input_enter, style=_STYLE_CHAT_INPUT, ) with me.content_button( color="primary", type="flat", disabled=state.in_progress, on_click=on_click_submit, style=_STYLE_CHAT_BUTTON, ): me.icon( _LABEL_BUTTON_IN_PROGRESS if state.in_progress else _LABEL_BUTTON ) <example> <example> import types from typing import Callable, Generator, Literal, cast import mesop as me @me.stateclass class State: input: str output: str textarea_key: int def text_io( transform: Callable[[str], Generator[str, None, None] | str], *, title: str | None = None, transform_mode: Literal["append", "replace"] = "replace", ): """Deprecated: Use `text_to_text` instead which provides the same functionality with better default settings. This function creates event handlers for text input and output operations using the provided transform function to process the input and generate the output. Args: transform: Function that takes in a string input and either returns or yields a string output. title: Headline text to display at the top of the UI transform_mode: Specifies how the output should be updated when yielding an output using a generator. - "append": Concatenates each new piece of text to the existing output. - "replace": Replaces the existing output with each new piece of text. """ print( "\033[93m[warning]\033[0m text_io is deprecated, use text_to_text instead" ) text_to_text(transform=transform, title=title, transform_mode=transform_mode) def text_to_text( transform: Callable[[str], Generator[str, None, None] | str], *, title: str | None = None, transform_mode: Literal["append", "replace"] = "append", ): """Creates a simple UI which takes in a text input and returns a text output. This function creates event handlers for text input and output operations using the provided transform function to process the input and generate the output. Args: transform: Function that takes in a string input and either returns or yields a string output. title: Headline text to display at the top of the UI transform_mode: Specifies how the output should be updated when yielding an output using a generator. - "append": Concatenates each new piece of text to the existing output. - "replace": Replaces the existing output with each new piece of text. """ def on_input(e: me.InputEvent): state = me.state(State) state.input = e.value def on_click_generate(e: me.ClickEvent): state = me.state(State) output = transform(state.input) if isinstance(output, types.GeneratorType): for val in output: if transform_mode == "append": state.output += val elif transform_mode == "replace": state.output = val else: raise ValueError(f"Unsupported transform_mode: {transform_mode}") yield else: # `output` is a str, however type inference doesn't # work w/ generator's unusual ininstance check. state.output = cast(str, output) yield def on_click_clear(e: me.ClickEvent): state = me.state(State) state.input = "" state.textarea_key += 1 with me.box( style=me.Style( background="#f0f4f8", height="100%", ) ): with me.box( style=me.Style( background="#f0f4f8", padding=me.Padding(top=24, left=24, right=24, bottom=24), display="flex", flex_direction="column", ) ): if title: me.text(title, type="headline-5") with me.box( style=me.Style( margin=me.Margin(left="auto", right="auto"), width="min(1024px, 100%)", gap="24px", flex_grow=1, display="flex", flex_wrap="wrap", ) ): box_style = me.Style( flex_basis="max(480px, calc(50% - 48px))", background="#fff", border_radius=12, box_shadow="0 3px 1px -2px #0003, 0 2px 2px #00000024, 0 1px 5px #0000001f", padding=me.Padding(top=16, left=16, right=16, bottom=16), display="flex", flex_direction="column", ) with me.box(style=box_style): me.text("Input", style=me.Style(font_weight=500)) me.box(style=me.Style(height=16)) me.textarea( key=str(me.state(State).textarea_key), on_input=on_input, rows=5, autosize=True, max_rows=15, style=me.Style(width="100%"), ) me.box(style=me.Style(height=12)) with me.box( style=me.Style(display="flex", justify_content="space-between") ): me.button( "Clear", color="primary", type="stroked", on_click=on_click_clear ) me.button( "Generate", color="primary", type="flat", on_click=on_click_generate, ) with me.box(style=box_style): me.text("Output", style=me.Style(font_weight=500)) me.markdown(me.state(State).output) <example> <example> from dataclasses import dataclass import mesop as me CARD_WIDTH = "320px" @dataclass class Resource: title: str description: str github_url: str github_username: str img_url: str app_url: str | None = None @dataclass class Section: name: str resources: list[Resource] icon: str SECTIONS = [ Section( name="Featured", icon="star", resources=[ Resource( title="Mesop Duo Chat", description="Chat with multiple models at once", github_url="https://github.com/wwwillchen/mesop-duo-chat", github_username="wwwillchen", app_url="https://huggingface.co/spaces/wwwillchen/mesop-duo-chat", img_url="https://github.com/user-attachments/assets/107afb9c-f08c-4f27-bd00-e122415c069e", ), Resource( title="Mesop Prompt Tuner", description="Prompt tuning app heavily inspired by Anthropic Console Workbench.", app_url="https://huggingface.co/spaces/richard-to/mesop-prompt-tuner", img_url="https://github.com/user-attachments/assets/2ec6cbfb-c28b-4f60-98f9-34bfca1f6938", github_url="https://github.com/richard-to/mesop-prompt-tuner", github_username="richard-to", ), Resource( title="Meta Llama Agentic System", description="Agentic components of the Llama Stack APIs. Chat UI in Mesop.", img_url="https://github.com/meta-llama/llama-agentic-system/raw/main/demo.png", github_url="https://github.com/meta-llama/llama-agentic-system", github_username="meta-llama", ), ], ), Section( name="Apps", icon="computer", resources=[ Resource( title="Mesop App Maker", description="Generate apps with Mesop using LLMs", img_url="https://github.com/user-attachments/assets/1a826d44-c87b-4c79-aeaf-29bc8da3b1c0", github_url="https://github.com/richard-to/mesop-app-maker", github_username="richard-to", ), Resource( title="Mesop Jeopardy", description="A simple jeopardy game built using Mesop", img_url="https://github.com/richard-to/mesop-jeopardy/assets/539889/bc27447d-129f-47ae-b0b1-8f5c546762ed", github_url="https://github.com/richard-to/mesop-jeopardy", github_username="richard-to", ), ], ), Section( name="Web components", icon="code_blocks", resources=[ Resource( title="Mesop Markmap", description="Mesop web component for the Markmap library", img_url="https://github.com/user-attachments/assets/6aa40ca3-d98a-42b2-adea-3f49b134445d", github_url="https://github.com/lianggecm/mesop_markmap", app_url="https://colab.research.google.com/drive/17gXlsXPDeo6hcFl1oOyrZ58FTozviN45?usp=sharing", github_username="lianggecm", ), ], ), Section( name="Notebooks", icon="description", resources=[ Resource( title="Mesop Getting Started Colab", description="Get started with Mesop in Colab", img_url="https://github.com/user-attachments/assets/37efbe69-ac97-4d26-8fda-d1b7b2b4976a", github_url="https://github.com/google/mesop/blob/main/notebooks/mesop_colab_getting_started.ipynb", app_url="https://colab.research.google.com/github/google/mesop/blob/main/notebooks/mesop_colab_getting_started.ipynb", github_username="google", ), Resource( title="Gemma with Mesop Notebook", description="Use Gemma with Mesop in Colab", img_url="https://github.com/user-attachments/assets/a52ebf01-7f24-469b-9ad9-b271fdb19e37", github_url="https://github.com/google-gemini/gemma-cookbook/blob/main/Gemma/Integrate_with_Mesop.ipynb", app_url="https://colab.research.google.com/github/google-gemini/gemma-cookbook/blob/main/Gemma/Integrate_with_Mesop.ipynb", github_username="google-gemini", ), Resource( title="PaliGemma with Mesop Notebook", description="Use PaliGemma with Mesop in Colab", img_url="https://github.com/user-attachments/assets/8cb456a1-f7be-4187-9a3f-f6b48bde73e9", github_url="https://github.com/google-gemini/gemma-cookbook/blob/main/PaliGemma/Integrate_PaliGemma_with_Mesop.ipynb", app_url="https://colab.research.google.com/github/google-gemini/gemma-cookbook/blob/main/PaliGemma/Integrate_PaliGemma_with_Mesop.ipynb", github_username="google-gemini", ), ], ), ] def scroll_to_section(e: me.ClickEvent): me.scroll_into_view(key="section-" + e.key) me.state(State).sidenav_menu_open = False def toggle_theme(e: me.ClickEvent): if me.theme_brightness() == "light": me.set_theme_mode("dark") else: me.set_theme_mode("light") def on_load(e: me.LoadEvent): me.set_theme_mode("system") @me.stateclass class State: sidenav_menu_open: bool def toggle_menu_button(e: me.ClickEvent): s = me.state(State) s.sidenav_menu_open = not s.sidenav_menu_open def is_mobile(): return me.viewport_size().width < 640 @me.page( title="Mesop Showcase", on_load=on_load, security_policy=me.SecurityPolicy( allowed_iframe_parents=["https://huggingface.co"], ), ) def page(): with me.box(style=me.Style(display="flex", height="100%")): if is_mobile(): with me.content_button( type="icon", style=me.Style(top=6, left=8, position="absolute", z_index=9), on_click=toggle_menu_button, ): me.icon("menu") with me.sidenav( opened=me.state(State).sidenav_menu_open, style=me.Style( background=me.theme_var("surface-container-low"), ), ): sidenav() else: sidenav() with me.box( style=me.Style( background=me.theme_var("surface-container-low"), display="flex", flex_direction="column", flex_grow=1, ) ): with me.box( style=me.Style( height=240, width="100%", padding=me.Padding.all(16), display="flex", align_items="center", ), ): me.text( "Mesop Showcase", style=me.Style( color=me.theme_var("on-background"), font_size=22, font_weight=500, letter_spacing="0.8px", padding=me.Padding(left=36) if is_mobile() else None, ), ) with me.content_button( type="icon", style=me.Style(position="absolute", right=4, top=8), on_click=toggle_theme, ): me.icon( "light_mode" if me.theme_brightness() == "dark" else "dark_mode" ) with me.box( style=me.Style( background=me.theme_var("background"), flex_grow=1, padding=me.Padding( left=32, right=32, bottom=64, ), border_radius=16, overflow_y="auto", ) ): for section in SECTIONS: me.text( section.name, style=me.Style( font_size=18, font_weight=500, padding=me.Padding(top=32, bottom=16), ), key="section-" + section.name, ) with me.box( style=me.Style( display="grid", grid_template_columns=f"repeat(auto-fit, minmax({CARD_WIDTH}, 1fr))", gap=24, margin=me.Margin( bottom=24, ), ) ): for resource in section.resources: card(resource) with me.box( on_click=lambda e: me.navigate( "https://github.com/google/mesop/issues/new/choose" ), style=me.Style( cursor="pointer", max_width=300, background=me.theme_var("surface-container-lowest"), box_shadow="0 2px 4px rgba(0, 0, 0, 0.1)", # margin=me.Margin.symmetric(horizontal="auto"), display="flex", justify_content="center", align_items="center", border_radius=16, height=120, ), ): me.icon( "add_circle", style=me.Style( color=me.theme_var("primary"), font_size=24, margin=me.Margin(right=4, top=2), ), ) me.link( text="Submit your showcase", url="https://github.com/google/mesop/issues/new/choose", style=me.Style( font_size=24, color=me.theme_var("on-background"), text_decoration="none", ), ) def sidenav(): with me.box( style=me.Style( width=216, height="100%", background=me.theme_var("surface-container-low"), padding=me.Padding.all(16), ) ): with me.box( style=me.Style( display="flex", flex_direction="column", margin=me.Margin(top=48) ) ): with me.content_button( type="icon", on_click=lambda e: me.navigate("https://google.github.io/mesop/"), ): with me.box( style=me.Style(display="flex", align_items="center", gap=12) ): me.icon("home") me.text( "Home", style=me.Style( font_size=16, margin=me.Margin(bottom=4), ), ) with me.content_button( type="icon", on_click=lambda e: me.navigate("https://google.github.io/mesop/demo/"), ): with me.box( style=me.Style( display="flex", align_items="center", gap=8, ) ): me.icon("gallery_thumbnail") me.text( "Demos", style=me.Style( font_size=16, margin=me.Margin(bottom=6, left=4), ), ) with me.box( style=me.Style( padding=me.Padding(top=24), display="flex", flex_direction="column", gap=8, ), ): me.text( "Categories", style=me.Style( font_weight=500, letter_spacing="0.4px", padding=me.Padding(left=12), ), ) for section in SECTIONS: with me.box( style=me.Style( display="flex", align_items="center", cursor="pointer", ), on_click=scroll_to_section, key=section.name, ): with me.content_button(type="icon"): me.icon(section.icon) me.text(section.name) with me.box( style=me.Style( display="flex", align_items="center", cursor="pointer", padding=me.Padding(top=16), ), on_click=lambda e: me.navigate( "https://github.com/google/mesop/issues/new/choose" ), ): with me.content_button(type="icon"): me.icon("add_circle") me.text("Submit your showcase") def card(resource: Resource): with me.box( style=me.Style( display="flex", flex_direction="column", gap=12, box_shadow="0 2px 4px rgba(0, 0, 0, 0.1)", border_radius=16, min_width=CARD_WIDTH, max_width=480, background=me.theme_var("surface-container-lowest"), ) ): me.box( style=me.Style( background=f"url('{resource.img_url}') center/cover no-repeat", cursor="pointer", height=200, width="100%", border_radius=16, margin=me.Margin(bottom=8), ), key=resource.app_url or resource.github_url, on_click=lambda e: me.navigate(e.key), ) with me.box( style=me.Style( padding=me.Padding(left=16), display="flex", flex_direction="column", gap=8, ) ): me.text(resource.title, style=me.Style(font_weight="bold")) with me.box( style=me.Style( display="flex", flex_direction="row", align_items="center", gap=8, cursor="pointer", ), key="https://github.com/" + resource.github_username, on_click=lambda e: me.navigate(e.key), ): me.image( src="https://avatars.githubusercontent.com/" + resource.github_username, style=me.Style(height=32, width=32, border_radius=16), ) me.text( resource.github_username, style=me.Style( letter_spacing="0.2px", ), ) me.text(resource.description, style=me.Style(height=40)) with me.box( style=me.Style( display="flex", justify_content="space-between", padding=me.Padding(left=8, right=8, bottom=8), ) ): if resource.github_url: me.button( "Open repo", on_click=lambda e: me.navigate(e.key), key=resource.github_url, ) if resource.app_url: me.button( "Open app", on_click=lambda e: me.navigate(e.key), key=resource.app_url, ) <example> |