File size: 56,554 Bytes
4aec76b afaa9de 4aec76b |
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 |
import json
import time
import requests
import streamlit as st
from contextlib import contextmanager
from typing import Optional, List, Literal
# import server.logger as logger
# ------------------------------------------------------------------------------
# Page Config:
# ------------------------------------------------------------------------------
# Configure page with professional branding
st.set_page_config(
page_title="Chat with your data | Knowledge Assistant",
page_icon="π¦",
layout='wide',
initial_sidebar_state='expanded',
menu_items={
'Get Help': 'https://github.com/sanchit-shaleen/chat-with-your-data',
'Report a bug': 'https://github.com/sanchit-shaleen/chat-with-your-data/issues',
'About': '# Chat with your data\nA production-grade document intelligence system'
}
)
# Modern CSS styling for professional appearance
st.markdown("""
<style>
/* Modern, soothing color scheme */
:root {
--primary: #4F46E5;
--primary-dark: #4F46E5;
--primary-light: #818CF8;
--background-dark: #0F172A;
--background-light: #1E293B;
--surface: #334155;
--text-primary: #F8FAFC;
--text-secondary: #CBD5E1;
--accent: #06B6D4;
--success: #10B981;
--warning: #F59E0B;
}
/* Page background */
body {
background: linear-gradient(135deg, #0F172A 0%, #1E293B 100%);
}
/* Main container */
.main {
background-color: transparent;
}
/* Header styling */
.header-container {
background: linear-gradient(135deg, #4F46E5 0%, #06B6D4 100%);
padding: 2rem 1.5rem;
border-radius: 12px;
margin-bottom: 2rem;
box-shadow: 0 4px 20px rgba(79, 70, 229, 0.25);
}
.header-title {
font-size: 2.5em;
font-weight: 700;
color: #FFFFFF;
margin: 0;
letter-spacing: -0.5px;
}
.header-subtitle {
font-size: 1.1em;
color: rgba(255, 255, 255, 0.9);
margin: 0.5rem 0 0 0;
font-weight: 400;
}
/* Auth sections */
.stTabs [data-baseweb="tab-list"] {
gap: 1rem;
}
.stTabs [data-baseweb="tab"] {
background: transparent;
border-radius: 8px 8px 0 0;
color: rgba(203, 213, 225, 0.7);
font-weight: 600;
padding: 1rem 2rem;
border-bottom: 2px solid transparent;
transition: all 0.3s ease;
}
.stTabs [data-baseweb="tab"][aria-selected="true"] {
background: linear-gradient(135deg, #4F46E5 0%, #06B6D4 100%);
color: white;
border: none;
}
/* Input fields */
.stTextInput > div > div > input,
.stTextArea > div > div > textarea {
background-color: rgba(30, 41, 59, 0.7) !important;
border: 1px solid rgba(79, 70, 229, 0.3) !important;
border-radius: 8px !important;
color: #F8FAFC !important;
padding: 0.75rem !important;
transition: all 0.3s ease !important;
}
.stTextInput > div > div > input::placeholder {
color: rgba(203, 213, 225, 0.5) !important;
}
.stTextInput > div > div > input:focus,
.stTextArea > div > div > textarea:focus {
border: 1px solid #4F46E5 !important;
box-shadow: 0 0 0 2px rgba(79, 70, 229, 0.2) !important;
}
/* Buttons */
.stButton > button {
background: linear-gradient(135deg, #4F46E5 0%, #06B6D4 100%) !important;
color: white !important;
font-weight: 600 !important;
border: none !important;
border-radius: 8px !important;
padding: 0.75rem 2rem !important;
transition: all 0.3s ease !important;
box-shadow: 0 4px 12px rgba(79, 70, 229, 0.3) !important;
}
.stButton > button:hover {
box-shadow: 0 6px 20px rgba(79, 70, 229, 0.5) !important;
transform: translateY(-2px) !important;
}
.stButton > button[kind="secondary"] {
background: rgba(79, 70, 229, 0.1) !important;
color: #4F46E5 !important;
border: 1px solid #4F46E5 !important;
}
/* Chat messages */
.stChatMessage {
background: rgba(30, 41, 59, 0.5);
border-radius: 8px;
border: 1px solid rgba(79, 70, 229, 0.2);
}
/* Containers with borders */
.stContainer {
background: linear-gradient(135deg, rgba(30, 41, 59, 0.5) 0%, rgba(15, 23, 42, 0.5) 100%);
border: 1px solid rgba(79, 70, 229, 0.2);
border-radius: 8px;
}
/* Checkbox and selections */
.stCheckbox {
color: #F8FAFC;
}
.stCheckbox input[type="checkbox"] {
accent-color: #4F46E5 !important;
}
/* Loading spinners and progress */
.stSpinner {
color: #4F46E5 !important;
}
/* Metric styling */
.stMetric {
background: rgba(30, 41, 59, 0.5);
border: 1px solid rgba(79, 70, 229, 0.2);
border-radius: 8px;
padding: 1rem;
}
/* Sidebar */
[data-testid="stSidebar"] {
background: linear-gradient(180deg, #1E293B 0%, #0F172A 100%);
border-right: 1px solid rgba(79, 70, 229, 0.2);
}
/* Success/Error/Info messages */
.stSuccess {
background: rgba(16, 185, 129, 0.1) !important;
border: 1px solid rgba(16, 185, 129, 0.3) !important;
border-radius: 8px !important;
}
.stError {
background: rgba(239, 68, 68, 0.1) !important;
border: 1px solid rgba(239, 68, 68, 0.3) !important;
border-radius: 8px !important;
}
.stInfo {
background: rgba(59, 130, 246, 0.1) !important;
border: 1px solid rgba(59, 130, 246, 0.3) !important;
border-radius: 8px !important;
}
.stWarning {
background: rgba(245, 158, 11, 0.1) !important;
border: 1px solid rgba(245, 158, 11, 0.3) !important;
border-radius: 8px !important;
}
/* Dividers */
hr {
border: none;
border-top: 1px solid rgba(79, 70, 229, 0.2);
margin: 1.5rem 0;
}
/* File uploader */
.stFileUploader {
border: 2px dashed rgba(79, 70, 229, 0.3) !important;
border-radius: 8px !important;
background: rgba(79, 70, 229, 0.05) !important;
}
/* Selectbox and multiselect */
.stSelectbox [data-baseweb="select"],
.stMultiSelect [data-baseweb="multi-select"] {
background-color: rgba(30, 41, 59, 0.7) !important;
border-radius: 8px !important;
border: 1px solid rgba(79, 70, 229, 0.3) !important;
}
/* Loading spinners and progress */
.stSpinner {
color: #4F46E5 !important;
}
/* Metric styling */
.stMetric {
background: rgba(30, 41, 59, 0.5);
border: 1px solid rgba(79, 70, 229, 0.2);
border-radius: 8px;
padding: 1rem;
}
/* Sidebar */
[data-testid="stSidebar"] {
background: linear-gradient(180deg, #1E293B 0%, #0F172A 100%);
border-right: 1px solid rgba(79, 70, 229, 0.2);
}
/* Success/Error/Info messages */
.stSuccess {
background: rgba(16, 185, 129, 0.1) !important;
border: 1px solid rgba(16, 185, 129, 0.3) !important;
border-radius: 8px !important;
}
.stError {
background: rgba(239, 68, 68, 0.1) !important;
border: 1px solid rgba(239, 68, 68, 0.3) !important;
border-radius: 8px !important;
}
.stInfo {
background: rgba(59, 130, 246, 0.1) !important;
border: 1px solid rgba(59, 130, 246, 0.3) !important;
border-radius: 8px !important;
}
.stWarning {
background: rgba(245, 158, 11, 0.1) !important;
border: 1px solid rgba(245, 158, 11, 0.3) !important;
border-radius: 8px !important;
}
/* Multi-select styling */
.stMultiSelect [data-baseweb="multi-select"] {
background-color: rgba(30, 41, 59, 0.7) !important;
border-radius: 8px !important;
border: 1px solid rgba(79, 70, 229, 0.3) !important;
}
/* Dividers */
hr {
border: none;
border-top: 1px solid rgba(79, 70, 229, 0.2);
margin: 1.5rem 0;
}
/* File uploader */
.stFileUploader {
border: 2px dashed rgba(79, 70, 229, 0.3) !important;
border-radius: 8px !important;
background: rgba(79, 70, 229, 0.05) !important;
}
/* Selectbox and multiselect */
.stSelectbox [data-baseweb="select"],
.stMultiSelect [data-baseweb="multi-select"] {
background-color: rgba(30, 41, 59, 0.7) !important;
border-radius: 8px !important;
border: 1px solid rgba(79, 70, 229, 0.3) !important;
}
/* Text and number inputs */
.stNumberInput > div > div > input {
color: #4F46E5;
}
/* Sliders */
.stSlider > div > div > div > div {
color: #4F46E5;
}
/* Active tab underline */
.stTabs [data-baseweb="tab"][aria-selected="true"] {
color: #4F46E5;
border-bottom: 2px solid #4F46E5;
}
/* Features sidebar */
.features-sidebar {
border-right: 1px solid rgba(79, 70, 229, 0.2);
}
/* Chat sidebar */
.chat-sidebar {
border-top: 1px solid rgba(79, 70, 229, 0.2);
}
/* Upload area */
.upload-area {
border: 2px dashed rgba(79, 70, 229, 0.3) !important;
border-radius: 12px;
background: rgba(79, 70, 229, 0.05) !important;
}
</style>
""", unsafe_allow_html=True)
# ------------------------------------------------------------------------------
# Page consistent settings and initializations:
# ------------------------------------------------------------------------------
class Message:
type: Literal['assistant', 'human']
content: str
filenames: Optional[List[str]]
# List of filenames attached to the message
# These names will be original file names, might be diff than actual saved on server
# Hence, Chat-UI and sidebar might show same file with different names.
def __init__(
self, type: Literal['assistant', 'human'],
content: str, filenames: Optional[List[str]] = None
):
self.type = type
self.content = content
self.filenames = filenames
# Get user_id:
if "session_id" not in st.session_state:
# Enhanced CSS for modern landing page
st.markdown("""
<style>
/* Landing page styling */
.landing-container {
display: flex;
height: 100vh;
background: linear-gradient(135deg, #0F172A 0%, #1E293B 100%);
margin: -2rem -2rem -2rem -2rem;
}
.landing-left {
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
padding: 4rem;
background: linear-gradient(135deg, rgba(79, 70, 229, 0.1) 0%, rgba(6, 182, 212, 0.05) 100%);
border-right: 1px solid rgba(79, 70, 229, 0.2);
}
.landing-right {
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding: 4rem 3rem;
overflow-y: auto;
}
.landing-logo {
font-size: 3.5em;
margin-bottom: 1.5rem;
animation: float 3s ease-in-out infinite;
}
@keyframes float {
0%, 100% { transform: translateY(0px); }
50% { transform: translateY(-10px); }
}
.landing-brand {
font-size: 2.2em;
font-weight: 700;
color: #F1F5F9;
margin-bottom: 0.5rem;
letter-spacing: -0.5px;
}
.landing-tagline {
font-size: 1.4em;
color: #4F46E5;
font-weight: 600;
margin-bottom: 2rem;
}
.landing-description {
font-size: 1.1em;
color: rgba(241, 245, 249, 0.8);
line-height: 1.6;
margin-bottom: 3rem;
max-width: 500px;
}
.feature-list {
display: flex;
flex-direction: column;
gap: 2rem;
max-width: 500px;
}
.feature-item {
display: flex;
gap: 1.5rem;
align-items: flex-start;
}
.feature-icon {
font-size: 2em;
min-width: 3rem;
display: flex;
justify-content: center;
padding: 0.5rem;
background: rgba(79, 70, 229, 0.2);
border-radius: 8px;
height: fit-content;
}
.feature-content h4 {
margin: 0 0 0.5rem 0;
color: #F1F5F9;
font-size: 1.1em;
font-weight: 600;
}
.feature-content p {
margin: 0;
color: rgba(241, 245, 249, 0.7);
font-size: 0.95em;
}
.auth-container {
width: 100%;
max-width: 420px;
background: rgba(30, 41, 59, 0.9);
backdrop-filter: blur(10px);
border: 1px solid rgba(79, 70, 229, 0.2);
border-radius: 12px;
padding: 3rem;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}
.auth-header {
text-align: center;
margin-bottom: 2.5rem;
}
.auth-header h2 {
color: #F1F5F9;
margin: 0 0 0.5rem 0;
font-size: 1.8em;
font-weight: 700;
}
.auth-header p {
color: rgba(241, 245, 249, 0.6);
margin: 0;
font-size: 0.95em;
}
.auth-form-group {
margin-bottom: 1.5rem;
}
.auth-form-group label {
display: block;
color: #F1F5F9;
font-weight: 600;
margin-bottom: 0.75rem;
font-size: 0.95em;
}
.auth-form-group input {
width: 100%;
padding: 0.875rem 1rem;
background-color: rgba(15, 23, 42, 0.8) !important;
border: 1px solid rgba(79, 70, 229, 0.3) !important;
border-radius: 8px !important;
color: #F1F5F9 !important;
font-size: 0.95em;
transition: all 0.3s ease;
}
.auth-form-group input::placeholder {
color: rgba(241, 245, 249, 0.4) !important;
}
.auth-form-group input:focus {
border: 1px solid #4F46E5 !important;
box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1) !important;
outline: none !important;
}
.auth-checkbox {
display: flex;
align-items: center;
gap: 0.5rem;
margin-bottom: 1.5rem;
}
.auth-checkbox input[type="checkbox"] {
accent-color: #4F46E5 !important;
cursor: pointer;
}
.auth-checkbox label {
color: rgba(241, 245, 249, 0.8);
margin: 0;
font-weight: 500;
cursor: pointer;
font-size: 0.9em;
}
.auth-forgot-link {
text-align: right;
margin-bottom: 1.5rem;
}
.auth-forgot-link a {
color: #4F46E5;
text-decoration: none;
font-size: 0.9em;
font-weight: 500;
transition: color 0.3s ease;
}
.auth-forgot-link a:hover {
color: #4F46E5;
text-decoration: underline;
}
.auth-button {
width: 100%;
padding: 0.9rem;
background: linear-gradient(135deg, #4F46E5 0%, #06B6D4 100%);
color: white;
border: none;
border-radius: 8px;
font-size: 1em;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
box-shadow: 0 4px 12px rgba(79, 70, 229, 0.4);
margin-bottom: 1rem;
}
.auth-button:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(79, 70, 229, 0.6);
}
.auth-button:active {
transform: translateY(0);
}
.auth-signup-link {
text-align: center;
color: rgba(241, 245, 249, 0.7);
font-size: 0.9em;
}
.auth-signup-link a {
color: #4F46E5;
text-decoration: none;
font-weight: 600;
transition: color 0.3s ease;
}
.auth-signup-link a:hover {
color: #4F46E5;
text-decoration: underline;
}
/* Tab styling */
.auth-tabs {
display: flex;
gap: 0.5rem;
margin-bottom: 2rem;
border-bottom: 1px solid rgba(79, 70, 229, 0.2);
}
.auth-tab {
flex: 1;
padding: 0.75rem 1rem;
background: transparent;
border: none;
color: rgba(241, 245, 249, 0.6);
font-weight: 600;
cursor: pointer;
border-bottom: 2px solid transparent;
transition: all 0.3s ease;
font-size: 0.95em;
}
.auth-tab.active {
color: #4F46E5;
border-bottom: 2px solid #4F46E5;
}
.auth-tab:hover {
color: #F1F5F9;
}
/* Responsive */
@media (max-width: 1024px) {
.landing-container {
flex-direction: column;
}
.landing-left {
padding: 2rem;
border-right: none;
border-bottom: 1px solid rgba(79, 70, 229, 0.2);
}
.landing-right {
padding: 2rem;
}
}
</style>
""", unsafe_allow_html=True)
# Add header banner
st.markdown("""
<div style="background: linear-gradient(135deg, #4F46E5 0%, #06B6D4 100%);
padding: 3rem 2rem; border-radius: 12px; margin-bottom: 2rem;
box-shadow: 0 4px 20px rgba(79, 70, 229, 0.25);">
<div style="display: flex; align-items: center; gap: 1rem;">
<span style="font-size: 3em;">π¬</span>
<div>
<h1 style="margin: 0; color: white; font-size: 2em;">Chat with your data</h1>
<p style="margin: 0.5rem 0 0 0; color: rgba(255,255,255,0.9);">Your Personal Document Intelligence Assistant</p>
</div>
</div>
</div>
""", unsafe_allow_html=True)
# Check server availability with retries
max_retries = 5
retry_delay = 2 # seconds
server_ready = False
for attempt in range(max_retries):
try:
if requests.get(f"{st.secrets.server.ip_address}/", timeout=5).status_code == 200:
server_ready = True
break
except:
if attempt < max_retries - 1:
st.info(f"π Initializing services... ({attempt + 1}/{max_retries})")
import time
time.sleep(retry_delay)
else:
st.error("π« Server is not reachable. Please check your connection or server status.", icon="π")
st.stop()
# Create two-column layout with proper sizing
col_left, col_right = st.columns([1, 1.2], gap="large")
with col_left:
st.markdown("### π¬ Why Chat with Your Data?", help="Key features")
# Feature cards with updated color scheme
st.markdown("""
<div style="background: rgba(79, 70, 229, 0.1); padding: 1.5rem; border-radius: 8px; margin-bottom: 1rem; border-left: 4px solid #4F46E5;">
<h4 style="margin: 0 0 0.5rem 0; color: #F8FAFC;">π€ Upload Any Data</h4>
<p style="margin: 0; color: rgba(248, 250, 252, 0.8); font-size: 0.9em;">Support for CSV, Excel, JSON, and more</p>
</div>
<div style="background: rgba(6, 182, 212, 0.1); padding: 1.5rem; border-radius: 8px; margin-bottom: 1rem; border-left: 4px solid #06B6D4;">
<h4 style="margin: 0 0 0.5rem 0; color: #F8FAFC;">π¬ Natural Conversations</h4>
<p style="margin: 0; color: rgba(248, 250, 252, 0.8); font-size: 0.9em;">Ask questions in plain English, get instant answers</p>
</div>
<div style="background: rgba(79, 70, 229, 0.1); padding: 1.5rem; border-radius: 8px; margin-bottom: 1rem; border-left: 4px solid #4F46E5;">
<h4 style="margin: 0 0 0.5rem 0; color: #F8FAFC;">β AI-Powered Insights</h4>
<p style="margin: 0; color: rgba(248, 250, 252, 0.8); font-size: 0.9em;">Discover patterns and trends automatically</p>
</div>
<div style="background: rgba(6, 182, 212, 0.1); padding: 1.5rem; border-radius: 8px; border-left: 4px solid #06B6D4;">
<h4 style="margin: 0 0 0.5rem 0; color: #F8FAFC;">π Lightning Fast</h4>
<p style="margin: 0; color: rgba(248, 250, 252, 0.8); font-size: 0.9em;">Optimized caching for instant responses</p>
</div>
""", unsafe_allow_html=True)
with col_right:
# Determine which tab is active
if "auth_tab" not in st.session_state:
st.session_state.auth_tab = "login"
st.markdown("""
### π Sign In / Create Account
""")
# Tab selection
tab1, tab2 = st.tabs(["π Login", "π Register"])
with tab1:
st.write("Welcome back! Sign in to your account to continue.")
ip_user_id = st.text_input(
"User ID",
placeholder="Enter your user ID",
key="login_user_id"
)
ip_user_pw = st.text_input(
"Password",
placeholder="Enter your password",
type="password",
key="login_user_pw"
)
remember = st.checkbox("Remember me", key="login_remember", value=False)
if st.button("π Login", type="primary", use_container_width=True, key="login_btn"):
ip_user_id = "_".join(ip_user_id.strip().lower().split(" "))
ip_user_pw = ip_user_pw.strip()
if not ip_user_id or not ip_user_pw:
st.error("β Please fill all the fields.")
else:
try:
resp = requests.post(
f"{st.secrets.server.ip_address}/login",
json={"login_id": ip_user_id, "password": ip_user_pw}
)
if resp.status_code == 200:
session_id = resp.json().get("user_id")
st.session_state.session_id = session_id
name_of_user = resp.json().get("name", session_id)
st.session_state.name_of_user = name_of_user
st.success("β
Login successful! Redirecting...", icon="β¨")
time.sleep(1)
st.rerun()
else:
st.error("β " + resp.json().get("error", "Login failed."))
except requests.RequestException as e:
st.error(f"β Error connecting to server: {e}")
with tab2:
st.write("Join us and start chatting with your data today!")
ip_user_name = st.text_input(
"Full Name",
placeholder="John Doe",
key="register_user_name"
)
ip_user_id = st.text_input(
"User ID",
placeholder="john_doe",
key="register_user_id"
)
st.caption("Use: lowercase, numbers, `-`, `_` only")
ip_user_pw = st.text_input(
"Password",
placeholder="Create a strong password",
type="password",
key="register_user_pw"
)
if st.button("β¨ Create Account", type="primary", use_container_width=True, key="register_btn"):
ip_user_id = "_".join(ip_user_id.strip().lower().split(" "))
ip_user_pw = ip_user_pw.strip()
if not ip_user_name or not ip_user_id or not ip_user_pw:
st.error("β Please fill all the fields.")
else:
try:
resp = requests.post(
f"{st.secrets.server.ip_address}/register",
json={
"name": ip_user_name,
"user_id": ip_user_id,
"password": ip_user_pw
}
)
if resp.status_code == 201:
st.success("β
Registration successful! You can now login.", icon="π")
st.info("π Switch to the Login tab to sign in.", icon="βΉοΈ")
else:
st.error("β " + resp.json().get("error", "Registration failed."))
except requests.RequestException as e:
st.error(f"β Error connecting to server: {e}")
st.stop()
if "initialized" not in st.session_state:
# Initialize Logger:
# st.session_state.logger = logger.get_logger(name="Streamlit")
# log = st.session_state.logger
# log.info("Streamlit initialized.")
# Initialize the session with server::
st.session_state.server_ip = st.secrets.server.ip_address
try:
resp = requests.post(
f"{st.session_state.server_ip}/chat_history",
data={"user_id": st.session_state.session_id}
)
if resp.status_code == 200:
# Initialize messages:
st.session_state.chat_history = [Message('assistant', "π, How may I help you today?")]
# Load old chat history (if):
chat_hist = resp.json().get("chat_history", [])
for msg in chat_hist:
st.session_state.chat_history.append(Message(msg['role'], msg['content']))
else:
# log.error(f"Failed to initialize chat history: {resp.json().get('error', 'Unknown error')}")
st.error(
"Failed to initialize chat history. Please try again later.",
icon="π«"
)
st.stop()
except requests.RequestException as e:
# log.error(f"Error initializing server session: {e}")
st.error(
"Failed to connect to the server. Please check your connection or server status.",
icon="π«"
)
st.stop()
# # Initialize messages:
# st.session_state.chat_history = [
# Message('assistant', "π, How may I help you today?"),
# # Message("human", "Help me in some thing...")
# ]
# User's Existing Uploads:
st.session_state.user_uploads = requests.get(
f"{st.session_state.server_ip}/uploads",
params={"user_id": st.session_state.session_id}
).json().get("files", [])
# Last resp retrieved docs:
st.session_state.last_retrieved_docs = []
# Set flag to true:
st.session_state.initialized = True
# All variables in session state:
user_id = st.session_state.session_id
chat_history = st.session_state.chat_history
server_ip = st.session_state.server_ip
# Debug: Display current user_id
with st.sidebar:
st.caption(f"π€ Logged in as: `{user_id}`")
# ------------------------------------------------------------------------------
# Helper functions:
# ------------------------------------------------------------------------------
def write_as_ai(text):
with st.chat_message(name='assistant', avatar='assistant'):
st.markdown(text)
def write_as_human(text: str, filenames: Optional[List[str]] = None):
with st.chat_message(name='user', avatar='user'):
st.markdown(text)
if filenames:
files = ", ".join([f"`'{file}'`" for file in filenames])
st.caption(f"π Attached file(s): {files}.")
def upload_file(uploaded_file) -> tuple[bool, str]:
"""Upload the st attachment/uploaded file to the server and save it.
Args:
uploaded_file: The file object uploaded by the user.
Returns:
tuple: A tuple containing:
- bool: True if the file was uploaded successfully, False otherwise.
- str: The server file name or error message.
"""
try:
# POST to FastAPI
files = {"file": (uploaded_file.name, uploaded_file.getvalue())}
data = {"user_id": user_id}
response = requests.post(f"{server_ip}/upload", files=files, data=data)
if response.status_code == 200:
message = response.json().get("message", "")
# log.info(f"File `{message}` uploaded successfully for user `{user_id}`.")
return True, message
else:
message = response.json().get("error", "Unknown error")
# log.error(
# f"Failed to upload file `{uploaded_file.name}`: {message} for user `{user_id}`.")
return False, message
except Exception as e:
# log.error(f"Error uploading file `{uploaded_file.name}`: {e} for user `{user_id}`.")
return False, str(e)
def embed_file(file_name: str) -> tuple[bool, str, dict]:
"""Embed the content of the file into the RAG system with multimodal support.
Args:
file_name: The name of the file to embed.
Returns:
tuple: A tuple containing:
- bool: True if the file was embedded successfully, False otherwise.
- str: Success message or error message.
- dict: Additional metadata (items_embedded, text_chunks, images_extracted, image_paths)
"""
try:
response = requests.post(
f"{server_ip}/embed",
json={
"user_id": user_id,
"file_name": file_name
}
)
if response.status_code == 200:
resp_data = response.json()
message = resp_data.get("message", "File embedded successfully.")
# Build detailed message with multimodal info
detailed_message = message
items = resp_data.get("items_embedded", 0)
text_chunks = resp_data.get("text_chunks", 0)
images = resp_data.get("images_extracted", 0)
if items > 0:
detailed_message = f"β
Ingested {items} items ({text_chunks} text chunks + {images} πΌοΈ images)"
# Return with metadata for frontend enhancement
metadata = {
"items_embedded": items,
"text_chunks": text_chunks,
"images_extracted": images,
"image_paths": resp_data.get("image_paths", [])
}
return True, detailed_message, metadata
else:
error_message = response.json().get("error", "Unknown error")
return False, error_message, {}
except Exception as e:
return False, str(e), {}
def handle_uploaded_files(uploaded_files) -> bool:
"""Handle the uploaded files by uploading them to the server and embedding their content."""
progress_status = ""
with st.chat_message(name='assistant', avatar='./assets/settings_3.png'):
with st.spinner("Processing files..."):
container = st.empty()
# Found out later that all this thing can be done with st.status() as status:
# But, it does not allow that much customization.
@contextmanager
def write_progress(msg: str):
# Shared variable across multiple steps
nonlocal progress_status
# Start with β³οΈ to show progress:
curr = progress_status + f"- β³ {msg}\n"
container.container(border=True).markdown(curr)
try:
# Do the actual step (indent of 'with')
yield
# yield is over means, step is done > Update with β
progress_status += f"\n- β
{msg}\n"
curr = progress_status
except Exception as e:
progress_status += f"\n- β {msg}: {e}\n"
raise e
finally:
container.container(border=True).markdown(curr)
try:
for i, file in enumerate(uploaded_files):
progress_status += f"\nπ Processing file {i+1} of {len(uploaded_files)}...\n"
# log.info(f"Processing file: {file.name}")
# Upload file:
with write_progress("Uploading file..."):
status, message = upload_file(file)
if not status:
raise RuntimeError(f"Upload failed for file: {file.name}")
server_file_name = message
time.sleep(st.secrets.llm.per_step_delay)
# Embed the file:
with write_progress("Embedding content..."):
status, message, embed_metadata = embed_file(server_file_name)
if not status:
raise RuntimeError(f"Embedding failed for file: {file.name}")
# Show multimodal embedding results if available
if embed_metadata.get("images_extracted", 0) > 0:
st.success(f"π {message}", icon="β
")
time.sleep(st.secrets.llm.per_step_delay)
# Any last steps like finalizing or cleanup:
with write_progress("Finalizing the process..."):
# Update data with latest user_upload
st.session_state.user_uploads = requests.get(
f"{st.session_state.server_ip}/uploads",
params={"user_id": user_id}
).json().get("files", [])
# log.info(f"File `{file.name}` processed successfully.")
time.sleep(st.secrets.llm.end_delay)
return True
except Exception as e:
st.exception(exception=e)
st.stop()
return False
@st.cache_data(ttl=60 * 10, show_spinner=False)
def get_iframe(file_name: str, num_pages: int = 5) -> tuple[bool, str]:
"""Get the iframe HTML for the PDF file."""
try:
response = requests.post(
f"{st.session_state.server_ip}/iframe",
json={
"user_id": user_id,
"file_name": file_name,
"num_pages": num_pages
},
)
if response.status_code == 200:
return True, response.json().get("iframe", "")
else:
return False, response.json().get("error", "Unknown error")
except requests.RequestException as e:
# log.error(f"Error getting iframe for {file_name}: {e}")
return False, str(e)
# ------------------------------------------------------------------------------
# Sidebar:
# ------------------------------------------------------------------------------
# User Profile:
with st.sidebar.container(border=True):
col1, col2, col3 = st.columns([1, 5, 1])
col1.write("π€")
col2.markdown(f"**{st.session_state.get('name_of_user', 'User')}**")
col3.write(f"β¨")
st.sidebar.divider()
# Files Preview Section:
st.sidebar.subheader("π Document Management")
selected_file = st.sidebar.selectbox(
label="Choose Document",
index=0,
options=st.session_state.user_uploads,
help="Select a document to preview"
)
# Tried to show pdf persistently, but it re-renders on each run and page hangs in streaming response:
if not st.session_state.user_uploads:
st.sidebar.info("π No documents uploaded yet.\n\nStart by uploading your first document!", icon="βΉοΈ")
else:
col1, col2 = st.sidebar.columns([1, 1])
with col1:
preview_button = st.sidebar.button("ποΈ Preview", use_container_width=True)
with col2:
delete_button = st.sidebar.button("ποΈ Delete", use_container_width=True)
if selected_file and preview_button:
status, content = get_iframe(selected_file)
if status:
st.sidebar.markdown(content, unsafe_allow_html=True)
else:
st.sidebar.error(f"β Error: {content}", icon="π«")
if selected_file and delete_button:
try:
resp = requests.post(
f"{st.session_state.server_ip}/delete_file",
json={"user_id": user_id, "file_name": selected_file}
)
if resp.status_code == 200:
st.sidebar.success("β
Document deleted successfully!", icon="ποΈ")
st.cache_data.clear()
st.rerun()
else:
st.sidebar.error(resp.json().get("error", "Failed to delete document."), icon="π«")
except requests.RequestException as e:
st.sidebar.error(f"β Error deleting document: {e}", icon="π")
st.sidebar.divider()
# Advanced Options:
st.sidebar.subheader("βοΈ Advanced Options")
col1, col2 = st.sidebar.columns([1, 1])
with col1:
dummy_mode = st.sidebar.toggle(
label="π Dummy Mode",
value=False,
key="dummy_mode",
help="Use placeholder responses instead of LLM"
)
with col2:
cache_mode = st.sidebar.toggle(
label="πΎ Cache Info",
value=False,
key="show_cache_info",
help="Show cache performance metrics"
)
st.sidebar.divider()
# Destructive Actions:
st.sidebar.subheader("π΄ Danger Zone")
col1, col2 = st.sidebar.columns([1, 1])
with col1:
if st.sidebar.button("ποΈ Clear Uploads", type="secondary", use_container_width=True):
try:
resp = requests.post(
f"{st.session_state.server_ip}/clear_my_files",
data={"user_id": user_id}
)
if resp.status_code == 200:
st.sidebar.success("β
All documents cleared!", icon="ποΈ")
st.cache_data.clear()
st.rerun()
else:
st.sidebar.error(resp.json().get("error", "Failed to clear documents."), icon="π«")
except requests.RequestException as e:
st.sidebar.error(f"β Error: {e}", icon="π")
with col2:
if st.sidebar.button("π¬ Clear Chat", type="secondary", use_container_width=True):
resp = requests.post(
f"{server_ip}/clear_chat_history",
data={"user_id": user_id}
)
if resp.status_code == 200:
st.session_state.chat_history = [
Message('assistant', "π Hello! How can I help you today?")
]
st.session_state.last_retrieved_docs = []
st.sidebar.success("β
Chat cleared!", icon="π¬")
st.rerun()
else:
st.sidebar.error(resp.json().get("error", "Failed to clear chat."), icon="π«")
st.sidebar.divider()
# Footer
st.sidebar.markdown("""
---
<div style='text-align: center; color: rgba(241, 245, 249, 0.6); font-size: 0.85em;'>
<p>π¬ Chat with your data</p>
<p style='font-size: 0.8em;'>Production-grade Document Intelligence</p>
</div>
""", unsafe_allow_html=True)
# with st.sidebar:
# st.write(st.session_state)
# ------------------------------------------------------------------------------
# Page content:
# ------------------------------------------------------------------------------
# Page content with modern header
col1, col2 = st.columns([0.8, 9.2], vertical_alignment='bottom', gap='small')
with col1:
col1.markdown("π¦")
with col2:
st.markdown("""
<div style="margin-bottom: -1rem;">
<h1 style="margin: 0; background: linear-gradient(135deg, #4F46E5 0%, #06B6D4 100%);
-webkit-background-clip: text; -webkit-text-fill-color: transparent;
background-clip: text; font-weight: 700;">
Chat with your data
</h1>
<p style="color: rgba(241, 245, 249, 0.7); margin: 0.5rem 0 0 0; font-size: 0.95em;">
Your intelligent document assistant powered by local AI inference
</p>
</div>
""", unsafe_allow_html=True)
st.divider()
# Display cache info if enabled
if st.session_state.get('show_cache_info', False):
with st.expander("β‘ Cache Performance & Statistics", expanded=True):
try:
cache_stats = requests.get(f"{server_ip}/cache-debug").json()
col1, col2, col3 = st.columns(3)
with col1:
st.metric("π¦ Cache Size", f"{cache_stats.get('cache_size', 0)} entries",
help="Number of queries currently cached")
with col2:
st.metric("β‘ Status", "π’ Active",
help="Cache is operational and responding")
with col3:
st.metric("πΎ Memory", "Optimized",
help="Using LRU eviction and TTL expiration")
if cache_stats.get('cache_keys'):
st.caption(f"π Recent queries in cache: {', '.join([f'`{k[:15]}...`' for k in cache_stats.get('cache_keys', [])[:5]])}")
except Exception as e:
st.warning("β οΈ Cache stats unavailable", icon="βΉοΈ")
# Chat history display
for ind, message in enumerate(st.session_state.chat_history):
if ind < len(st.session_state.chat_history) - 1: # all messages except last
if message.type == 'human':
write_as_human(message.content, message.filenames)
elif message.type == 'assistant':
answer = message.content
if "<think>" in answer:
answer = answer[answer.find("</think>") + len("</think>"):]
write_as_ai(answer)
else: # Last message
if message.type == 'human': # if human, write normally
write_as_human(message.content)
elif message.type == 'assistant': # if assistant
# Get the answer, thoughts and docs from the message:
full = message.content
thoughts = full[
full.find("<think>")+8:full.find("</think>")
] if "<think>" in full else None
answer = full[full.find("</think>") + len("</think>"):] if thoughts else full
documents = st.session_state.last_retrieved_docs if st.session_state.last_retrieved_docs else None
with st.chat_message(name='assistant', avatar='assistant'):
with st.container(border=True):
# # Thinking:
# if thoughts:
# cont_thoughts = st.expander("π Thoughts", expanded=True).markdown(thoughts)
# # Answer:
# st.markdown(answer)
# # Documents:
# if documents:
# tabs = st.expander("ποΈ Sources", expanded=False).tabs(
# tabs=[f"Document {i+1}" for i in range(len(documents))]
# )
# for i, doc in enumerate(documents):
# with tabs[i]:
# st.subheader(":blue[Content:]")
# st.markdown(doc['page_content'])
# st.divider()
# st.subheader(":blue[Source Details:]")
# st.json(doc['metadata'], expanded=False)
# Thinking:
if thoughts:
# cont_thoughts = c1.expander("π Thoughts", expanded=True).markdown(thoughts)
cont_thoughts = st.popover(
"π Thoughts", use_container_width=False).markdown(thoughts)
# Answer:
st.markdown(answer)
# Documents:
if documents:
tabs = st.expander("ποΈ Sources", expanded=False).tabs(
tabs=[f"Document {i+1}" for i in range(len(documents))]
)
for i, doc in enumerate(documents):
with tabs[i]:
# Check if this is an image document
is_image = doc.get('metadata', {}).get('type') == 'image'
if is_image and 'image_path' in doc.get('metadata', {}):
# Display image document
st.subheader("πΌοΈ Image Source")
image_path = doc['metadata']['image_path']
try:
from PIL import Image
img = Image.open(image_path)
st.image(img, caption=f"Image ID: {doc['metadata'].get('image_id', 'unknown')}", use_column_width=True)
st.divider()
st.subheader(":blue[Image Details:]")
img_details = {
"page_number": doc['metadata'].get('page_number'),
"position": doc['metadata'].get('position'),
"extractor": doc['metadata'].get('extractor'),
"size": img.size if hasattr(img, 'size') else "unknown"
}
st.json(img_details, expanded=False)
except FileNotFoundError:
st.warning(f"β οΈ Image not found at: {image_path}")
except Exception as e:
st.error(f"β Error loading image: {e}")
else:
# Display text document (original behavior)
st.subheader(":blue[Content:]")
st.markdown(doc['page_content'])
st.divider()
st.subheader(":blue[Source Details:]")
st.json(doc['metadata'], expanded=False)
# Metrics Display:
last_metrics = st.session_state.get('last_metrics', {})
if last_metrics and "error" not in last_metrics:
with st.expander("π Response Quality Metrics", expanded=True):
st.markdown("**LLM-based evaluation using DeepEval + Ollama (Reference-Free)**")
cols = st.columns(2)
# Answer Relevancy
with cols[0]:
relevancy_score = last_metrics.get("answer_relevancy", 0.0)
st.metric(
label="π― Answer Relevancy",
value=f"{relevancy_score:.2%}",
help="Measures how relevant the answer is to your question (0-100%)"
)
if relevancy_score >= 0.7:
st.success("β Highly relevant", icon="β
")
elif relevancy_score >= 0.5:
st.warning("β Moderate", icon="β οΈ")
else:
st.error("β Low relevance", icon="β")
# Faithfulness
with cols[1]:
faithfulness_score = last_metrics.get("faithfulness", 0.0)
st.metric(
label="π Faithfulness",
value=f"{faithfulness_score:.2%}",
help="Measures how well the answer is grounded in the retrieved documents (0-100%)"
)
if faithfulness_score >= 0.7:
st.success("β Well-grounded", icon="β
")
elif faithfulness_score >= 0.5:
st.warning("β Partial support", icon="β οΈ")
else:
st.error("β Weak grounding", icon="β")
st.caption("π‘ Metrics use reference-free LLM-as-Judge approach - no ground truth needed")
if user_message := st.chat_input(
placeholder="π¬ Ask anything about your documents... Attach [pdf, txt, md] files with π",
max_chars=2000,
accept_file='multiple',
file_type=['pdf', 'txt', 'md'],
):
# Create Message object from the user input:
new_message = Message(
type="human",
content=user_message.text,
filenames=[file.name for file in user_message.files] if user_message.files else None
)
# Save it to the chat:
st.session_state.chat_history.append(new_message)
# For now, write it on screen:
write_as_human(new_message.content, new_message.filenames)
# Clear last documents:
st.session_state.last_retrieved_docs = []
# Handle the files if any:
if user_message.files:
if handle_uploaded_files(user_message.files):
st.toast("Files processed successfully!", icon="β
")
else:
st.error("Error processing files. Please try again.", icon="π«")
# Get response and write it:
with st.chat_message(name='assistant', avatar='assistant'):
with st.spinner("Generating response..."):
full = ""
# If dummy mode is enabled, use dummy response:
if st.session_state.get("dummy_mode", False):
resp_holder = st.empty()
response = requests.post(
f"{server_ip}/rag",
json={
"query": new_message.content,
"session_id": user_id,
"dummy": True
},
stream=True
)
for chunk in response.iter_content(chunk_size=None):
if chunk:
decoded = chunk.decode("utf-8")
decoded = json.loads(decoded)
if decoded["type"] == "content":
full += decoded["data"]
# elif decoded["type"] == "metadata":
# full += f"```json\n{json.dumps(decoded['data'], indent=2)}\n```\n\n\n"
# elif decoded["type"] == "context":
# documents.append(decoded['data'])
# else:
# st.error(decoded['data'])
# continue
resp_holder.markdown(full + "β")
else: # real RAG response from server
response = requests.post(
f"{server_ip}/rag",
json={
"query": new_message.content,
"session_id": user_id,
"dummy": False
},
stream=True
)
documents = []
metrics = {}
resp_holder = st.container(border=True)
# Create placeholder containers that won't be replaced
reply_container = resp_holder.container(border=True)
reply_holder = reply_container.empty()
document_container = resp_holder.container()
document_holder = document_container.empty()
for chunk in response.iter_content(chunk_size=None):
print(" Received chunk... :", chunk, flush=True)
if chunk:
decoded = chunk.decode("utf-8")
decoded = json.loads(decoded)
print(" Decoded chunk: ", decoded, flush=True)
if decoded["type"] == "metadata":
# Skip metadata for now
continue
# full += f"```json\n{json.dumps(decoded['data'], indent=2)}\n```\n\n\n"
elif decoded["type"] == "context":
documents.append(decoded['data'])
elif decoded["type"] == "content":
full += decoded["data"]
elif decoded["type"] == "metrics":
metrics = decoded["data"]
st.session_state.last_metrics = metrics
print("π―π―π― METRICS RECEIVED:", metrics, flush=True)
st.toast("π Metrics received!", icon="β
")
else:
st.error(decoded['data'])
continue
if documents:
docs = document_holder.expander("ποΈ Sources", expanded=True)
tabs = docs.tabs(
tabs=[f"Document {i+1}" for i in range(len(documents))])
for i, doc in enumerate(documents):
with tabs[i]:
st.subheader(":blue[Content:]")
st.markdown(doc['page_content'])
st.divider()
st.subheader(":blue[Source Details:]")
st.json(doc['metadata'], expanded=False)
print(" Updating reply_holder:", full)
reply_holder.markdown(full + "β")
# Remove cursor after streaming completes
reply_holder.markdown(full)
# Debug: Check metrics state
print(f"π DEBUG: After streaming - metrics type={type(metrics)}, value={metrics}", flush=True)
print(f"π DEBUG: metrics bool={bool(metrics)}, has error={'error' in metrics if metrics else 'N/A'}", flush=True)
print(" Final response received: ", full)
st.session_state.last_retrieved_docs = documents
st.session_state.chat_history.append(Message("assistant", full))
st.rerun()
|