Spaces:
Running
Running
File size: 46,140 Bytes
8ff817c |
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 |
"""
DS-STAR Gradio Application
A modern web interface for the DS-STAR Multi-Agent Data Science System.
Created for the Hugging Face MCP 1st Birthday Hackathon.
"""
import os
import shutil
from typing import Generator
import gradio as gr
import httpx
from src.config import get_llm
from src.graph import build_ds_star_graph, create_initial_state
# ==================== MODEL FETCHING ====================
# Store fetch status for UI feedback
_last_fetch_status = {"success": False, "message": "", "from_api": False}
def fetch_google_models(api_key: str | None = None) -> tuple[list[str], str]:
"""Fetch available models from Google Gemini API. Returns (models, status_message)."""
api_key = api_key or os.getenv("GOOGLE_API_KEY", "")
fallback = [
"gemini-2.0-flash",
"gemini-1.5-pro",
"gemini-1.5-flash",
"gemini-1.0-pro",
]
if not api_key:
return fallback, "⚠️ No API key - showing default models"
try:
url = f"https://generativelanguage.googleapis.com/v1beta/models?key={api_key}"
response = httpx.get(url, timeout=15)
if response.status_code == 200:
data = response.json()
models = []
for model in data.get("models", []):
name = model.get("name", "").replace("models/", "")
# Filter for chat/generate models
if "generateContent" in model.get("supportedGenerationMethods", []):
models.append(name)
if models:
return sorted(
models, reverse=True
), f"✅ Fetched {len(models)} models from API"
return fallback, "⚠️ No compatible models found - showing defaults"
elif response.status_code == 400:
return fallback, "❌ Invalid API key format"
elif response.status_code == 403:
return fallback, "❌ API key invalid or expired"
else:
return fallback, f"❌ API error: {response.status_code}"
except httpx.TimeoutException:
return fallback, "❌ Request timed out"
except httpx.ConnectError:
return fallback, "❌ Connection failed - check internet"
except Exception as e:
return fallback, f"❌ Error: {str(e)[:50]}"
def fetch_openai_models(
api_key: str | None = None, base_url: str | None = None
) -> tuple[list[str], str]:
"""Fetch available models from OpenAI API or compatible endpoint. Returns (models, status_message)."""
api_key = api_key or os.getenv("OPENAI_API_KEY", "")
base_url = base_url or "https://api.openai.com/v1"
fallback = ["gpt-4o", "gpt-4o-mini", "gpt-4-turbo", "gpt-4", "gpt-3.5-turbo"]
if not api_key:
return fallback, "⚠️ No API key - showing default models"
try:
headers = {"Authorization": f"Bearer {api_key}"}
endpoint = f"{base_url.rstrip('/')}/models"
response = httpx.get(endpoint, headers=headers, timeout=15)
if response.status_code == 200:
data = response.json()
models = []
for model in data.get("data", []):
model_id = model.get("id", "")
# For OpenAI, filter chat models; for custom endpoints, include all
if base_url != "https://api.openai.com/v1":
models.append(model_id)
elif model_id.startswith(("gpt-", "o1", "o3", "o4", "chatgpt")):
models.append(model_id)
if models:
return sorted(
models, reverse=True
), f"✅ Fetched {len(models)} models from API"
return fallback, "⚠️ No chat models found - showing defaults"
elif response.status_code == 401:
return fallback, "❌ Invalid API key"
elif response.status_code == 403:
return fallback, "❌ Access denied"
else:
return fallback, f"❌ API error: {response.status_code}"
except httpx.TimeoutException:
return fallback, "❌ Request timed out"
except httpx.ConnectError:
return fallback, "❌ Connection failed - check URL/internet"
except Exception as e:
return fallback, f"❌ Error: {str(e)[:50]}"
def fetch_anthropic_models(api_key: str | None = None) -> tuple[list[str], str]:
"""Fetch available models from Anthropic API. Returns (models, status_message)."""
api_key = api_key or os.getenv("ANTHROPIC_API_KEY", "")
fallback = [
"claude-sonnet-4-20250514",
"claude-3-5-sonnet-20241022",
"claude-3-5-haiku-20241022",
"claude-3-opus-20240229",
]
if not api_key:
return fallback, "⚠️ No API key - showing default models"
try:
headers = {"x-api-key": api_key, "anthropic-version": "2023-06-01"}
response = httpx.get(
"https://api.anthropic.com/v1/models", headers=headers, timeout=15
)
if response.status_code == 200:
data = response.json()
models = [
model.get("id", "") for model in data.get("data", []) if model.get("id")
]
if models:
return sorted(
models, reverse=True
), f"✅ Fetched {len(models)} models from API"
return fallback, "⚠️ No models found - showing defaults"
elif response.status_code == 401:
return fallback, "❌ Invalid API key"
elif response.status_code == 403:
return fallback, "❌ Access denied"
else:
# Anthropic may not have a public models endpoint, use fallback
return fallback, "ℹ️ Using known Anthropic models"
except httpx.TimeoutException:
return fallback, "❌ Request timed out"
except httpx.ConnectError:
return fallback, "❌ Connection failed"
except Exception as e:
return fallback, f"❌ Error: {str(e)[:50]}"
def fetch_models_for_provider(
provider: str, api_key: str | None = None, base_url: str | None = None
) -> tuple[list[str], str]:
"""Fetch models for the given provider. Returns (models, status_message)."""
if provider == "google":
return fetch_google_models(api_key)
elif provider == "openai":
return fetch_openai_models(api_key)
elif provider == "anthropic":
return fetch_anthropic_models(api_key)
elif provider == "custom":
if not base_url:
return [], "❌ Please enter a Base URL for custom provider"
return fetch_openai_models(api_key, base_url)
return [], "❌ Unknown provider"
# ==================== CUSTOM THEME ====================
def create_ds_star_theme():
"""Create a modern dark theme for DS-STAR."""
return gr.themes.Base(
primary_hue=gr.themes.colors.violet,
secondary_hue=gr.themes.colors.purple,
neutral_hue=gr.themes.colors.slate,
font=[
gr.themes.GoogleFont("Inter"),
"ui-sans-serif",
"system-ui",
"sans-serif",
],
font_mono=[gr.themes.GoogleFont("JetBrains Mono"), "ui-monospace", "monospace"],
).set(
# Body - Dark background
body_background_fill="#0a0a0f",
body_background_fill_dark="#0a0a0f",
body_text_color="#e4e4e7",
body_text_color_dark="#e4e4e7",
# Buttons
button_primary_background_fill="linear-gradient(135deg, #7c3aed 0%, #8b5cf6 100%)",
button_primary_background_fill_hover="linear-gradient(135deg, #6d28d9 0%, #7c3aed 100%)",
button_primary_text_color="white",
button_primary_border_color="transparent",
button_secondary_background_fill="transparent",
button_secondary_background_fill_hover="rgba(139, 92, 246, 0.15)",
button_secondary_border_color="#7c3aed",
button_secondary_text_color="#a78bfa",
# Blocks
block_background_fill="#18181b",
block_background_fill_dark="#18181b",
block_border_width="1px",
block_border_color="#27272a",
block_border_color_dark="#27272a",
block_shadow="none",
block_title_text_weight="600",
block_title_text_size="*text_md",
block_label_text_weight="500",
block_label_text_size="*text_sm",
block_radius="12px",
block_padding="16px",
# Inputs
input_background_fill="#27272a",
input_background_fill_dark="#27272a",
input_border_color="#3f3f46",
input_border_color_dark="#3f3f46",
input_border_width="1px",
input_shadow="none",
input_radius="8px",
# Panels
panel_background_fill="#18181b",
panel_background_fill_dark="#18181b",
panel_border_width="0px",
# Spacing
layout_gap="16px",
# Shadows
shadow_drop="none",
shadow_drop_lg="none",
# Checkbox
checkbox_background_color="#27272a",
checkbox_background_color_dark="#27272a",
checkbox_border_color="#3f3f46",
checkbox_border_color_dark="#3f3f46",
checkbox_label_text_color="#a1a1aa",
checkbox_label_text_color_dark="#a1a1aa",
# Slider
slider_color="#7c3aed",
slider_color_dark="#8b5cf6",
)
# ==================== CSS STYLING ====================
CUSTOM_CSS = """
/* Modern Font Import */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap');
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600&display=swap');
/* Root variables */
:root {
--bg-primary: #0a0a0f;
--bg-secondary: #18181b;
--bg-tertiary: #27272a;
--border-color: #3f3f46;
--text-primary: #fafafa;
--text-secondary: #a1a1aa;
--text-muted: #71717a;
--accent-primary: #8b5cf6;
--accent-secondary: #7c3aed;
--accent-glow: rgba(139, 92, 246, 0.3);
--success: #22c55e;
--error: #ef4444;
}
/* Main container - Dark background */
.gradio-container {
max-width: 1400px !important;
margin: 0 auto !important;
padding: 32px !important;
font-family: 'Inter', sans-serif !important;
background: var(--bg-primary) !important;
min-height: 100vh;
}
/* Remove all default shadows and borders for cleaner look */
.gradio-container * {
box-shadow: none !important;
}
/* ===== HEADER ===== */
.header-section {
background: linear-gradient(135deg, #1e1b4b 0%, #312e81 50%, #3730a3 100%);
border-radius: 16px;
padding: 40px 32px;
margin-bottom: 24px;
border: 1px solid #4338ca;
position: relative;
overflow: hidden;
}
.header-section::before {
content: '';
position: absolute;
top: 0;
right: 0;
width: 40%;
height: 100%;
background: radial-gradient(ellipse at top right, rgba(139, 92, 246, 0.3), transparent 70%);
}
.header-content {
position: relative;
z-index: 1;
text-align: center;
}
.header-title {
font-size: 2.75rem;
font-weight: 800;
color: #fff;
margin: 0 0 8px 0;
letter-spacing: -0.02em;
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
}
.header-title .star-icon {
font-size: 2.2rem;
}
.header-subtitle {
font-size: 1.1rem;
color: rgba(255, 255, 255, 0.7);
margin: 0;
font-weight: 400;
}
.header-badges {
display: flex;
justify-content: center;
gap: 10px;
margin-top: 20px;
flex-wrap: wrap;
}
.header-badge {
padding: 6px 14px;
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 20px;
font-size: 0.8rem;
font-weight: 500;
color: rgba(255, 255, 255, 0.9);
}
/* ===== CARDS & GROUPS ===== */
.dark-card {
background: var(--bg-secondary) !important;
border: 1px solid var(--border-color) !important;
border-radius: 12px !important;
padding: 20px !important;
margin-bottom: 16px !important;
}
/* Group styling */
.gr-group {
background: var(--bg-secondary) !important;
border: 1px solid var(--border-color) !important;
border-radius: 12px !important;
padding: 20px !important;
}
/* ===== SECTION HEADERS ===== */
.section-header {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 16px;
padding-bottom: 12px;
border-bottom: 1px solid var(--border-color);
}
.section-icon {
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(135deg, var(--accent-secondary), var(--accent-primary));
border-radius: 8px;
font-size: 1rem;
}
.section-title {
font-size: 1.1rem;
font-weight: 600;
color: var(--text-primary);
margin: 0;
}
/* ===== ACCORDIONS ===== */
.gr-accordion {
border: 1px solid var(--border-color) !important;
border-radius: 10px !important;
overflow: hidden !important;
margin-bottom: 12px !important;
background: var(--bg-secondary) !important;
}
.gr-accordion > .label-wrap {
background: var(--bg-tertiary) !important;
padding: 12px 16px !important;
cursor: pointer !important;
border: none !important;
}
.gr-accordion > .label-wrap:hover {
background: #323238 !important;
}
.gr-accordion > .label-wrap span {
font-weight: 600 !important;
font-size: 0.95rem !important;
color: var(--text-primary) !important;
}
.gr-accordion > div:last-child {
padding: 16px !important;
background: var(--bg-secondary) !important;
}
/* ===== BUTTONS ===== */
button.primary, .gr-button-primary {
background: linear-gradient(135deg, var(--accent-secondary), var(--accent-primary)) !important;
border: none !important;
border-radius: 8px !important;
padding: 10px 20px !important;
font-weight: 600 !important;
font-size: 0.9rem !important;
color: white !important;
cursor: pointer !important;
transition: all 0.2s ease !important;
}
button.primary:hover, .gr-button-primary:hover {
opacity: 0.9 !important;
transform: translateY(-1px) !important;
}
button.secondary, .gr-button-secondary {
background: transparent !important;
border: 1px solid var(--accent-primary) !important;
border-radius: 8px !important;
color: var(--accent-primary) !important;
font-weight: 500 !important;
padding: 10px 20px !important;
transition: all 0.2s ease !important;
}
button.secondary:hover, .gr-button-secondary:hover {
background: rgba(139, 92, 246, 0.1) !important;
}
/* Refresh button */
.refresh-btn {
min-width: 40px !important;
width: 40px !important;
height: 40px !important;
padding: 0 !important;
display: flex !important;
align-items: center !important;
justify-content: center !important;
border-radius: 8px !important;
background: var(--bg-tertiary) !important;
border: 1px solid var(--border-color) !important;
font-size: 1rem !important;
color: var(--text-secondary) !important;
transition: all 0.2s ease !important;
}
.refresh-btn:hover {
background: var(--accent-primary) !important;
border-color: var(--accent-primary) !important;
color: white !important;
}
/* ===== INPUTS ===== */
input, textarea, select, .gr-input, .gr-text-input {
background: var(--bg-tertiary) !important;
border: 1px solid var(--border-color) !important;
border-radius: 8px !important;
color: var(--text-primary) !important;
padding: 10px 14px !important;
font-size: 0.9rem !important;
transition: border-color 0.2s ease !important;
}
input:focus, textarea:focus, select:focus {
border-color: var(--accent-primary) !important;
outline: none !important;
}
input::placeholder, textarea::placeholder {
color: var(--text-muted) !important;
}
/* Dropdown */
.gr-dropdown {
background: var(--bg-tertiary) !important;
}
/* ===== TABS ===== */
.gr-tabs {
background: transparent !important;
}
.gr-tab-nav {
background: var(--bg-secondary) !important;
border-radius: 10px !important;
padding: 4px !important;
margin-bottom: 16px !important;
border: 1px solid var(--border-color) !important;
gap: 4px !important;
display: flex !important;
overflow-x: auto !important;
}
.gr-tab-nav button {
border-radius: 8px !important;
padding: 10px 16px !important;
font-weight: 500 !important;
font-size: 0.85rem !important;
background: transparent !important;
border: none !important;
color: var(--text-secondary) !important;
white-space: nowrap !important;
transition: all 0.2s ease !important;
}
.gr-tab-nav button:hover {
background: var(--bg-tertiary) !important;
color: var(--text-primary) !important;
}
.gr-tab-nav button.selected {
background: var(--accent-primary) !important;
color: white !important;
}
/* ===== CODE OUTPUT ===== */
.code-wrap, .gr-code {
border-radius: 10px !important;
overflow: hidden !important;
border: 1px solid var(--border-color) !important;
}
.code-wrap pre, .gr-code pre {
background: #0d0d12 !important;
padding: 16px !important;
margin: 0 !important;
font-family: 'JetBrains Mono', monospace !important;
font-size: 0.85rem !important;
line-height: 1.5 !important;
max-height: 400px !important;
overflow: auto !important;
}
/* ===== FILE UPLOAD ===== */
.file-upload, .gr-file {
border: 2px dashed var(--border-color) !important;
border-radius: 10px !important;
background: var(--bg-tertiary) !important;
padding: 24px !important;
transition: all 0.2s ease !important;
}
.file-upload:hover, .gr-file:hover {
border-color: var(--accent-primary) !important;
}
/* ===== STATUS DISPLAYS ===== */
.status-box textarea {
font-weight: 600 !important;
color: var(--accent-primary) !important;
background: rgba(139, 92, 246, 0.1) !important;
border: 1px solid rgba(139, 92, 246, 0.3) !important;
border-radius: 8px !important;
}
.step-box textarea {
font-family: 'JetBrains Mono', monospace !important;
font-size: 0.85rem !important;
color: var(--text-secondary) !important;
background: var(--bg-tertiary) !important;
border-radius: 8px !important;
}
/* ===== EXAMPLES - Redesigned as chips ===== */
.gr-examples {
margin-top: 16px !important;
padding-top: 16px !important;
border-top: 1px solid var(--border-color) !important;
}
.gr-examples .label {
font-size: 0.85rem !important;
font-weight: 600 !important;
color: var(--text-secondary) !important;
margin-bottom: 12px !important;
}
.gr-examples-table {
display: flex !important;
flex-wrap: wrap !important;
gap: 8px !important;
}
.gr-examples-table tbody {
display: flex !important;
flex-wrap: wrap !important;
gap: 8px !important;
}
.gr-examples-table tr {
display: contents !important;
}
.gr-examples-table td {
display: block !important;
padding: 0 !important;
}
.gr-examples-table button, .gr-samples-table button {
background: var(--bg-tertiary) !important;
border: 1px solid var(--border-color) !important;
border-radius: 20px !important;
padding: 8px 16px !important;
font-size: 0.8rem !important;
color: var(--text-secondary) !important;
cursor: pointer !important;
transition: all 0.2s ease !important;
white-space: nowrap !important;
max-width: none !important;
}
.gr-examples-table button:hover, .gr-samples-table button:hover {
background: var(--accent-primary) !important;
border-color: var(--accent-primary) !important;
color: white !important;
}
/* ===== FILE LIST ===== */
.file-list {
background: var(--bg-tertiary) !important;
border-radius: 8px !important;
padding: 12px !important;
font-size: 0.85rem !important;
color: var(--text-secondary) !important;
max-height: 120px !important;
overflow-y: auto !important;
}
/* ===== WORKFLOW STEPS ===== */
.workflow-container {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 12px;
padding: 16px;
}
.workflow-step {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 14px;
background: var(--bg-tertiary);
border: 1px solid var(--border-color);
border-radius: 10px;
transition: all 0.2s ease;
}
.workflow-step:hover {
border-color: var(--accent-primary);
}
.step-number {
width: 28px;
height: 28px;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(135deg, var(--accent-secondary), var(--accent-primary));
border-radius: 6px;
color: white;
font-weight: 700;
font-size: 0.8rem;
flex-shrink: 0;
}
.step-content {
flex: 1;
min-width: 0;
}
.step-title {
font-weight: 600;
color: var(--text-primary);
font-size: 0.85rem;
}
.step-desc {
font-size: 0.75rem;
color: var(--text-muted);
margin-top: 2px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* ===== SCROLLBAR ===== */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: var(--bg-tertiary);
border-radius: 3px;
}
::-webkit-scrollbar-thumb {
background: var(--border-color);
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: #52525b;
}
/* ===== LAYOUT FIXES ===== */
.gr-row {
gap: 12px !important;
}
.gr-column {
gap: 12px !important;
}
/* Remove excess padding/margins */
.gr-form {
gap: 12px !important;
}
.gr-block {
padding: 0 !important;
}
/* Label styling */
label, .gr-input-label {
font-size: 0.85rem !important;
font-weight: 500 !important;
color: var(--text-secondary) !important;
margin-bottom: 6px !important;
}
/* Info text */
.gr-info {
font-size: 0.75rem !important;
color: var(--text-muted) !important;
}
/* Fix button alignment in rows */
.gr-button {
height: 40px !important;
}
/* Slider styling */
input[type="range"] {
accent-color: var(--accent-primary) !important;
}
.gr-slider input {
background: var(--bg-tertiary) !important;
}
/* ===== RESPONSIVE ===== */
@media (max-width: 768px) {
.header-title {
font-size: 1.75rem;
}
.gradio-container {
padding: 16px !important;
}
.workflow-container {
grid-template-columns: 1fr;
}
}
"""
# ==================== HELPER FUNCTIONS ====================
def validate_api_key(
provider: str, api_key: str, base_url: str = ""
) -> tuple[bool, str]:
"""Validate that the API key is provided for the selected provider."""
if provider == "custom":
if not api_key or api_key.strip() == "":
return False, "❌ Please provide an API key for custom provider"
if not base_url or base_url.strip() == "":
return False, "❌ Please provide a Base URL for custom provider"
return True, "✅ Custom provider configured"
if not api_key or api_key.strip() == "":
env_var = {
"google": "GOOGLE_API_KEY",
"openai": "OPENAI_API_KEY",
"anthropic": "ANTHROPIC_API_KEY",
}.get(provider, "")
# Check environment variable
if os.getenv(env_var):
return True, f"✅ Using API key from environment variable ({env_var})"
return (
False,
f"❌ Please provide an API key or set the {env_var} environment variable",
)
return True, "✅ API key provided"
def get_model_choices(
provider: str, api_key: str | None = None, base_url: str | None = None
) -> list[str]:
"""Get available models for each provider (fallback list)."""
fallback_models = {
"google": [
"gemini-2.0-flash",
"gemini-1.5-pro",
"gemini-1.5-flash",
],
"openai": [
"gpt-4o",
"gpt-4o-mini",
"gpt-4-turbo",
"gpt-4",
"gpt-3.5-turbo",
],
"anthropic": [
"claude-sonnet-4-20250514",
"claude-3-5-sonnet-20241022",
"claude-3-5-haiku-20241022",
"claude-3-opus-20240229",
],
"custom": [],
}
return fallback_models.get(provider, [])
def update_model_dropdown(provider: str, api_key: str = "", base_url: str = ""):
"""Update model dropdown when provider changes."""
# Fetch models with status
models, status = fetch_models_for_provider(
provider,
api_key.strip() if api_key and api_key.strip() else None,
base_url.strip() if base_url and base_url.strip() else None,
)
if not models:
models = get_model_choices(provider)
return gr.update(choices=models, value=models[0] if models else None)
def update_base_url_visibility(provider: str):
"""Show/hide base URL field based on provider."""
return gr.update(visible=(provider == "custom"))
def refresh_models(provider: str, api_key: str, base_url: str):
"""Refresh the model list from the API."""
models, status = fetch_models_for_provider(
provider,
api_key.strip() if api_key and api_key.strip() else None,
base_url.strip() if base_url and base_url.strip() else None,
)
if models:
return gr.update(choices=models, value=models[0]), status
# Use fallback if no models returned
fallback = get_model_choices(provider)
if fallback:
return gr.update(
choices=fallback, value=fallback[0]
), status or "ℹ️ Using default models"
return gr.update(), status or "❌ No models available"
def copy_uploaded_files(files: list) -> str:
"""Copy uploaded files to the data directory."""
data_dir = os.path.join(os.path.dirname(__file__), "data")
# Clear existing files in data directory (except .gitkeep)
if os.path.exists(data_dir):
for f in os.listdir(data_dir):
if f != ".gitkeep":
file_path = os.path.join(data_dir, f)
if os.path.isfile(file_path):
os.remove(file_path)
else:
os.makedirs(data_dir)
# Copy new files
copied_files = []
if files:
for file_path in files:
if file_path:
filename = os.path.basename(file_path)
dest_path = os.path.join(data_dir, filename)
shutil.copy2(file_path, dest_path)
copied_files.append(filename)
if copied_files:
return f"✅ Uploaded {len(copied_files)} file(s): {', '.join(copied_files)}"
return "ℹ️ No files uploaded. Using existing files in data/ directory."
def list_data_files() -> str:
"""List files currently in the data directory."""
data_dir = os.path.join(os.path.dirname(__file__), "data")
if not os.path.exists(data_dir):
return "No data directory found."
files = [
f
for f in os.listdir(data_dir)
if f != ".gitkeep" and os.path.isfile(os.path.join(data_dir, f))
]
if files:
file_list = "\n".join([f" 📄 {f}" for f in files])
return f"**Files in data/ directory:**\n{file_list}"
return "No data files found. Please upload some files."
# ==================== MAIN WORKFLOW ====================
def run_ds_star_workflow(
query: str,
provider: str,
model: str,
api_key: str,
base_url: str,
max_iterations: int,
temperature: float,
progress=gr.Progress(),
) -> Generator[tuple[str, str, str, str], None, None]:
"""
Run the DS-STAR workflow with streaming updates.
Yields: (status, current_step, code_output, execution_result)
"""
# Validate inputs
if not query or query.strip() == "":
yield "❌ Error", "Please enter a query", "", ""
return
is_valid, message = validate_api_key(provider, api_key, base_url)
if not is_valid:
yield "❌ Configuration Error", message, "", ""
return
# Initialize LLM
yield "🔄 Initializing...", "Setting up LLM connection", "", ""
# For custom provider, use openai with custom base_url
actual_provider = "openai" if provider == "custom" else provider
try:
llm = get_llm(
provider=actual_provider,
model=model,
api_key=api_key if api_key.strip() else None,
temperature=temperature,
base_url=base_url if provider == "custom" and base_url.strip() else None,
)
except Exception as e:
yield "❌ LLM Error", f"Failed to initialize LLM: {str(e)}", "", ""
return
# Build graph
yield "🔄 Building Graph...", "Constructing multi-agent workflow", "", ""
try:
app = build_ds_star_graph(llm, max_iterations)
except Exception as e:
yield "❌ Graph Error", f"Failed to build graph: {str(e)}", "", ""
return
# Create initial state
initial_state = create_initial_state(query, llm, max_iterations)
config = {"configurable": {"thread_id": f"gradio-session-{os.urandom(4).hex()}"}}
# Run workflow with progress updates
step_descriptions = {
"analyzer": "📊 Analyzing data files...",
"planner": "📝 Creating execution plan...",
"coder": "💻 Generating code...",
"verifier": "✅ Verifying solution...",
"router": "🔀 Routing to next step...",
"backtrack": "↩️ Backtracking...",
"finalyzer": "🎯 Finalizing solution...",
}
yield "🚀 Running DS-STAR...", "Starting multi-agent workflow", "", ""
try:
# Stream through the workflow
current_code = ""
current_result = ""
iteration = 0
for event in app.stream(initial_state, config, stream_mode="values"):
# Update progress based on current state
next_node = event.get("next", "")
iteration = event.get("iteration", 0)
step_desc = step_descriptions.get(next_node, f"Processing: {next_node}")
progress_msg = (
f"Iteration {iteration}/{max_iterations}"
if iteration > 0
else "Starting..."
)
current_code = event.get("current_code", current_code) or ""
current_result = event.get("execution_result", current_result) or ""
yield f"🔄 {progress_msg}", step_desc, current_code, current_result
# Final state
final_code = event.get("current_code", "") or ""
final_result = event.get("execution_result", "") or ""
yield "✅ Complete!", "Workflow finished successfully", final_code, final_result
except Exception as e:
import traceback
error_trace = traceback.format_exc()
yield (
"❌ Execution Error",
f"Error: {str(e)}\n\n{error_trace}",
current_code,
current_result,
)
# ==================== GRADIO INTERFACE ====================
def create_gradio_app():
"""Create and configure the Gradio application."""
with gr.Blocks(title="DS-STAR | Multi-Agent Data Science") as demo:
# Header Section
gr.HTML("""
<div class="header-section">
<div class="header-content">
<h1 class="header-title">
<span class="star-icon">✨</span>
DS-STAR
</h1>
<p class="header-subtitle">Multi-Agent System for Automated Data Science Tasks</p>
<div class="header-badges">
<span class="header-badge">🔗 LangGraph</span>
<span class="header-badge">🤗 HuggingFace MCP</span>
<span class="header-badge">🤖 Multi-Agent</span>
</div>
</div>
</div>
""")
with gr.Row():
# Left Column - Configuration (narrower)
with gr.Column(scale=1, min_width=300):
# LLM Configuration - Accordion
with gr.Accordion("🔑 LLM Configuration", open=True):
provider = gr.Dropdown(
choices=["google", "openai", "anthropic", "custom"],
value="google",
label="Provider",
info="Select your LLM provider",
)
base_url = gr.Textbox(
label="Base URL",
placeholder="https://api.together.xyz/v1",
info="OpenAI-compatible API endpoint",
visible=False,
)
with gr.Row():
model = gr.Dropdown(
choices=get_model_choices("google"),
value="gemini-2.0-flash",
label="Model",
scale=5,
)
refresh_models_btn = gr.Button(
"🔄",
variant="secondary",
size="sm",
scale=1,
min_width=40,
elem_classes="refresh-btn",
)
api_key = gr.Textbox(
label="API Key",
type="password",
placeholder="Enter API key or use env variable",
)
api_status = gr.Markdown(
"💡 *Enter API key or set environment variable*"
)
# Advanced Settings - Accordion (closed by default)
with gr.Accordion("⚙️ Advanced Settings", open=False):
max_iterations = gr.Slider(
minimum=1,
maximum=50,
value=20,
step=1,
label="Max Iterations",
info="Maximum refinement cycles",
)
temperature = gr.Slider(
minimum=0.0,
maximum=1.0,
value=0.0,
step=0.1,
label="Temperature",
info="Controls response creativity (0 = deterministic)",
)
# Data Files - Accordion
with gr.Accordion("📁 Data Files", open=True):
file_upload = gr.File(
label="Upload Files",
file_count="multiple",
file_types=[".csv", ".json", ".xlsx", ".parquet", ".txt"],
type="filepath",
)
upload_status = gr.Markdown(
list_data_files(), elem_classes="file-list"
)
refresh_btn = gr.Button(
"🔄 Refresh Files", variant="secondary", size="sm"
)
# Right Column - Main Interface (wider)
with gr.Column(scale=2, min_width=500):
# Query Input Section
gr.HTML("""
<div class="section-header">
<div class="section-icon">💬</div>
<h3 class="section-title">Ask Your Question</h3>
</div>
""")
query_input = gr.Textbox(
label="",
placeholder="e.g., What percentage of transactions use credit cards? Show the distribution by category.",
lines=2,
max_lines=4,
show_label=False,
)
# Buttons Row - properly aligned
with gr.Row():
run_btn = gr.Button(
"🚀 Run Analysis",
variant="primary",
size="lg",
scale=3,
)
clear_btn = gr.Button(
"🗑️ Clear",
variant="secondary",
size="lg",
scale=1,
)
# Example Queries - as clickable chips
gr.HTML("""
<div style="margin-top: 16px; padding-top: 12px; border-top: 1px solid var(--border-color);">
<span style="font-size: 0.8rem; font-weight: 600; color: var(--text-muted); margin-bottom: 8px; display: block;">💡 Quick Examples</span>
</div>
""")
gr.Examples(
examples=[
["Show distribution of transaction amounts"],
["Which category has highest sales?"],
["Find correlations between columns"],
["Create summary statistics report"],
],
inputs=query_input,
label="",
examples_per_page=4,
)
# Status Section
gr.HTML("""
<div class="section-header" style="margin-top: 20px;">
<div class="section-icon">📊</div>
<h3 class="section-title">Status</h3>
</div>
""")
with gr.Row():
status_display = gr.Textbox(
label="Status",
value="⏳ Ready",
interactive=False,
scale=1,
elem_classes="status-box",
lines=1,
max_lines=1,
)
current_step = gr.Textbox(
label="Current Step",
value="Waiting for query...",
interactive=False,
scale=2,
elem_classes="step-box",
lines=1,
max_lines=1,
)
# Results Tabs
with gr.Tabs():
with gr.TabItem("💻 Code", id=0):
code_output = gr.Code(
label="",
language="python",
lines=16,
interactive=False,
show_label=False,
)
with gr.TabItem("📊 Output", id=1):
result_output = gr.Textbox(
label="",
lines=14,
interactive=False,
show_label=False,
)
with gr.TabItem("🔄 Workflow", id=2):
gr.HTML("""
<div class="workflow-container">
<div class="workflow-step">
<div class="step-number">1</div>
<div class="step-content">
<div class="step-title">Analyzer</div>
<div class="step-desc">Examines data structure</div>
</div>
</div>
<div class="workflow-step">
<div class="step-number">2</div>
<div class="step-content">
<div class="step-title">Planner</div>
<div class="step-desc">Creates execution plan</div>
</div>
</div>
<div class="workflow-step">
<div class="step-number">3</div>
<div class="step-content">
<div class="step-title">Coder</div>
<div class="step-desc">Generates Python code</div>
</div>
</div>
<div class="workflow-step">
<div class="step-number">4</div>
<div class="step-content">
<div class="step-title">Verifier</div>
<div class="step-desc">Validates solution</div>
</div>
</div>
<div class="workflow-step">
<div class="step-number">5</div>
<div class="step-content">
<div class="step-title">Router</div>
<div class="step-desc">Decides next step</div>
</div>
</div>
<div class="workflow-step">
<div class="step-number">6</div>
<div class="step-content">
<div class="step-title">Finalyzer</div>
<div class="step-desc">Delivers final result</div>
</div>
</div>
</div>
""")
with gr.TabItem("ℹ️ About", id=3):
gr.Markdown("""
## About DS-STAR
**DS-STAR** (Data Science - Structured Task Analysis and Resolution) is a multi-agent system for automating data science tasks.
### ✨ Features
- 🤖 **Multi-Agent** — Specialized agents for analysis, planning, coding & verification
- 🔄 **Iterative** — Automatically refines solutions
- 🔙 **Backtracking** — Smart rollback when needed
- 💻 **Code Gen** — Produces clean Python code
### 🔌 Providers
**Google Gemini** • **OpenAI GPT** • **Anthropic Claude** • **Custom API**
---
Built for the **HuggingFace MCP Hackathon** • [GitHub](https://github.com/Anurag-Deo/DS-STAR)
""")
# Event Handlers
provider.change(
fn=update_model_dropdown,
inputs=[provider, api_key, base_url],
outputs=[model],
)
provider.change(
fn=update_base_url_visibility,
inputs=[provider],
outputs=[base_url],
)
provider.change(
fn=lambda p, k, b: validate_api_key(p, k, b)[1],
inputs=[provider, api_key, base_url],
outputs=[api_status],
)
api_key.change(
fn=lambda p, k, b: validate_api_key(p, k, b)[1],
inputs=[provider, api_key, base_url],
outputs=[api_status],
)
base_url.change(
fn=lambda p, k, b: validate_api_key(p, k, b)[1],
inputs=[provider, api_key, base_url],
outputs=[api_status],
)
refresh_models_btn.click(
fn=refresh_models,
inputs=[provider, api_key, base_url],
outputs=[model, api_status],
)
file_upload.change(
fn=copy_uploaded_files, inputs=[file_upload], outputs=[upload_status]
)
refresh_btn.click(fn=list_data_files, outputs=[upload_status])
run_btn.click(
fn=run_ds_star_workflow,
inputs=[
query_input,
provider,
model,
api_key,
base_url,
max_iterations,
temperature,
],
outputs=[status_display, current_step, code_output, result_output],
)
clear_btn.click(
fn=lambda: ("⏳ Ready", "Waiting for query...", "", ""),
outputs=[status_display, current_step, code_output, result_output],
)
return demo
# ==================== MAIN ====================
if __name__ == "__main__":
demo = create_gradio_app()
theme = create_ds_star_theme()
demo.launch(share=False, show_error=True, theme=theme, css=CUSTOM_CSS)
|