-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1835 lines (1516 loc) · 84.5 KB
/
app.py
File metadata and controls
1835 lines (1516 loc) · 84.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
TraceMind MCP Server - Hugging Face Space Entry Point (Track 1)
This file serves as the entry point for HuggingFace Space deployment.
Exposes 11 AI-powered MCP tools + 3 Resources + 3 Prompts via Gradio's native MCP support.
Built on Open Source Foundation:
🔭 TraceVerde (genai_otel_instrument) - Automatic OpenTelemetry instrumentation
for LLM frameworks (LiteLLM, Transformers, LangChain, etc.)
GitHub: https://github.com/Mandark-droid/genai_otel_instrument
PyPI: https://pypi.org/project/genai-otel-instrument
📊 SMOLTRACE - Agent evaluation engine with OTEL tracing built-in
Generates structured datasets (leaderboard, results, traces, metrics)
GitHub: https://github.com/Mandark-droid/SMOLTRACE
PyPI: https://pypi.org/project/smoltrace/
The Flow: TraceVerde instruments → SMOLTRACE evaluates → TraceMind analyzes
Architecture:
User → MCP Client (Claude Desktop, Continue, Cline, etc.)
→ MCP Endpoint (Gradio SSE)
→ TraceMind MCP Server (this file)
→ Tools (mcp_tools.py)
→ Google Gemini 2.5 Flash API
For Track 1: Building MCP Servers - Enterprise Category
https://huggingface.co/MCP-1st-Birthday
Tools Provided:
📊 analyze_leaderboard - AI-powered leaderboard analysis
🐛 debug_trace - Debug agent execution traces with AI
💰 estimate_cost - Predict evaluation costs before running
⚖️ compare_runs - Compare evaluation runs with AI analysis
📋 analyze_results - Analyze detailed test results with optimization recommendations
🏆 get_top_performers - Get top N models from leaderboard (optimized)
📈 get_leaderboard_summary - Get leaderboard overview statistics
📦 get_dataset - Load SMOLTRACE datasets as JSON
🧪 generate_synthetic_dataset - Create domain-specific test datasets
📝 generate_prompt_template - Generate customized smolagents prompt templates
📤 push_dataset_to_hub - Upload datasets to HuggingFace Hub
Compatible with:
- Claude Desktop (via Gradio MCP support)
- Continue.dev (VS Code extension)
- Cline (VS Code extension)
- Any MCP client supporting Gradio's MCP protocol
"""
import os
import logging
import gradio as gr
from typing import Optional, Dict, Any
from datetime import datetime
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[logging.StreamHandler()]
)
logger = logging.getLogger(__name__)
# Local imports
from gemini_client import GeminiClient
from mcp_tools import (
analyze_leaderboard,
debug_trace,
estimate_cost,
compare_runs,
analyze_results,
get_top_performers,
get_leaderboard_summary,
get_dataset,
generate_synthetic_dataset,
generate_prompt_template,
push_dataset_to_hub
)
# Initialize default Gemini client (fallback if user doesn't provide key)
try:
default_gemini_client = GeminiClient()
except ValueError:
default_gemini_client = None # Will prompt user to enter API key
# Gradio Interface for Testing
def create_gradio_ui():
"""Create Gradio UI for testing MCP tools"""
# Note: In Gradio 6, theme is passed to launch(), not Blocks()
with gr.Blocks(title="TraceMind MCP Server") as demo:
# Top Banner (matching TraceMind-AI style)
gr.HTML("""
<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 25px;
border-radius: 10px;
margin-bottom: 20px;
text-align: center;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
<h1 style="color: white !important; margin: 0; font-size: 2.5em; font-weight: bold;">
🤖 TraceMind MCP Server
</h1>
<p style="color: rgba(255,255,255,0.9); margin: 10px 0 0 0; font-size: 1.2em;">
AI-Powered Analysis for Agent Evaluation
</p>
<p style="color: rgba(255,255,255,0.8); margin: 10px 0 0 0; font-size: 0.9em;">
Powered by Gemini | Gradio | TraceVerde | SMOLTRACE | HuggingFace | OpenTelemetry | MCP
</p>
</div>
""")
gr.Markdown("""
**Track 1 Submission**: Building MCP (Enterprise)
*AI-powered MCP server providing 11 tools, 3 resources, and 3 prompts for agent evaluation analysis.*
""")
# TraceMind Ecosystem (Accordion)
with gr.Accordion("🌐 The TraceMind Ecosystem", open=False):
gr.Markdown("""
### Complete Agent Evaluation Platform
TraceMind MCP Server is part of a 4-project ecosystem for comprehensive agent evaluation:
#### 🔭 TraceVerde (genai_otel_instrument)
**Foundation: OpenTelemetry Instrumentation**
- Zero-code OTEL instrumentation for LLM frameworks
- Automatically captures every LLM call, tool usage, and agent step
- Works with LiteLLM, Transformers, LangChain, CrewAI, and more
- [GitHub](https://github.com/Mandark-droid/genai_otel_instrument) | [PyPI](https://pypi.org/project/genai-otel-instrument)
#### 📊 SMOLTRACE
**Foundation: Evaluation Engine**
- Lightweight agent evaluation engine with built-in tracing
- Generates structured datasets (leaderboard, results, traces, metrics)
- Supports both API models (via LiteLLM) and local models (via Transformers)
- [GitHub](https://github.com/Mandark-droid/SMOLTRACE) | [PyPI](https://pypi.org/project/smoltrace/)
#### 🤖 TraceMind MCP Server (This Project)
**Track 1: Building MCP (Enterprise)**
- Provides AI-powered MCP tools for analyzing evaluation data
- Uses Google Gemini 2.5 Flash for intelligent insights
- 11 tools + 3 resources + 3 prompts
- [HF Space](https://huggingface.co/spaces/MCP-1st-Birthday/TraceMind-mcp-server)
#### 🧠 TraceMind-AI
**Track 2: MCP in Action (Enterprise)**
- Interactive UI that consumes MCP tools from this server
- Leaderboard visualization with AI-powered insights
- Autonomous agent chat powered by MCP tools
- Multi-cloud job submission (HuggingFace Jobs + Modal)
- [HF Space](https://huggingface.co/spaces/MCP-1st-Birthday/TraceMind)
### The Flow
```
TraceVerde → SMOLTRACE → Datasets
↓
TraceMind MCP Server (AI Tools)
↓
TraceMind-AI (UI + Agent)
```
**Built for**: MCP's 1st Birthday Hackathon (Nov 14-30, 2025)
""")
# About Section (Accordion)
with gr.Accordion("📖 About This MCP Server", open=False):
gr.Markdown("""
### What is This?
TraceMind MCP Server provides intelligent analysis tools for agent evaluation data through the Model Context Protocol (MCP).
**Powered by**: Google Gemini 2.5 Flash
**🎬 [Quick Demo (5 min)](https://www.loom.com/share/d4d0003f06fa4327b46ba5c081bdf835)** | **📺 [Full Demo (20 min)](https://www.loom.com/share/de559bb0aef749559c79117b7f951250)**
### MCP Tools (11 Available)
- 📊 **Analyze Leaderboard** - AI-powered insights from evaluation results
- 🐛 **Debug Trace** - Understand agent execution with AI debugging
- 💰 **Estimate Cost** - Predict evaluation costs with AI recommendations
- ⚖️ **Compare Runs** - Compare evaluation runs with AI analysis
- 🔍 **Analyze Results** - Deep dive into test results
- 🏆 **Get Top Performers** - Quick leaderboard queries (optimized)
- 📈 **Get Leaderboard Summary** - High-level statistics (optimized)
- 📦 **Get Dataset** - Load any HuggingFace dataset as JSON
- 🧪 **Generate Synthetic Dataset** - Create domain-specific test datasets
- 📝 **Generate Prompt Template** - Create customized smolagents prompts
- 📤 **Push to Hub** - Upload datasets to HuggingFace Hub
### MCP Resources (3 Available)
- 📊 `leaderboard://{repo}` - Raw leaderboard data
- 🔍 `trace://{trace_id}/{repo}` - Raw trace data
- 💰 `cost://model/{model_name}` - Model pricing data
### MCP Prompts (3 Templates)
- 📝 `analysis_prompt` - Analysis request templates
- 🐛 `debug_prompt` - Debugging trace templates
- ⚡ `optimization_prompt` - Optimization recommendation templates
""")
# MCP Connection Info (Accordion)
with gr.Accordion("🔌 MCP Connection Details", open=False):
gr.Markdown("""
### Connect Your MCP Client
**HuggingFace Space**:
```
https://huggingface.co/spaces/MCP-1st-Birthday/TraceMind-mcp-server
```
**MCP Endpoint (SSE - Recommended)**:
```
https://mcp-1st-birthday-tracemind-mcp-server.hf.space/gradio_api/mcp/sse
```
**MCP Endpoint (Streamable HTTP)**:
```
https://mcp-1st-birthday-tracemind-mcp-server.hf.space/gradio_api/mcp/
```
### Supported Clients
- Claude Desktop
- Continue.dev
- Cline
- Any MCP-compatible client
""")
gr.Markdown("---")
with gr.Tabs():
# Tab 1: Analyze Leaderboard
with gr.Tab("📊 Analyze Leaderboard"):
gr.Markdown("### Get AI-powered insights from evaluation leaderboard")
with gr.Row():
with gr.Column():
lb_repo = gr.Textbox(
label="Leaderboard Repository",
value="kshitijthakkar/smoltrace-leaderboard",
placeholder="username/dataset-name"
)
lb_metric = gr.Dropdown(
label="Metric Focus",
choices=["overall", "accuracy", "cost", "latency", "co2"],
value="overall"
)
lb_time = gr.Dropdown(
label="Time Range",
choices=["last_week", "last_month", "all_time"],
value="last_week"
)
lb_top_n = gr.Slider(
label="Top N Models",
minimum=3,
maximum=10,
value=5,
step=1
)
lb_button = gr.Button("🔍 Analyze", variant="primary")
with gr.Column():
lb_output = gr.Markdown(label="Analysis Results")
async def run_analyze_leaderboard(repo, metric, time_range, top_n):
"""
Analyze agent evaluation leaderboard and generate AI-powered insights.
This tool loads agent evaluation data from HuggingFace datasets and uses
Google Gemini 2.5 Flash to provide intelligent analysis of top performers,
trends, cost/performance trade-offs, and actionable recommendations.
Args:
repo (str): HuggingFace dataset repository containing leaderboard data
metric (str): Primary metric to focus analysis on - "overall", "accuracy", "cost", "latency", or "co2"
time_range (str): Time range for analysis - "last_week", "last_month", or "all_time"
top_n (int): Number of top models to highlight in analysis (3-10)
gemini_key (str): Gemini API key from session state
hf_token (str): HuggingFace token from session state
Returns:
str: Markdown-formatted analysis with top performers, trends, and recommendations
"""
try:
result = await analyze_leaderboard(
leaderboard_repo=repo,
metric_focus=metric,
time_range=time_range,
top_n=int(top_n)
)
return result
except Exception as e:
return f"❌ **Error**: {str(e)}"
lb_button.click(
fn=run_analyze_leaderboard,
inputs=[lb_repo, lb_metric, lb_time, lb_top_n],
outputs=[lb_output]
)
# Tab 2: Debug Trace
with gr.Tab("🐛 Debug Trace"):
gr.Markdown("### Ask questions about specific agent execution traces")
with gr.Row():
with gr.Column():
trace_id = gr.Textbox(
label="Trace ID",
placeholder="trace_abc123",
info="Get this from the Run Detail screen"
)
traces_repo = gr.Textbox(
label="Traces Repository",
placeholder="username/agent-traces-model-timestamp",
info="Dataset containing trace data"
)
question = gr.Textbox(
label="Your Question",
placeholder="Why was tool X called twice?",
lines=3
)
trace_button = gr.Button("🔍 Analyze", variant="primary")
with gr.Column():
trace_output = gr.Markdown(label="Debug Analysis")
async def run_debug_trace(trace_id_val, traces_repo_val, question_val):
"""
Debug a specific agent execution trace using OpenTelemetry data.
This tool analyzes OpenTelemetry trace data from agent executions and uses
Google Gemini 2.5 Flash to answer specific questions about the execution flow,
identify bottlenecks, explain agent behavior, and provide debugging insights.
Args:
trace_id_val (str): Unique identifier for the trace to analyze (e.g., "trace_abc123")
traces_repo_val (str): HuggingFace dataset repository containing trace data
question_val (str): Specific question about the trace (optional, defaults to general analysis)
gemini_key (str): Gemini API key from session state
hf_token (str): HuggingFace token from session state
Returns:
str: Markdown-formatted debug analysis with step-by-step breakdown and answers
"""
try:
if not trace_id_val or not traces_repo_val:
return "❌ **Error**: Please provide both Trace ID and Traces Repository"
result = await debug_trace(
trace_id=trace_id_val,
traces_repo=traces_repo_val,
question=question_val or "Analyze this trace")
return result
except Exception as e:
return f"❌ **Error**: {str(e)}"
trace_button.click(
fn=run_debug_trace,
inputs=[trace_id, traces_repo, question],
outputs=[trace_output]
)
# Tab 3: Estimate Cost
with gr.Tab("💰 Estimate Cost"):
gr.Markdown("### Predict evaluation costs before running")
with gr.Row():
with gr.Column():
cost_model = gr.Textbox(
label="Model",
placeholder="openai/gpt-4 or meta-llama/Llama-3.1-8B",
info="Use litellm format (provider/model)"
)
cost_agent_type = gr.Dropdown(
label="Agent Type",
choices=["tool", "code", "both"],
value="both"
)
cost_num_tests = gr.Slider(
label="Number of Tests",
minimum=10,
maximum=1000,
value=100,
step=10
)
cost_hardware = gr.Dropdown(
label="Hardware Type",
choices=[
"auto",
# Modal
"cpu", "gpu_t4", "gpu_l4", "gpu_a10", "gpu_l40s",
"gpu_a100", "gpu_a100_80gb", "gpu_h100", "gpu_h200", "gpu_b200",
# HuggingFace Jobs
"cpu-basic", "cpu-upgrade",
"t4-small", "t4-medium",
"l4x1", "l4x4",
"a10g-small", "a10g-large", "a10g-largex2", "a10g-largex4",
"a100-large",
"v5e-1x1", "v5e-2x2", "v5e-2x4"
],
value="auto",
info="Supports Modal and HuggingFace Jobs hardware. 'auto' selects cpu-basic (API) or a10g-small (local)."
)
cost_button = gr.Button("💰 Estimate", variant="primary")
with gr.Column():
cost_output = gr.Markdown(label="Cost Estimate")
async def run_estimate_cost(model, agent_type, num_tests, hardware):
"""
Estimate the cost, duration, and CO2 emissions of running agent evaluations.
This tool predicts costs before running evaluations by calculating LLM API costs,
HuggingFace Jobs compute costs, and CO2 emissions. Uses Google Gemini 2.5 Flash
to provide detailed cost breakdown and optimization recommendations.
Args:
model (str): Model identifier in litellm format (e.g., "openai/gpt-4", "meta-llama/Llama-3.1-8B")
agent_type (str): Type of agent capabilities to test - "tool", "code", or "both"
num_tests (int): Number of test cases to run (10-1000)
hardware (str): Hardware type for HF Jobs - "auto", "cpu", "gpu_a10", or "gpu_h200"
gemini_key (str): Gemini API key from session state
Returns:
str: Markdown-formatted cost estimate with LLM costs, HF Jobs costs, duration, CO2, and tips
"""
try:
if not model:
return "❌ **Error**: Please provide a model name"
result = await estimate_cost(
model=model,
agent_type=agent_type,
num_tests=int(num_tests),
hardware=hardware
)
return result
except Exception as e:
return f"❌ **Error**: {str(e)}"
cost_button.click(
fn=run_estimate_cost,
inputs=[cost_model, cost_agent_type, cost_num_tests, cost_hardware],
outputs=[cost_output]
)
# Tab 4: Compare Runs
with gr.Tab("⚖️ Compare Runs"):
gr.Markdown("""
## Compare Two Evaluation Runs
Compare two evaluation runs with AI-powered analysis across multiple dimensions:
success rate, cost efficiency, speed, environmental impact, and more.
""")
with gr.Row():
with gr.Column():
compare_run_id_1 = gr.Textbox(
label="First Run ID",
placeholder="e.g., run_abc123",
info="Enter the run_id from the leaderboard"
)
with gr.Column():
compare_run_id_2 = gr.Textbox(
label="Second Run ID",
placeholder="e.g., run_xyz789",
info="Enter the run_id to compare against"
)
with gr.Row():
compare_focus = gr.Dropdown(
choices=["comprehensive", "cost", "performance", "eco_friendly"],
value="comprehensive",
label="Comparison Focus",
info="Choose what aspect to focus the comparison on"
)
compare_repo = gr.Textbox(
label="Leaderboard Repository",
value="kshitijthakkar/smoltrace-leaderboard",
info="HuggingFace dataset containing leaderboard data"
)
compare_button = gr.Button("🔍 Compare Runs", variant="primary")
compare_output = gr.Markdown()
async def run_compare_runs(run_id_1, run_id_2, focus, repo):
"""
Compare two evaluation runs and generate AI-powered comparative analysis.
This tool fetches data for two evaluation runs from the leaderboard and uses
Google Gemini 2.5 Flash to provide intelligent comparison across multiple dimensions:
success rate, cost efficiency, speed, environmental impact, and use case recommendations.
Args:
run_id_1 (str): First run ID from the leaderboard to compare
run_id_2 (str): Second run ID from the leaderboard to compare against
focus (str): Focus area - "comprehensive", "cost", "performance", or "eco_friendly"
repo (str): HuggingFace dataset repository containing leaderboard data
gemini_key (str): Gemini API key from session state
hf_token (str): HuggingFace token from session state
Returns:
str: Markdown-formatted comparative analysis with winners, trade-offs, and recommendations
"""
try:
result = await compare_runs(
run_id_1=run_id_1,
run_id_2=run_id_2,
leaderboard_repo=repo,
comparison_focus=focus
)
return result
except Exception as e:
return f"❌ **Error**: {str(e)}"
compare_button.click(
fn=run_compare_runs,
inputs=[compare_run_id_1, compare_run_id_2, compare_focus, compare_repo],
outputs=[compare_output]
)
# Tab 5: Analyze Results
with gr.Tab("🔍 Analyze Results"):
gr.Markdown("""
## Analyze Test Results & Get Optimization Recommendations
Deep dive into individual test case results to identify failure patterns,
performance bottlenecks, and cost optimization opportunities.
""")
with gr.Row():
results_repo_input = gr.Textbox(
label="Results Repository",
placeholder="e.g., username/smoltrace-results-gpt4-20251114",
info="HuggingFace dataset containing results data"
)
results_focus = gr.Dropdown(
choices=["comprehensive", "failures", "performance", "cost"],
value="comprehensive",
label="Analysis Focus",
info="What aspect to focus the analysis on"
)
with gr.Row():
results_max_rows = gr.Slider(
minimum=10,
maximum=500,
value=100,
step=10,
label="Max Test Cases to Analyze",
info="Limit number of test cases for analysis"
)
results_button = gr.Button("🔍 Analyze Results", variant="primary")
results_output = gr.Markdown()
async def run_analyze_results(repo, focus, max_rows):
"""
Analyze detailed test results and provide optimization recommendations.
Args:
repo (str): HuggingFace dataset repository containing results
focus (str): Analysis focus area
max_rows (int): Maximum test cases to analyze
gemini_key (str): Gemini API key from session state
hf_token (str): HuggingFace token from session state
Returns:
str: Markdown-formatted analysis with recommendations
"""
try:
if not repo:
return "❌ **Error**: Please provide a results repository"
result = await analyze_results(
results_repo=repo,
analysis_focus=focus,
max_rows=int(max_rows)
)
return result
except Exception as e:
return f"❌ **Error**: {str(e)}"
results_button.click(
fn=run_analyze_results,
inputs=[results_repo_input, results_focus, results_max_rows],
outputs=[results_output]
)
# Tab 6: Get Top Performers
with gr.Tab("🏆 Get Top Performers"):
gr.Markdown("""
## Get Top Performing Models (Token-Optimized)
Quickly retrieve top N models from the leaderboard without loading all runs.
**90% token reduction** compared to loading the full leaderboard dataset.
""")
with gr.Row():
with gr.Column():
top_perf_repo = gr.Textbox(
label="Leaderboard Repository",
value="kshitijthakkar/smoltrace-leaderboard",
placeholder="username/dataset-name"
)
top_perf_metric = gr.Dropdown(
label="Ranking Metric",
choices=["success_rate", "total_cost_usd", "avg_duration_ms", "co2_emissions_g"],
value="success_rate",
info="Metric to rank models by"
)
top_perf_n = gr.Slider(
label="Top N Models",
minimum=1,
maximum=20,
value=5,
step=1,
info="Number of top models to return"
)
top_perf_button = gr.Button("🏆 Get Top Performers", variant="primary")
with gr.Column():
top_perf_output = gr.JSON(label="Top Performers (JSON)")
async def run_get_top_performers(repo, metric, top_n):
"""Get top performing models from leaderboard."""
try:
import json
result = await get_top_performers(
leaderboard_repo=repo,
metric=metric,
top_n=int(top_n)
)
return json.loads(result)
except Exception as e:
return {"error": str(e)}
top_perf_button.click(
fn=run_get_top_performers,
inputs=[top_perf_repo, top_perf_metric, top_perf_n],
outputs=[top_perf_output]
)
# Tab 7: Get Leaderboard Summary
with gr.Tab("📈 Get Leaderboard Summary"):
gr.Markdown("""
## Get Leaderboard Overview Statistics (Token-Optimized)
Get high-level summary statistics without loading individual runs.
**99% token reduction** compared to loading the full leaderboard dataset.
""")
with gr.Row():
with gr.Column():
summary_repo = gr.Textbox(
label="Leaderboard Repository",
value="kshitijthakkar/smoltrace-leaderboard",
placeholder="username/dataset-name"
)
summary_button = gr.Button("📈 Get Summary", variant="primary")
with gr.Column():
summary_output = gr.JSON(label="Leaderboard Summary (JSON)")
async def run_get_leaderboard_summary(repo):
"""Get leaderboard summary statistics."""
try:
import json
result = await get_leaderboard_summary(leaderboard_repo=repo)
return json.loads(result)
except Exception as e:
return {"error": str(e)}
summary_button.click(
fn=run_get_leaderboard_summary,
inputs=[summary_repo],
outputs=[summary_output]
)
# Tab 8: Get Dataset
with gr.Tab("📦 Get Dataset"):
gr.Markdown("""
## Load SMOLTRACE Datasets as JSON
This tool loads datasets with the **smoltrace-** prefix and returns the raw data as JSON.
Use this to access leaderboard data, results datasets, traces datasets, or metrics datasets.
**Restriction**: Only datasets with "smoltrace-" in the name are allowed for security.
**Tip**: If you don't know which dataset to load, first load the leaderboard to see
dataset references in the `results_dataset`, `traces_dataset`, `metrics_dataset` fields.
""")
with gr.Row():
dataset_repo_input = gr.Textbox(
label="Dataset Repository (must contain 'smoltrace-')",
placeholder="e.g., kshitijthakkar/smoltrace-leaderboard",
value="kshitijthakkar/smoltrace-leaderboard",
info="HuggingFace dataset repository path with smoltrace- prefix"
)
dataset_max_rows = gr.Slider(
minimum=1,
maximum=200,
value=50,
step=1,
label="Max Rows",
info="Limit rows to avoid token limits"
)
dataset_button = gr.Button("📥 Load Dataset", variant="primary")
dataset_output = gr.JSON(label="Dataset JSON Output")
async def run_get_dataset(repo, max_rows):
"""
Load SMOLTRACE datasets from HuggingFace and return as JSON.
This tool loads datasets with the "smoltrace-" prefix and returns the raw data
as JSON. Use this to access leaderboard data, results datasets, traces datasets,
or metrics datasets. Only datasets with "smoltrace-" in the name are allowed.
Args:
repo (str): HuggingFace dataset repository path with "smoltrace-" prefix (e.g., "kshitijthakkar/smoltrace-leaderboard")
max_rows (int): Maximum number of rows to return (1-200, default 50)
hf_token (str): HuggingFace token from session state
Returns:
dict: JSON object with dataset data, metadata, total rows, and column names
"""
try:
import json
result = await get_dataset(
dataset_repo=repo,
max_rows=int(max_rows)
)
# Parse JSON string back to dict for JSON component
return json.loads(result)
except Exception as e:
return {"error": str(e)}
dataset_button.click(
fn=run_get_dataset,
inputs=[dataset_repo_input, dataset_max_rows],
outputs=[dataset_output]
)
# Tab 6: Generate Synthetic Dataset
with gr.Tab("🧪 Generate Synthetic Dataset"):
gr.Markdown("""
## Create Domain-Specific Test Datasets for SMOLTRACE
Use AI to generate synthetic evaluation tasks tailored to your domain and tools.
Perfect for creating custom benchmarks when standard datasets don't fit your use case.
**🎯 Enterprise Use Case**: Quickly create evaluation datasets for:
- Custom tools and APIs your agents use
- Industry-specific domains (finance, healthcare, legal, etc.)
- Internal workflows and processes
- Specialized agent capabilities
**Output Format**: SMOLTRACE-compatible task dataset ready for HuggingFace upload
""")
with gr.Row():
with gr.Column():
synth_domain = gr.Textbox(
label="Domain",
placeholder="e.g., finance, healthcare, travel, ecommerce, customer_support",
value="travel",
info="The domain/industry for your synthetic tasks"
)
synth_tools = gr.Textbox(
label="Tool Names (comma-separated)",
placeholder="e.g., get_weather,search_flights,book_hotel,currency_converter",
value="get_weather,search_flights,book_hotel",
info="Names of tools your agent can use",
lines=2
)
synth_num_tasks = gr.Slider(
label="Number of Tasks",
minimum=5,
maximum=100,
value=10,
step=1,
info="Total number of synthetic tasks to generate"
)
synth_difficulty = gr.Dropdown(
label="Difficulty Distribution",
choices=["balanced", "easy_only", "medium_only", "hard_only", "progressive"],
value="balanced",
info="How to distribute task difficulty"
)
synth_agent_type = gr.Dropdown(
label="Agent Type",
choices=["both", "tool", "code"],
value="both",
info="Target agent type for the tasks"
)
synth_button = gr.Button("🧪 Generate Synthetic Dataset", variant="primary", size="lg")
with gr.Column():
synth_output = gr.JSON(label="Generated Dataset (JSON)")
gr.Markdown("""
### 📝 Next Steps
After generation:
1. **Copy the `tasks` array** from the JSON output above
2. **Use the "Push to Hub" tab** to upload directly to HuggingFace
3. **Or upload manually** following the instructions in the output
**💡 Tip**: The generated dataset includes usage instructions and follows SMOLTRACE naming convention!
""")
async def run_generate_synthetic(domain, tools, num_tasks, difficulty, agent_type):
"""Generate synthetic dataset with async support."""
try:
import json
result = await generate_synthetic_dataset(
domain=domain,
tool_names=tools,
num_tasks=int(num_tasks),
difficulty_distribution=difficulty,
agent_type=agent_type
)
return json.loads(result)
except Exception as e:
return {"error": str(e)}
synth_button.click(
fn=run_generate_synthetic,
inputs=[synth_domain, synth_tools, synth_num_tasks, synth_difficulty, synth_agent_type],
outputs=[synth_output]
)
# Tab: Generate Prompt Template
with gr.Tab("📝 Generate Prompt Template"):
gr.Markdown("""
## Create Customized Agent Prompt Template
Generate a domain-specific prompt template based on smolagents templates.
This template can be used with your synthetic dataset to run SMOLTRACE evaluations.
**🎯 Use Case**: After generating a synthetic dataset, create a matching prompt template
that agents can use during evaluation. This ensures your evaluation setup is complete.
**Output**: Customized YAML prompt template ready for use with smolagents
""")
with gr.Row():
with gr.Column():
prompt_domain = gr.Textbox(
label="Domain",
placeholder="e.g., finance, healthcare, customer_support",
value="travel",
info="The domain/industry for the prompt template"
)
prompt_tools = gr.Textbox(
label="Tool Names (comma-separated)",
placeholder="e.g., get_weather,search_flights,book_hotel",
value="get_weather,search_flights,book_hotel",
info="Names of tools the agent will use",
lines=2
)
prompt_agent_type = gr.Dropdown(
label="Agent Type",
choices=["tool", "code"],
value="tool",
info="ToolCallingAgent (tool) or CodeAgent (code)"
)
prompt_button = gr.Button("📝 Generate Prompt Template", variant="primary", size="lg")
with gr.Column():
prompt_output = gr.JSON(label="Generated Prompt Template (JSON)")
gr.Markdown("""
### 📝 Next Steps
After generation:
1. **Copy the `prompt_template`** from the JSON output above
2. **Save it as a YAML file** (e.g., `{domain}_agent.yaml`)
3. **Include it in your HuggingFace dataset** card or repository
4. **Use it with SMOLTRACE** when running evaluations
**💡 Tip**: This template is AI-customized for your domain and tools!
""")
async def run_generate_prompt_template(domain, tools, agent_type):
"""Generate prompt template with async support."""
try:
import json
result = await generate_prompt_template(
domain=domain,
tool_names=tools,
agent_type=agent_type
)
return json.loads(result)
except Exception as e:
return {"error": str(e)}
prompt_button.click(
fn=run_generate_prompt_template,
inputs=[prompt_domain, prompt_tools, prompt_agent_type],
outputs=[prompt_output]
)
# Tab 7: Push Dataset to Hub
with gr.Tab("📤 Push to Hub"):
gr.Markdown("""
## Upload Generated Dataset to HuggingFace Hub
Upload your synthetic dataset (from the previous tab or any SMOLTRACE-format dataset)
directly to HuggingFace Hub.
**Requirements**:
- HuggingFace account
- API token with write permissions ([Get one here](https://huggingface.co/settings/tokens))
- Dataset in SMOLTRACE format
**Naming Convention**: `{username}/smoltrace-{domain}-tasks` or `{username}/smoltrace-{domain}-tasks-v1`
""")
with gr.Row():
with gr.Column():
push_dataset_json = gr.Textbox(
label="Dataset JSON (tasks array)",
placeholder='[{"id": "task_001", "prompt": "...", "expected_tool": "...", ...}]',
info="Paste the 'tasks' array from generate_synthetic_dataset output",
lines=10
)
push_repo_name = gr.Textbox(
label="Repository Name",
placeholder="your-username/smoltrace-finance-tasks",
info="HuggingFace repo name (follow SMOLTRACE convention)",
value=""
)
push_hf_token = gr.Textbox(
label="HuggingFace Token",
placeholder="hf_...",
info="API token with write permissions",
type="password"
)
push_private = gr.Checkbox(
label="Make dataset private",
value=False,
info="Private datasets are only visible to you"
)
# Hidden field for prompt template (used by API calls from TraceMind-AI)
push_prompt_template = gr.Textbox(
label="Prompt Template (Optional)",
placeholder="Leave empty if not using prompt template",
info="YAML prompt template to include in dataset card",
lines=5,
visible=True,
value=""
)
push_button = gr.Button("📤 Push to HuggingFace Hub", variant="primary", size="lg")
with gr.Column():
push_output = gr.JSON(label="Upload Result")
gr.Markdown("""
### 🎉 After Upload
Once uploaded, you can:
1. **View your dataset** at the URL provided in the output
2. **Use in SMOLTRACE** evaluations with the command shown
3. **Share with your team** (if public) or manage access (if private)
**Example**: After uploading to `company/smoltrace-finance-tasks`:
```bash
smoltrace-eval --model openai/gpt-4 --dataset-name company/smoltrace-finance-tasks
```
""")
async def run_push_dataset(dataset_json, repo_name, hf_token, private, prompt_template=""):
"""Push dataset to hub with async support and optional prompt template."""
try:
import json
result = await push_dataset_to_hub(
dataset_json=dataset_json,
repo_name=repo_name,
hf_token=hf_token,
private=private,
prompt_template=prompt_template if prompt_template else None
)
return json.loads(result)
except Exception as e:
return {"error": str(e)}
push_button.click(
fn=run_push_dataset,
inputs=[push_dataset_json, push_repo_name, push_hf_token, push_private, push_prompt_template],
outputs=[push_output]
)
# Tab 9: MCP Resources & Prompts
with gr.Tab("🔌 MCP Resources & Prompts"):
gr.Markdown("""
## MCP Resources & Prompts
Beyond the 7 MCP Tools, this server also exposes **MCP Resources** and **MCP Prompts**
that MCP clients can use directly.