Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,1002 +1,1090 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Schema-Agnostic Database Chatbot - Streamlit Application
|
| 3 |
-
|
| 4 |
-
A production-grade chatbot that connects to ANY database
|
| 5 |
-
(MySQL, PostgreSQL, SQLite) and provides intelligent querying
|
| 6 |
-
through RAG and Text-to-SQL.
|
| 7 |
-
|
| 8 |
-
Uses Groq for FREE LLM inference!
|
| 9 |
-
"""
|
| 10 |
-
|
| 11 |
-
import os
|
| 12 |
-
from pathlib import Path
|
| 13 |
-
|
| 14 |
-
# Load .env FIRST before any other imports
|
| 15 |
-
from dotenv import load_dotenv
|
| 16 |
-
load_dotenv(Path(__file__).parent / ".env")
|
| 17 |
-
|
| 18 |
-
import streamlit as st
|
| 19 |
-
import uuid
|
| 20 |
-
import time
|
| 21 |
-
import io
|
| 22 |
-
import csv
|
| 23 |
-
import base64
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
from
|
| 37 |
-
from database
|
| 38 |
-
from
|
| 39 |
-
from
|
| 40 |
-
from
|
| 41 |
-
from
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
"llama-3.
|
| 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 |
-
writer.
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
lines
|
| 180 |
-
lines.append(
|
| 181 |
-
lines.append(f"
|
| 182 |
-
lines.append("
|
| 183 |
-
lines.append("")
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
if meta.get("
|
| 196 |
-
lines.append(f"
|
| 197 |
-
if meta.get("
|
| 198 |
-
lines.append(f"
|
| 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 |
-
key="
|
| 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 |
-
st.
|
| 351 |
-
st.
|
| 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 |
-
st.
|
| 390 |
-
|
| 391 |
-
st.divider()
|
| 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 |
-
if st.session_state.initialized
|
| 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 |
-
st.
|
| 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 |
-
st.
|
| 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 |
-
if
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Schema-Agnostic Database Chatbot - Streamlit Application
|
| 3 |
+
|
| 4 |
+
A production-grade chatbot that connects to ANY database
|
| 5 |
+
(MySQL, PostgreSQL, SQLite) and provides intelligent querying
|
| 6 |
+
through RAG and Text-to-SQL.
|
| 7 |
+
|
| 8 |
+
Uses Groq for FREE LLM inference!
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
# Load .env FIRST before any other imports
|
| 15 |
+
from dotenv import load_dotenv
|
| 16 |
+
load_dotenv(Path(__file__).parent / ".env")
|
| 17 |
+
|
| 18 |
+
import streamlit as st
|
| 19 |
+
import uuid
|
| 20 |
+
import time
|
| 21 |
+
import io
|
| 22 |
+
import csv
|
| 23 |
+
import base64
|
| 24 |
+
import pandas as pd
|
| 25 |
+
from datetime import datetime
|
| 26 |
+
|
| 27 |
+
# Page config must be first
|
| 28 |
+
st.set_page_config(
|
| 29 |
+
page_title="OnceDataBot",
|
| 30 |
+
page_icon="🤖",
|
| 31 |
+
layout="wide",
|
| 32 |
+
initial_sidebar_state="expanded"
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
# Imports
|
| 36 |
+
from config import config, DatabaseConfig, DatabaseType
|
| 37 |
+
from database import get_db, get_schema, get_introspector
|
| 38 |
+
from database.connection import DatabaseConnection
|
| 39 |
+
from llm import create_llm_client
|
| 40 |
+
from chatbot import create_chatbot, DatabaseChatbot
|
| 41 |
+
from memory import ChatMemory, EnhancedChatMemory
|
| 42 |
+
from viz_utils import render_visualization
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# Groq models (all FREE!)
|
| 50 |
+
GROQ_MODELS = [
|
| 51 |
+
"llama-3.3-70b-versatile",
|
| 52 |
+
"llama-3.1-8b-instant",
|
| 53 |
+
"mixtral-8x7b-32768",
|
| 54 |
+
"gemma2-9b-it"
|
| 55 |
+
]
|
| 56 |
+
|
| 57 |
+
# Database types
|
| 58 |
+
DB_TYPES = {
|
| 59 |
+
"MySQL": "mysql",
|
| 60 |
+
"PostgreSQL": "postgresql",
|
| 61 |
+
"SQLite": "sqlite"
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
# Supported languages for multi-language responses
|
| 65 |
+
SUPPORTED_LANGUAGES = {
|
| 66 |
+
"English": "en",
|
| 67 |
+
"हिन्दी (Hindi)": "hi",
|
| 68 |
+
"Español (Spanish)": "es",
|
| 69 |
+
"Français (French)": "fr",
|
| 70 |
+
"Deutsch (German)": "de",
|
| 71 |
+
"中文 (Chinese)": "zh",
|
| 72 |
+
"日本語 (Japanese)": "ja",
|
| 73 |
+
"한국어 (Korean)": "ko",
|
| 74 |
+
"Português (Portuguese)": "pt",
|
| 75 |
+
"العربية (Arabic)": "ar",
|
| 76 |
+
"Русский (Russian)": "ru",
|
| 77 |
+
"Italiano (Italian)": "it",
|
| 78 |
+
"Nederlands (Dutch)": "nl",
|
| 79 |
+
"தமிழ் (Tamil)": "ta",
|
| 80 |
+
"తెలుగు (Telugu)": "te",
|
| 81 |
+
"मराठी (Marathi)": "mr",
|
| 82 |
+
"বাংলা (Bengali)": "bn",
|
| 83 |
+
"ગુજરાতી (Gujarati)": "gu"
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def create_custom_db_config(db_type: str, **kwargs) -> DatabaseConfig:
|
| 88 |
+
"""Create a custom database configuration from user input."""
|
| 89 |
+
return DatabaseConfig(
|
| 90 |
+
db_type=DatabaseType(db_type),
|
| 91 |
+
host=kwargs.get("host", ""),
|
| 92 |
+
port=kwargs.get("port", 3306 if db_type == "mysql" else 5432),
|
| 93 |
+
database=kwargs.get("database", ""),
|
| 94 |
+
username=kwargs.get("username", ""),
|
| 95 |
+
password=kwargs.get("password", ""),
|
| 96 |
+
ssl_ca=kwargs.get("ssl_ca", None)
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def create_custom_memory(session_id: str, user_id: str, db_connection, llm_client=None,
|
| 101 |
+
enable_summarization=True, summary_threshold=10) -> EnhancedChatMemory:
|
| 102 |
+
"""Create enhanced memory with a custom database connection."""
|
| 103 |
+
return EnhancedChatMemory(
|
| 104 |
+
session_id=session_id,
|
| 105 |
+
user_id=user_id,
|
| 106 |
+
max_messages=20,
|
| 107 |
+
db_connection=db_connection,
|
| 108 |
+
llm_client=llm_client,
|
| 109 |
+
enable_summarization=enable_summarization,
|
| 110 |
+
summary_threshold=summary_threshold
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def init_session_state():
|
| 115 |
+
"""Initialize Streamlit session state."""
|
| 116 |
+
if "session_id" not in st.session_state:
|
| 117 |
+
st.session_state.session_id = str(uuid.uuid4())
|
| 118 |
+
|
| 119 |
+
if "messages" not in st.session_state:
|
| 120 |
+
st.session_state.messages = []
|
| 121 |
+
|
| 122 |
+
if "chatbot" not in st.session_state:
|
| 123 |
+
st.session_state.chatbot = None
|
| 124 |
+
|
| 125 |
+
if "initialized" not in st.session_state:
|
| 126 |
+
st.session_state.initialized = False
|
| 127 |
+
|
| 128 |
+
if "user_id" not in st.session_state:
|
| 129 |
+
st.session_state.user_id = "default"
|
| 130 |
+
|
| 131 |
+
if "enable_summarization" not in st.session_state:
|
| 132 |
+
st.session_state.enable_summarization = True
|
| 133 |
+
|
| 134 |
+
if "summary_threshold" not in st.session_state:
|
| 135 |
+
st.session_state.summary_threshold = 10
|
| 136 |
+
|
| 137 |
+
if "memory" not in st.session_state:
|
| 138 |
+
st.session_state.memory = None
|
| 139 |
+
|
| 140 |
+
if "indexed" not in st.session_state:
|
| 141 |
+
st.session_state.indexed = False
|
| 142 |
+
|
| 143 |
+
if "db_source" not in st.session_state:
|
| 144 |
+
st.session_state.db_source = "environment" # "environment" or "custom"
|
| 145 |
+
|
| 146 |
+
if "custom_db_config" not in st.session_state:
|
| 147 |
+
st.session_state.custom_db_config = None
|
| 148 |
+
|
| 149 |
+
if "custom_db_connection" not in st.session_state:
|
| 150 |
+
st.session_state.custom_db_connection = None
|
| 151 |
+
|
| 152 |
+
if "ignored_tables" not in st.session_state:
|
| 153 |
+
st.session_state.ignored_tables = set()
|
| 154 |
+
|
| 155 |
+
if "response_language" not in st.session_state:
|
| 156 |
+
st.session_state.response_language = "English"
|
| 157 |
+
|
| 158 |
+
if "favorites" not in st.session_state:
|
| 159 |
+
st.session_state.favorites = [] # List of message indices that are favorited
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def export_results_to_csv(results: list) -> str:
|
| 163 |
+
"""Convert SQL results to CSV format and return as downloadable string."""
|
| 164 |
+
if not results:
|
| 165 |
+
return ""
|
| 166 |
+
|
| 167 |
+
output = io.StringIO()
|
| 168 |
+
writer = csv.DictWriter(output, fieldnames=results[0].keys())
|
| 169 |
+
writer.writeheader()
|
| 170 |
+
writer.writerows(results)
|
| 171 |
+
return output.getvalue()
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def export_chat_to_text() -> str:
|
| 175 |
+
"""Export chat messages to text format."""
|
| 176 |
+
if not st.session_state.messages:
|
| 177 |
+
return "No messages to export."
|
| 178 |
+
|
| 179 |
+
lines = []
|
| 180 |
+
lines.append("=" * 50)
|
| 181 |
+
lines.append(f"OnceDataBot Chat Export")
|
| 182 |
+
lines.append(f"Exported: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
| 183 |
+
lines.append(f"User: {st.session_state.user_id}")
|
| 184 |
+
lines.append("=" * 50)
|
| 185 |
+
lines.append("")
|
| 186 |
+
|
| 187 |
+
for i, msg in enumerate(st.session_state.messages):
|
| 188 |
+
role = "🧑 User" if msg["role"] == "user" else "🤖 Assistant"
|
| 189 |
+
is_favorited = "⭐ " if i in st.session_state.favorites else ""
|
| 190 |
+
lines.append(f"{is_favorited}{role}:")
|
| 191 |
+
lines.append(msg["content"])
|
| 192 |
+
|
| 193 |
+
if msg["role"] == "assistant" and "metadata" in msg:
|
| 194 |
+
meta = msg["metadata"]
|
| 195 |
+
if meta.get("sql_query"):
|
| 196 |
+
lines.append(f"\n📝 SQL Query: {meta['sql_query']}")
|
| 197 |
+
if meta.get("query_type"):
|
| 198 |
+
lines.append(f"📌 Query Type: {meta['query_type']}")
|
| 199 |
+
if meta.get("execution_time"):
|
| 200 |
+
lines.append(f"⏱️ Execution Time: {meta['execution_time']:.2f}s")
|
| 201 |
+
|
| 202 |
+
lines.append("-" * 40)
|
| 203 |
+
lines.append("")
|
| 204 |
+
|
| 205 |
+
return "\n".join(lines)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def render_copy_button(text: str, key: str):
|
| 209 |
+
"""Render a copy to clipboard button using Streamlit."""
|
| 210 |
+
# Using a workaround with st.code which has built-in copy
|
| 211 |
+
st.code(text, language="sql")
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def render_database_config():
|
| 215 |
+
"""Render database configuration section in sidebar."""
|
| 216 |
+
st.subheader("🗄️ Database Configuration")
|
| 217 |
+
|
| 218 |
+
# Database source selection
|
| 219 |
+
db_source = st.radio(
|
| 220 |
+
"Database Source",
|
| 221 |
+
options=["Use Environment Variables", "Custom Database"],
|
| 222 |
+
index=0 if st.session_state.db_source == "environment" else 1,
|
| 223 |
+
key="db_source_radio",
|
| 224 |
+
help="Choose to use .env settings or enter custom credentials"
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
st.session_state.db_source = "environment" if db_source == "Use Environment Variables" else "custom"
|
| 228 |
+
|
| 229 |
+
if st.session_state.db_source == "environment":
|
| 230 |
+
# Show current environment config
|
| 231 |
+
current_db_type = config.database.db_type.value.upper()
|
| 232 |
+
st.info(f"📌 Using {current_db_type} from environment")
|
| 233 |
+
st.caption(f"Host: {config.database.host}")
|
| 234 |
+
return None
|
| 235 |
+
|
| 236 |
+
else:
|
| 237 |
+
# Custom database configuration
|
| 238 |
+
st.markdown("##### Enter Database Credentials")
|
| 239 |
+
|
| 240 |
+
# Database type selector
|
| 241 |
+
db_type_label = st.selectbox(
|
| 242 |
+
"Database Type",
|
| 243 |
+
options=list(DB_TYPES.keys()),
|
| 244 |
+
index=0,
|
| 245 |
+
key="custom_db_type"
|
| 246 |
+
)
|
| 247 |
+
db_type = DB_TYPES[db_type_label]
|
| 248 |
+
|
| 249 |
+
if db_type == "sqlite":
|
| 250 |
+
# SQLite only needs a file path
|
| 251 |
+
database = st.text_input(
|
| 252 |
+
"SQLite Database File",
|
| 253 |
+
value="ingested_data.db",
|
| 254 |
+
key="db_sqlite_path",
|
| 255 |
+
help="Path to the .db file (will be created if it doesn't exist)"
|
| 256 |
+
)
|
| 257 |
+
return {
|
| 258 |
+
"db_type": db_type,
|
| 259 |
+
"database": database
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
else: # MySQL or PostgreSQL
|
| 263 |
+
# MySQL or PostgreSQL
|
| 264 |
+
col1, col2 = st.columns([3, 1])
|
| 265 |
+
with col1:
|
| 266 |
+
host = st.text_input(
|
| 267 |
+
"Host",
|
| 268 |
+
value="",
|
| 269 |
+
key="db_host_input",
|
| 270 |
+
placeholder="your-database-host.com"
|
| 271 |
+
)
|
| 272 |
+
with col2:
|
| 273 |
+
default_port = 3306 if db_type == "mysql" else 5432
|
| 274 |
+
port = st.number_input(
|
| 275 |
+
"Port",
|
| 276 |
+
value=default_port,
|
| 277 |
+
min_value=1,
|
| 278 |
+
max_value=65535,
|
| 279 |
+
key="db_port_input"
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
database = st.text_input(
|
| 283 |
+
"Database Name",
|
| 284 |
+
value="",
|
| 285 |
+
key="db_name_input",
|
| 286 |
+
placeholder="your_database"
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
username = st.text_input(
|
| 290 |
+
"Username",
|
| 291 |
+
value="",
|
| 292 |
+
key="db_user_input",
|
| 293 |
+
placeholder="your_username"
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
password = st.text_input(
|
| 297 |
+
"Password",
|
| 298 |
+
value="",
|
| 299 |
+
type="password",
|
| 300 |
+
key="db_pass_input"
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
# Optional SSL
|
| 304 |
+
with st.expander("🔒 SSL Settings (Optional)"):
|
| 305 |
+
ssl_ca = st.text_input(
|
| 306 |
+
"SSL CA Certificate Path",
|
| 307 |
+
value="",
|
| 308 |
+
key="ssl_ca_input",
|
| 309 |
+
help="Path to SSL CA certificate file (for cloud databases like Aiven)"
|
| 310 |
+
)
|
| 311 |
+
|
| 312 |
+
return {
|
| 313 |
+
"db_type": db_type,
|
| 314 |
+
"host": host,
|
| 315 |
+
"port": int(port),
|
| 316 |
+
"database": database,
|
| 317 |
+
"username": username,
|
| 318 |
+
"password": password,
|
| 319 |
+
"ssl_ca": ssl_ca if ssl_ca else None
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def render_sidebar():
|
| 324 |
+
"""Render the configuration sidebar."""
|
| 325 |
+
with st.sidebar:
|
| 326 |
+
st.title("⚙️ Settings")
|
| 327 |
+
|
| 328 |
+
# Session Dashboard
|
| 329 |
+
if st.session_state.messages:
|
| 330 |
+
st.markdown("### 📊 Session Stats")
|
| 331 |
+
|
| 332 |
+
# Calculate stats
|
| 333 |
+
total_msgs = len(st.session_state.messages)
|
| 334 |
+
assistant_msgs = [m for m in st.session_state.messages if m.get("role") == "assistant"]
|
| 335 |
+
sql_queries = sum(1 for m in assistant_msgs if m.get("metadata", {}).get("sql_query"))
|
| 336 |
+
|
| 337 |
+
total_tokens = 0
|
| 338 |
+
exec_times = []
|
| 339 |
+
for m in assistant_msgs:
|
| 340 |
+
meta = m.get("metadata", {})
|
| 341 |
+
total_tokens += meta.get("token_usage", {}).get("total", 0)
|
| 342 |
+
if meta.get("execution_time"):
|
| 343 |
+
exec_times.append(meta["execution_time"])
|
| 344 |
+
|
| 345 |
+
avg_time = sum(exec_times) / len(exec_times) if exec_times else 0
|
| 346 |
+
|
| 347 |
+
col_s1, col_s2 = st.columns(2)
|
| 348 |
+
col_s1.metric("Queries", sql_queries)
|
| 349 |
+
col_s2.metric("Tokens", f"{total_tokens:,}")
|
| 350 |
+
st.caption(f"⏱️ Avg Time: {avg_time:.2f}s | 💬 Msgs: {total_msgs}")
|
| 351 |
+
st.divider()
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
# User Profile
|
| 356 |
+
st.subheader("👤 User Profile")
|
| 357 |
+
user_id = st.text_input(
|
| 358 |
+
"User ID / Name",
|
| 359 |
+
value=st.session_state.get("user_id", "default"),
|
| 360 |
+
key="user_id_input",
|
| 361 |
+
help="Your unique ID for private memory storage"
|
| 362 |
+
)
|
| 363 |
+
if user_id != st.session_state.get("user_id"):
|
| 364 |
+
st.session_state.user_id = user_id
|
| 365 |
+
st.session_state.session_id = str(uuid.uuid4())
|
| 366 |
+
st.session_state.messages = []
|
| 367 |
+
|
| 368 |
+
# Recreate memory for new user
|
| 369 |
+
if st.session_state.custom_db_connection:
|
| 370 |
+
st.session_state.memory = create_custom_memory(
|
| 371 |
+
st.session_state.session_id,
|
| 372 |
+
user_id,
|
| 373 |
+
st.session_state.custom_db_connection,
|
| 374 |
+
st.session_state.get("llm"),
|
| 375 |
+
st.session_state.enable_summarization,
|
| 376 |
+
st.session_state.summary_threshold
|
| 377 |
+
)
|
| 378 |
+
elif st.session_state.initialized:
|
| 379 |
+
from memory import create_enhanced_memory
|
| 380 |
+
st.session_state.memory = create_enhanced_memory(
|
| 381 |
+
st.session_state.session_id,
|
| 382 |
+
user_id=user_id,
|
| 383 |
+
enable_summarization=st.session_state.enable_summarization,
|
| 384 |
+
summary_threshold=st.session_state.summary_threshold
|
| 385 |
+
)
|
| 386 |
+
|
| 387 |
+
if st.session_state.memory:
|
| 388 |
+
st.session_state.memory.clear_user_history()
|
| 389 |
+
st.rerun()
|
| 390 |
+
|
| 391 |
+
st.divider()
|
| 392 |
+
|
| 393 |
+
# Language Selection
|
| 394 |
+
st.subheader("🌐 Response Language")
|
| 395 |
+
selected_language = st.selectbox(
|
| 396 |
+
"Select Language",
|
| 397 |
+
options=list(SUPPORTED_LANGUAGES.keys()),
|
| 398 |
+
index=list(SUPPORTED_LANGUAGES.keys()).index(st.session_state.response_language),
|
| 399 |
+
key="language_selector",
|
| 400 |
+
help="Choose the language for chatbot responses"
|
| 401 |
+
)
|
| 402 |
+
if selected_language != st.session_state.response_language:
|
| 403 |
+
st.session_state.response_language = selected_language
|
| 404 |
+
st.toast(f"🌐 Language changed to {selected_language}")
|
| 405 |
+
|
| 406 |
+
st.divider()
|
| 407 |
+
|
| 408 |
+
if st.session_state.messages:
|
| 409 |
+
st.download_button(
|
| 410 |
+
label="📄 Export Chat",
|
| 411 |
+
data=export_chat_to_text(),
|
| 412 |
+
file_name=f"chat_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt",
|
| 413 |
+
mime="text/plain",
|
| 414 |
+
use_container_width=True,
|
| 415 |
+
help="Download your chat conversation as a text file"
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
st.divider()
|
| 419 |
+
|
| 420 |
+
# CSV Ingestion Section
|
| 421 |
+
st.subheader("📥 Ingest CSV Data")
|
| 422 |
+
uploaded_files = st.file_uploader(
|
| 423 |
+
"Upload CSV(s) to create database",
|
| 424 |
+
type=["csv"],
|
| 425 |
+
accept_multiple_files=True,
|
| 426 |
+
help="Your CSVs will be converted to tables in a local SQLite database"
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
if uploaded_files:
|
| 430 |
+
if st.button("🚀 Upload & Initialize", use_container_width=True):
|
| 431 |
+
with st.spinner("Processing CSVs..."):
|
| 432 |
+
success_count = 0
|
| 433 |
+
table_names = []
|
| 434 |
+
for uploaded_file in uploaded_files:
|
| 435 |
+
success, name, rows = ingest_csv(uploaded_file)
|
| 436 |
+
if success:
|
| 437 |
+
success_count += 1
|
| 438 |
+
table_names.append(name)
|
| 439 |
+
else:
|
| 440 |
+
st.error(f"Failed to ingest {uploaded_file.name}: {name}")
|
| 441 |
+
|
| 442 |
+
if success_count > 0:
|
| 443 |
+
st.success(f"Successfully ingested {success_count} file(s) as tables: {', '.join(table_names)}")
|
| 444 |
+
|
| 445 |
+
# Now initialize chatbot with this SQLite DB
|
| 446 |
+
sqlite_params = {
|
| 447 |
+
"db_type": "sqlite",
|
| 448 |
+
"database": "ingested_data.db"
|
| 449 |
+
}
|
| 450 |
+
# Temporarily set db_source to custom for initialization
|
| 451 |
+
old_source = st.session_state.db_source
|
| 452 |
+
st.session_state.db_source = "custom"
|
| 453 |
+
init_success = initialize_chatbot(sqlite_params, None, None)
|
| 454 |
+
if not init_success:
|
| 455 |
+
st.session_state.db_source = old_source
|
| 456 |
+
else:
|
| 457 |
+
st.rerun()
|
| 458 |
+
|
| 459 |
+
st.divider()
|
| 460 |
+
|
| 461 |
+
# Database Configuration
|
| 462 |
+
custom_db_params = render_database_config()
|
| 463 |
+
|
| 464 |
+
st.divider()
|
| 465 |
+
|
| 466 |
+
# LLM Configuration
|
| 467 |
+
st.subheader("🤖 LLM Configuration")
|
| 468 |
+
|
| 469 |
+
# Show status of API key
|
| 470 |
+
if os.getenv("GROQ_API_KEY"):
|
| 471 |
+
st.success("✓ API Key configured")
|
| 472 |
+
else:
|
| 473 |
+
st.warning("⚠️ GROQ_API_KEY not set in environment")
|
| 474 |
+
|
| 475 |
+
st.divider()
|
| 476 |
+
|
| 477 |
+
# Initialize Button
|
| 478 |
+
if st.button("🚀 Connect & Initialize", use_container_width=True, type="primary"):
|
| 479 |
+
with st.spinner("Connecting to database..."):
|
| 480 |
+
success = initialize_chatbot(custom_db_params, None, None)
|
| 481 |
+
if success:
|
| 482 |
+
st.success("✅ Connected!")
|
| 483 |
+
st.rerun()
|
| 484 |
+
|
| 485 |
+
# Index Button (after initialization)
|
| 486 |
+
if st.session_state.initialized:
|
| 487 |
+
if st.button("📚 Index Text Data", use_container_width=True):
|
| 488 |
+
with st.spinner("Indexing text data..."):
|
| 489 |
+
index_data()
|
| 490 |
+
st.success("✅ Indexed!")
|
| 491 |
+
st.rerun()
|
| 492 |
+
|
| 493 |
+
st.divider()
|
| 494 |
+
|
| 495 |
+
# Status
|
| 496 |
+
st.subheader("📊 Status")
|
| 497 |
+
if st.session_state.initialized:
|
| 498 |
+
# Show database type
|
| 499 |
+
if st.session_state.custom_db_connection:
|
| 500 |
+
db_type = st.session_state.custom_db_connection.db_type.value.upper()
|
| 501 |
+
else:
|
| 502 |
+
db_type = get_db().db_type.value.upper()
|
| 503 |
+
|
| 504 |
+
st.success(f"Database: {db_type} ✓")
|
| 505 |
+
|
| 506 |
+
try:
|
| 507 |
+
schema = get_schema()
|
| 508 |
+
st.info(f"Tables: {len(schema.tables)}")
|
| 509 |
+
except:
|
| 510 |
+
st.warning("Schema not loaded")
|
| 511 |
+
|
| 512 |
+
if st.session_state.indexed:
|
| 513 |
+
from rag import get_rag_engine
|
| 514 |
+
engine = get_rag_engine()
|
| 515 |
+
st.info(f"Indexed Docs: {engine.document_count}")
|
| 516 |
+
else:
|
| 517 |
+
st.warning("Not connected")
|
| 518 |
+
|
| 519 |
+
# New Chat
|
| 520 |
+
if st.button("➕ New Chat", use_container_width=True, type="secondary"):
|
| 521 |
+
if st.session_state.memory:
|
| 522 |
+
st.session_state.memory.clear()
|
| 523 |
+
|
| 524 |
+
st.session_state.messages = []
|
| 525 |
+
st.session_state.session_id = str(uuid.uuid4())
|
| 526 |
+
|
| 527 |
+
current_user = st.session_state.get("user_id", "default")
|
| 528 |
+
|
| 529 |
+
if st.session_state.custom_db_connection:
|
| 530 |
+
st.session_state.memory = create_custom_memory(
|
| 531 |
+
st.session_state.session_id,
|
| 532 |
+
current_user,
|
| 533 |
+
st.session_state.custom_db_connection,
|
| 534 |
+
st.session_state.get("llm"),
|
| 535 |
+
st.session_state.enable_summarization,
|
| 536 |
+
st.session_state.summary_threshold
|
| 537 |
+
)
|
| 538 |
+
elif st.session_state.initialized:
|
| 539 |
+
from memory import create_enhanced_memory
|
| 540 |
+
st.session_state.memory = create_enhanced_memory(
|
| 541 |
+
st.session_state.session_id,
|
| 542 |
+
user_id=current_user,
|
| 543 |
+
enable_summarization=st.session_state.enable_summarization,
|
| 544 |
+
summary_threshold=st.session_state.summary_threshold
|
| 545 |
+
)
|
| 546 |
+
if st.session_state.get("llm"):
|
| 547 |
+
st.session_state.memory.set_llm_client(st.session_state.llm)
|
| 548 |
+
|
| 549 |
+
st.rerun()
|
| 550 |
+
|
| 551 |
+
# Disconnect button (when using custom DB)
|
| 552 |
+
if st.session_state.initialized and st.session_state.db_source == "custom":
|
| 553 |
+
if st.button("🔌 Disconnect", use_container_width=True):
|
| 554 |
+
if st.session_state.custom_db_connection:
|
| 555 |
+
st.session_state.custom_db_connection.close()
|
| 556 |
+
st.session_state.custom_db_connection = None
|
| 557 |
+
st.session_state.chatbot = None
|
| 558 |
+
st.session_state.initialized = False
|
| 559 |
+
st.session_state.indexed = False
|
| 560 |
+
st.session_state.memory = None
|
| 561 |
+
st.success("Disconnected!")
|
| 562 |
+
st.rerun()
|
| 563 |
+
|
| 564 |
+
st.divider()
|
| 565 |
+
|
| 566 |
+
# Chat History Section
|
| 567 |
+
if st.session_state.memory:
|
| 568 |
+
st.subheader("🕰️ Chat History")
|
| 569 |
+
sessions = st.session_state.memory.get_user_sessions()
|
| 570 |
+
|
| 571 |
+
if not sessions:
|
| 572 |
+
st.caption("No previous chats found.")
|
| 573 |
+
else:
|
| 574 |
+
for session in sessions:
|
| 575 |
+
# Highlight current session
|
| 576 |
+
is_current = session["id"] == st.session_state.session_id
|
| 577 |
+
icon = "🟢" if is_current else "💬"
|
| 578 |
+
|
| 579 |
+
if st.button(
|
| 580 |
+
f"{icon} {session['title']}",
|
| 581 |
+
key=f"hist_{session['id']}",
|
| 582 |
+
use_container_width=True,
|
| 583 |
+
type="secondary" if not is_current else "primary"
|
| 584 |
+
):
|
| 585 |
+
if not is_current:
|
| 586 |
+
# Load selected session
|
| 587 |
+
st.session_state.session_id = session["id"]
|
| 588 |
+
st.session_state.memory.session_id = session["id"]
|
| 589 |
+
st.session_state.memory.messages = [] # Clear current state local cache
|
| 590 |
+
|
| 591 |
+
# Load from DB
|
| 592 |
+
msgs = st.session_state.memory.load_session(session["id"])
|
| 593 |
+
st.session_state.messages = msgs
|
| 594 |
+
|
| 595 |
+
# Re-populate memory object messages list for context
|
| 596 |
+
# (We need to convert dicts back to ChatMessage objects implicitly or just rely on reload)
|
| 597 |
+
# Actually, we should probably re-init the memory to be safe or manually populate
|
| 598 |
+
# Let's manually populate to keep the connection valid
|
| 599 |
+
from memory import ChatMessage
|
| 600 |
+
st.session_state.memory.messages = [
|
| 601 |
+
ChatMessage(
|
| 602 |
+
role=m['role'],
|
| 603 |
+
content=m['content'],
|
| 604 |
+
metadata=m.get('metadata')
|
| 605 |
+
) for m in msgs
|
| 606 |
+
]
|
| 607 |
+
|
| 608 |
+
st.rerun()
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
def initialize_chatbot(custom_db_params=None, api_key=None, model=None) -> bool:
|
| 612 |
+
"""Initialize the chatbot with either environment or custom database."""
|
| 613 |
+
try:
|
| 614 |
+
# Get API key
|
| 615 |
+
groq_api_key = api_key or os.getenv("GROQ_API_KEY", "")
|
| 616 |
+
groq_model = model or os.getenv("GROQ_MODEL", "llama-3.3-70b-versatile")
|
| 617 |
+
|
| 618 |
+
if not groq_api_key:
|
| 619 |
+
st.error("GROQ_API_KEY not configured. Please enter your API key.")
|
| 620 |
+
return False
|
| 621 |
+
|
| 622 |
+
# Create LLM client
|
| 623 |
+
llm = create_llm_client("groq", api_key=groq_api_key, model=groq_model)
|
| 624 |
+
|
| 625 |
+
# Create database connection
|
| 626 |
+
if custom_db_params and st.session_state.db_source == "custom":
|
| 627 |
+
# Validate custom params
|
| 628 |
+
db_type = custom_db_params.get("db_type", "mysql")
|
| 629 |
+
|
| 630 |
+
if db_type != "sqlite":
|
| 631 |
+
if not all([custom_db_params.get("host"),
|
| 632 |
+
custom_db_params.get("database"),
|
| 633 |
+
custom_db_params.get("username")]):
|
| 634 |
+
st.error("Please fill in all required database fields.")
|
| 635 |
+
return False
|
| 636 |
+
else:
|
| 637 |
+
if not custom_db_params.get("database"):
|
| 638 |
+
st.error("Please specify a SQLite database file path.")
|
| 639 |
+
return False
|
| 640 |
+
|
| 641 |
+
# Create custom config
|
| 642 |
+
db_config = create_custom_db_config(**custom_db_params)
|
| 643 |
+
|
| 644 |
+
# Create custom connection
|
| 645 |
+
custom_connection = DatabaseConnection(db_config)
|
| 646 |
+
|
| 647 |
+
# Test connection
|
| 648 |
+
success, msg = custom_connection.test_connection()
|
| 649 |
+
if not success:
|
| 650 |
+
st.error(f"Connection failed: {msg}")
|
| 651 |
+
return False
|
| 652 |
+
|
| 653 |
+
st.session_state.custom_db_connection = custom_connection
|
| 654 |
+
st.session_state.custom_db_config = db_config
|
| 655 |
+
|
| 656 |
+
# Override the global db connection for the chatbot
|
| 657 |
+
# We need to create a chatbot with this custom connection
|
| 658 |
+
from chatbot import DatabaseChatbot
|
| 659 |
+
from database.schema_introspector import SchemaIntrospector
|
| 660 |
+
from rag import get_rag_engine
|
| 661 |
+
from sql import get_sql_generator, get_sql_validator
|
| 662 |
+
from router import get_query_router
|
| 663 |
+
|
| 664 |
+
chatbot = DatabaseChatbot.__new__(DatabaseChatbot)
|
| 665 |
+
chatbot.db = custom_connection
|
| 666 |
+
chatbot.introspector = SchemaIntrospector()
|
| 667 |
+
chatbot.introspector.db = custom_connection
|
| 668 |
+
chatbot.rag_engine = get_rag_engine()
|
| 669 |
+
chatbot.sql_generator = get_sql_generator(db_type)
|
| 670 |
+
chatbot.sql_validator = get_sql_validator()
|
| 671 |
+
chatbot.router = get_query_router()
|
| 672 |
+
chatbot.llm_client = llm
|
| 673 |
+
chatbot._schema_initialized = False
|
| 674 |
+
chatbot._rag_initialized = False
|
| 675 |
+
|
| 676 |
+
# Set LLM client
|
| 677 |
+
chatbot.set_llm_client(llm)
|
| 678 |
+
|
| 679 |
+
# Initialize (introspect schema)
|
| 680 |
+
schema = chatbot.introspector.introspect(force_refresh=True)
|
| 681 |
+
chatbot.sql_validator.set_allowed_tables(schema.table_names)
|
| 682 |
+
chatbot._schema_initialized = True
|
| 683 |
+
|
| 684 |
+
st.session_state.chatbot = chatbot
|
| 685 |
+
|
| 686 |
+
else:
|
| 687 |
+
# Use environment-based connection (existing flow)
|
| 688 |
+
chatbot = create_chatbot(llm)
|
| 689 |
+
chatbot.set_llm_client(llm)
|
| 690 |
+
|
| 691 |
+
success, msg = chatbot.initialize()
|
| 692 |
+
if not success:
|
| 693 |
+
st.error(f"Initialization failed: {msg}")
|
| 694 |
+
return False
|
| 695 |
+
|
| 696 |
+
st.session_state.chatbot = chatbot
|
| 697 |
+
st.session_state.custom_db_connection = None
|
| 698 |
+
|
| 699 |
+
st.session_state.llm = llm
|
| 700 |
+
st.session_state.initialized = True
|
| 701 |
+
st.session_state.indexed = False # Reset index status on new connection
|
| 702 |
+
|
| 703 |
+
# Clear RAG index to ensure no data from previous DB connection persists
|
| 704 |
+
if hasattr(chatbot, 'rag_engine') and hasattr(chatbot.rag_engine, 'clear_index'):
|
| 705 |
+
chatbot.rag_engine.clear_index()
|
| 706 |
+
|
| 707 |
+
# Create memory with appropriate connection
|
| 708 |
+
db_conn = st.session_state.custom_db_connection or get_db()
|
| 709 |
+
st.session_state.memory = create_custom_memory(
|
| 710 |
+
st.session_state.session_id,
|
| 711 |
+
st.session_state.user_id,
|
| 712 |
+
db_conn,
|
| 713 |
+
llm,
|
| 714 |
+
st.session_state.enable_summarization,
|
| 715 |
+
st.session_state.summary_threshold
|
| 716 |
+
)
|
| 717 |
+
|
| 718 |
+
return True
|
| 719 |
+
|
| 720 |
+
except Exception as e:
|
| 721 |
+
st.error(f"Error: {str(e)}")
|
| 722 |
+
import traceback
|
| 723 |
+
st.error(traceback.format_exc())
|
| 724 |
+
return False
|
| 725 |
+
|
| 726 |
+
|
| 727 |
+
def ingest_csv(uploaded_file):
|
| 728 |
+
"""Ingest a CSV file into a SQLite database."""
|
| 729 |
+
from sqlalchemy import create_engine
|
| 730 |
+
|
| 731 |
+
try:
|
| 732 |
+
# 1. Read CSV
|
| 733 |
+
# Reset file pointer to beginning in case it was read before
|
| 734 |
+
uploaded_file.seek(0)
|
| 735 |
+
df = pd.read_csv(uploaded_file)
|
| 736 |
+
|
| 737 |
+
# 2. Clean table name from filename
|
| 738 |
+
table_name = Path(uploaded_file.name).stem.replace(" ", "_").replace("-", "_").lower()
|
| 739 |
+
# Ensure it starts with a letter and only contains alphanumeric/underscore
|
| 740 |
+
table_name = "".join([c for c in table_name if c.isalnum() or c == "_"])
|
| 741 |
+
if not table_name[0].isalpha():
|
| 742 |
+
table_name = "t_" + table_name
|
| 743 |
+
|
| 744 |
+
# 3. Create/Connect to SQLite DB
|
| 745 |
+
db_path = "ingested_data.db"
|
| 746 |
+
engine = create_engine(f"sqlite:///{db_path}")
|
| 747 |
+
|
| 748 |
+
# 4. Write to DB
|
| 749 |
+
df.to_sql(table_name, engine, if_exists='replace', index=False)
|
| 750 |
+
|
| 751 |
+
return True, table_name, len(df)
|
| 752 |
+
except Exception as e:
|
| 753 |
+
return False, str(e), 0
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
def index_data():
|
| 757 |
+
"""Index text data from the database."""
|
| 758 |
+
if st.session_state.chatbot:
|
| 759 |
+
progress = st.progress(0)
|
| 760 |
+
status = st.empty()
|
| 761 |
+
|
| 762 |
+
# Get schema from the correct introspector
|
| 763 |
+
schema = st.session_state.chatbot.introspector.introspect()
|
| 764 |
+
total_tables = len(schema.tables)
|
| 765 |
+
indexed = 0
|
| 766 |
+
|
| 767 |
+
def progress_callback(table_name, docs):
|
| 768 |
+
nonlocal indexed
|
| 769 |
+
indexed += 1
|
| 770 |
+
progress.progress(indexed / total_tables)
|
| 771 |
+
status.text(f"Indexed {table_name}: {docs} documents")
|
| 772 |
+
|
| 773 |
+
total_docs = st.session_state.chatbot.index_text_data(progress_callback)
|
| 774 |
+
st.session_state.indexed = True
|
| 775 |
+
status.text(f"Total: {total_docs} documents indexed")
|
| 776 |
+
|
| 777 |
+
|
| 778 |
+
def render_schema_explorer():
|
| 779 |
+
"""Render schema explorer in an expander."""
|
| 780 |
+
if not st.session_state.initialized:
|
| 781 |
+
return
|
| 782 |
+
|
| 783 |
+
with st.expander("📋 Database Schema", expanded=False):
|
| 784 |
+
try:
|
| 785 |
+
schema = st.session_state.chatbot.introspector.introspect()
|
| 786 |
+
|
| 787 |
+
tab_list, tab_erd = st.tabs(["📋 Table List", "🕸️ Schema Diagram"])
|
| 788 |
+
|
| 789 |
+
with tab_list:
|
| 790 |
+
st.markdown("Uncheck tables to exclude them from the chat context.")
|
| 791 |
+
|
| 792 |
+
for table_name, table_info in schema.tables.items():
|
| 793 |
+
col1, col2 = st.columns([0.05, 0.95])
|
| 794 |
+
|
| 795 |
+
with col1:
|
| 796 |
+
is_active = table_name not in st.session_state.ignored_tables
|
| 797 |
+
active = st.checkbox(
|
| 798 |
+
"Use",
|
| 799 |
+
value=is_active,
|
| 800 |
+
key=f"use_{table_name}",
|
| 801 |
+
label_visibility="collapsed",
|
| 802 |
+
help=f"Include {table_name} in chat analysis"
|
| 803 |
+
)
|
| 804 |
+
|
| 805 |
+
if not active:
|
| 806 |
+
st.session_state.ignored_tables.add(table_name)
|
| 807 |
+
else:
|
| 808 |
+
st.session_state.ignored_tables.discard(table_name)
|
| 809 |
+
|
| 810 |
+
with col2:
|
| 811 |
+
with st.container():
|
| 812 |
+
st.markdown(f"**{table_name}** ({table_info.row_count or '?'} rows)")
|
| 813 |
+
|
| 814 |
+
cols = []
|
| 815 |
+
for col in table_info.columns:
|
| 816 |
+
pk = "🔑" if col.is_primary_key else ""
|
| 817 |
+
txt = "📝" if col.is_text_type else ""
|
| 818 |
+
cols.append(f"`{col.name}` {col.data_type} {pk}{txt}")
|
| 819 |
+
|
| 820 |
+
st.caption(" | ".join(cols))
|
| 821 |
+
st.divider()
|
| 822 |
+
|
| 823 |
+
with tab_erd:
|
| 824 |
+
if len(schema.tables) > 50:
|
| 825 |
+
st.warning("⚠️ Too many tables to visualize effectively (limit: 50).")
|
| 826 |
+
else:
|
| 827 |
+
try:
|
| 828 |
+
# Build Graphviz DOT string
|
| 829 |
+
dot = ['digraph Database {']
|
| 830 |
+
dot.append(' rankdir=LR;')
|
| 831 |
+
dot.append(' node [shape=box, style="filled,rounded", fillcolor="#f0f2f6", fontname="Arial", fontsize=10];')
|
| 832 |
+
dot.append(' edge [fontname="Arial", fontsize=9, color="#666666"];')
|
| 833 |
+
|
| 834 |
+
# Add nodes (tables)
|
| 835 |
+
for table_name in schema.tables:
|
| 836 |
+
if table_name not in st.session_state.ignored_tables:
|
| 837 |
+
dot.append(f' "{table_name}" [label="{table_name}", fillcolor="#e1effe", color="#1e40af"];')
|
| 838 |
+
else:
|
| 839 |
+
dot.append(f' "{table_name}" [label="{table_name} (ignored)", fillcolor="#f3f4f6", color="#9ca3af", fontcolor="#9ca3af"];')
|
| 840 |
+
|
| 841 |
+
# Add edges (relationships)
|
| 842 |
+
has_edges = False
|
| 843 |
+
for table_name, table_info in schema.tables.items():
|
| 844 |
+
for col_name, ref_str in table_info.foreign_keys.items():
|
| 845 |
+
# ref_str format: "referenced_table.referenced_column"
|
| 846 |
+
if "." in ref_str:
|
| 847 |
+
ref_table = ref_str.split(".")[0]
|
| 848 |
+
# specific_col = ref_str.split(".")[1]
|
| 849 |
+
|
| 850 |
+
# Only draw if both tables exist in our schema list
|
| 851 |
+
if ref_table in schema.tables:
|
| 852 |
+
dot.append(f' "{table_name}" -> "{ref_table}" [label="{col_name}"];')
|
| 853 |
+
has_edges = True
|
| 854 |
+
|
| 855 |
+
dot.append('}')
|
| 856 |
+
graph_code = "\n".join(dot)
|
| 857 |
+
st.graphviz_chart(graph_code, width="stretch")
|
| 858 |
+
|
| 859 |
+
if not has_edges:
|
| 860 |
+
st.info("No foreign key relationships detected in the schema metadata.")
|
| 861 |
+
|
| 862 |
+
except Exception as e:
|
| 863 |
+
st.error(f"Could not render diagram: {e}")
|
| 864 |
+
|
| 865 |
+
except Exception as e:
|
| 866 |
+
st.error(f"Error loading schema: {e}")
|
| 867 |
+
|
| 868 |
+
|
| 869 |
+
def render_chat_interface():
|
| 870 |
+
"""Render the main chat interface."""
|
| 871 |
+
st.title("🤖 OnceDataBot")
|
| 872 |
+
st.caption("Schema-agnostic chatbot • MySQL | PostgreSQL • Powered by Groq (FREE!)")
|
| 873 |
+
|
| 874 |
+
# Schema explorer
|
| 875 |
+
render_schema_explorer()
|
| 876 |
+
|
| 877 |
+
# Chat container
|
| 878 |
+
chat_container = st.container()
|
| 879 |
+
|
| 880 |
+
with chat_container:
|
| 881 |
+
# Display messages
|
| 882 |
+
for i, msg in enumerate(st.session_state.messages):
|
| 883 |
+
with st.chat_message(msg["role"]):
|
| 884 |
+
# Create columns for message and favorite button
|
| 885 |
+
msg_col, fav_col = st.columns([0.95, 0.05])
|
| 886 |
+
|
| 887 |
+
with msg_col:
|
| 888 |
+
st.markdown(msg["content"])
|
| 889 |
+
|
| 890 |
+
with fav_col:
|
| 891 |
+
# Favorite button for assistant messages
|
| 892 |
+
if msg["role"] == "assistant":
|
| 893 |
+
is_favorited = i in st.session_state.favorites
|
| 894 |
+
if st.button(
|
| 895 |
+
"⭐" if is_favorited else "☆",
|
| 896 |
+
key=f"fav_{i}",
|
| 897 |
+
help="Click to favorite/unfavorite this response"
|
| 898 |
+
):
|
| 899 |
+
if is_favorited:
|
| 900 |
+
st.session_state.favorites.remove(i)
|
| 901 |
+
else:
|
| 902 |
+
st.session_state.favorites.append(i)
|
| 903 |
+
st.rerun()
|
| 904 |
+
|
| 905 |
+
# Show metadata for assistant messages
|
| 906 |
+
if msg["role"] == "assistant" and "metadata" in msg:
|
| 907 |
+
meta = msg["metadata"]
|
| 908 |
+
|
| 909 |
+
# Show token usage in a dropdown expander
|
| 910 |
+
if "token_usage" in meta:
|
| 911 |
+
usage = meta["token_usage"]
|
| 912 |
+
total = usage.get('total', 0)
|
| 913 |
+
|
| 914 |
+
with st.expander(f"📊 Token Usage ({total:,} total)", expanded=False):
|
| 915 |
+
# Create styled token usage boxes using columns
|
| 916 |
+
st.markdown("""
|
| 917 |
+
<style>
|
| 918 |
+
.token-box {
|
| 919 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 920 |
+
border-radius: 12px;
|
| 921 |
+
padding: 12px 16px;
|
| 922 |
+
color: white;
|
| 923 |
+
text-align: center;
|
| 924 |
+
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
|
| 925 |
+
margin: 4px 0;
|
| 926 |
+
}
|
| 927 |
+
.token-box-input {
|
| 928 |
+
background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
|
| 929 |
+
box-shadow: 0 4px 15px rgba(17, 153, 142, 0.3);
|
| 930 |
+
}
|
| 931 |
+
.token-box-output {
|
| 932 |
+
background: linear-gradient(135deg, #ee0979 0%, #ff6a00 100%);
|
| 933 |
+
box-shadow: 0 4px 15px rgba(238, 9, 121, 0.3);
|
| 934 |
+
}
|
| 935 |
+
.token-box-total {
|
| 936 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 937 |
+
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
|
| 938 |
+
}
|
| 939 |
+
.token-label {
|
| 940 |
+
font-size: 11px;
|
| 941 |
+
text-transform: uppercase;
|
| 942 |
+
letter-spacing: 1px;
|
| 943 |
+
opacity: 0.9;
|
| 944 |
+
margin-bottom: 4px;
|
| 945 |
+
}
|
| 946 |
+
.token-value {
|
| 947 |
+
font-size: 20px;
|
| 948 |
+
font-weight: 700;
|
| 949 |
+
}
|
| 950 |
+
</style>
|
| 951 |
+
""", unsafe_allow_html=True)
|
| 952 |
+
|
| 953 |
+
col1, col2, col3 = st.columns(3)
|
| 954 |
+
|
| 955 |
+
with col1:
|
| 956 |
+
st.markdown(f"""
|
| 957 |
+
<div class="token-box token-box-input">
|
| 958 |
+
<div class="token-label">📥 Input Tokens</div>
|
| 959 |
+
<div class="token-value">{usage.get('input', 0):,}</div>
|
| 960 |
+
</div>
|
| 961 |
+
""", unsafe_allow_html=True)
|
| 962 |
+
|
| 963 |
+
with col2:
|
| 964 |
+
st.markdown(f"""
|
| 965 |
+
<div class="token-box token-box-output">
|
| 966 |
+
<div class="token-label">📤 Output Tokens</div>
|
| 967 |
+
<div class="token-value">{usage.get('output', 0):,}</div>
|
| 968 |
+
</div>
|
| 969 |
+
""", unsafe_allow_html=True)
|
| 970 |
+
|
| 971 |
+
with col3:
|
| 972 |
+
st.markdown(f"""
|
| 973 |
+
<div class="token-box token-box-total">
|
| 974 |
+
<div class="token-label">📊 Total Tokens</div>
|
| 975 |
+
<div class="token-value">{usage.get('total', 0):,}</div>
|
| 976 |
+
</div>
|
| 977 |
+
""", unsafe_allow_html=True)
|
| 978 |
+
|
| 979 |
+
if meta.get("query_type"):
|
| 980 |
+
# Show query type and execution time on same line
|
| 981 |
+
info_text = f"Query type: {meta['query_type']}"
|
| 982 |
+
if meta.get("execution_time"):
|
| 983 |
+
info_text += f" • ⏱️ {meta['execution_time']:.2f}s"
|
| 984 |
+
st.caption(info_text)
|
| 985 |
+
|
| 986 |
+
# SQL Query expander
|
| 987 |
+
if meta.get("sql_query"):
|
| 988 |
+
with st.expander("🛠️ SQL Query & Details"):
|
| 989 |
+
st.code(meta["sql_query"], language="sql")
|
| 990 |
+
|
| 991 |
+
# Visualizations and CSV export
|
| 992 |
+
if meta.get("sql_results"):
|
| 993 |
+
# Only render viz if we have results
|
| 994 |
+
render_visualization(meta["sql_results"], f"viz_{i}")
|
| 995 |
+
|
| 996 |
+
# CSV Export button
|
| 997 |
+
csv_data = export_results_to_csv(meta["sql_results"])
|
| 998 |
+
if csv_data:
|
| 999 |
+
st.download_button(
|
| 1000 |
+
label="📊 Export to CSV",
|
| 1001 |
+
data=csv_data,
|
| 1002 |
+
file_name=f"query_results_{i}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
|
| 1003 |
+
mime="text/csv",
|
| 1004 |
+
key=f"csv_export_{i}",
|
| 1005 |
+
help="Download query results as CSV file"
|
| 1006 |
+
)
|
| 1007 |
+
|
| 1008 |
+
# Chat input
|
| 1009 |
+
if prompt := st.chat_input("Ask about your data..."):
|
| 1010 |
+
if not st.session_state.initialized:
|
| 1011 |
+
st.error("Please connect to a database first!")
|
| 1012 |
+
return
|
| 1013 |
+
|
| 1014 |
+
# Add user message
|
| 1015 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 1016 |
+
|
| 1017 |
+
# Calculate memory context for display? No, just render user msg
|
| 1018 |
+
with st.chat_message("user"):
|
| 1019 |
+
st.markdown(prompt)
|
| 1020 |
+
|
| 1021 |
+
# Get response
|
| 1022 |
+
with st.spinner("Thinking..."):
|
| 1023 |
+
try:
|
| 1024 |
+
# Add memory interaction
|
| 1025 |
+
if st.session_state.memory:
|
| 1026 |
+
st.session_state.memory.add_message("user", prompt)
|
| 1027 |
+
|
| 1028 |
+
# Track execution time
|
| 1029 |
+
start_time = time.time()
|
| 1030 |
+
|
| 1031 |
+
response = st.session_state.chatbot.chat(
|
| 1032 |
+
prompt,
|
| 1033 |
+
st.session_state.memory,
|
| 1034 |
+
ignored_tables=list(st.session_state.ignored_tables),
|
| 1035 |
+
language=st.session_state.response_language
|
| 1036 |
+
)
|
| 1037 |
+
|
| 1038 |
+
execution_time = time.time() - start_time
|
| 1039 |
+
|
| 1040 |
+
|
| 1041 |
+
|
| 1042 |
+
# Create metadata dict
|
| 1043 |
+
metadata = {
|
| 1044 |
+
"query_type": response.query_type,
|
| 1045 |
+
"sql_query": response.sql_query,
|
| 1046 |
+
"sql_results": response.sql_results,
|
| 1047 |
+
"token_usage": response.token_usage,
|
| 1048 |
+
"execution_time": execution_time
|
| 1049 |
+
}
|
| 1050 |
+
|
| 1051 |
+
# Save to session state
|
| 1052 |
+
st.session_state.messages.append({
|
| 1053 |
+
"role": "assistant",
|
| 1054 |
+
"content": response.answer,
|
| 1055 |
+
"metadata": metadata
|
| 1056 |
+
})
|
| 1057 |
+
|
| 1058 |
+
# Set flag to auto-read the latest response
|
| 1059 |
+
st.session_state.auto_read_latest = True
|
| 1060 |
+
|
| 1061 |
+
# Save to active memory
|
| 1062 |
+
if st.session_state.memory:
|
| 1063 |
+
st.session_state.memory.add_message("assistant", response.answer)
|
| 1064 |
+
|
| 1065 |
+
st.rerun()
|
| 1066 |
+
|
| 1067 |
+
except Exception as e:
|
| 1068 |
+
st.error(f"An error occurred: {e}")
|
| 1069 |
+
import traceback
|
| 1070 |
+
st.error(traceback.format_exc())
|
| 1071 |
+
|
| 1072 |
+
|
| 1073 |
+
def main():
|
| 1074 |
+
"""Main application entry point."""
|
| 1075 |
+
init_session_state()
|
| 1076 |
+
|
| 1077 |
+
# Auto-connect to environment database on first load
|
| 1078 |
+
if "auto_connect_attempted" not in st.session_state:
|
| 1079 |
+
st.session_state.auto_connect_attempted = True
|
| 1080 |
+
if st.session_state.db_source == "environment":
|
| 1081 |
+
success = initialize_chatbot()
|
| 1082 |
+
if success:
|
| 1083 |
+
st.toast("✅ Auto-connected to database!")
|
| 1084 |
+
|
| 1085 |
+
render_sidebar()
|
| 1086 |
+
render_chat_interface()
|
| 1087 |
+
|
| 1088 |
+
|
| 1089 |
+
if __name__ == "__main__":
|
| 1090 |
+
main()
|