File size: 18,825 Bytes
28fa73f
337873f
28fa73f
 
0785e04
b174d42
 
28fa73f
 
 
0785e04
 
 
 
 
 
28fa73f
337873f
28fa73f
 
 
 
 
 
337873f
28fa73f
 
 
4cb5786
28fa73f
337873f
b174d42
 
337873f
 
b174d42
4cb5786
b174d42
 
4cb5786
 
 
 
 
 
b174d42
4cb5786
 
 
 
b174d42
4cb5786
b174d42
 
4cb5786
b174d42
4cb5786
b174d42
4cb5786
 
b174d42
4cb5786
 
 
 
 
 
 
 
b174d42
4cb5786
 
 
 
 
 
 
 
b174d42
4cb5786
 
 
 
 
 
 
 
b174d42
4cb5786
b174d42
4cb5786
 
 
 
b174d42
4cb5786
 
 
b174d42
4cb5786
 
b174d42
4cb5786
 
 
 
 
 
 
 
b174d42
4cb5786
 
 
 
 
 
b174d42
4cb5786
 
 
 
 
 
 
 
b174d42
28fa73f
4cb5786
 
b174d42
4cb5786
 
28fa73f
4cb5786
 
28fa73f
0e08434
337873f
28fa73f
 
 
b174d42
28fa73f
 
b174d42
0785e04
b174d42
337873f
 
 
 
 
 
 
 
 
 
b174d42
28fa73f
 
337873f
b174d42
28fa73f
 
b174d42
337873f
b174d42
337873f
28fa73f
 
b174d42
28fa73f
337873f
28fa73f
b174d42
337873f
b174d42
28fa73f
 
b174d42
337873f
 
 
 
b174d42
337873f
b174d42
337873f
 
b174d42
337873f
b174d42
337873f
 
 
b174d42
337873f
b174d42
28fa73f
337873f
 
b174d42
337873f
b174d42
337873f
 
 
b174d42
28fa73f
 
b174d42
337873f
b174d42
28fa73f
b174d42
28fa73f
4cb5786
28fa73f
b174d42
28fa73f
 
 
 
 
337873f
 
 
 
28fa73f
b174d42
28fa73f
 
 
337873f
 
 
 
 
 
b174d42
337873f
 
 
 
 
28fa73f
 
337873f
28fa73f
 
 
 
 
 
 
 
 
 
 
 
b174d42
28fa73f
337873f
fa472b6
 
 
337873f
 
28fa73f
 
 
 
 
b174d42
28fa73f
 
337873f
28fa73f
fa472b6
 
337873f
 
 
b174d42
fa472b6
 
b174d42
fa472b6
337873f
 
28fa73f
b174d42
0785e04
 
b174d42
0785e04
b174d42
28fa73f
 
337873f
b174d42
 
337873f
 
 
 
b174d42
 
 
337873f
 
b174d42
28fa73f
337873f
28fa73f
b174d42
28fa73f
b174d42
28fa73f
337873f
 
b174d42
337873f
 
 
 
 
b174d42
337873f
 
b174d42
337873f
b174d42
 
337873f
 
 
b174d42
337873f
b174d42
337873f
 
 
b174d42
337873f
b174d42
0785e04
1736ee6
 
 
c71b7dd
b174d42
1736ee6
 
b174d42
1736ee6
0785e04
 
b174d42
c71b7dd
89c14ba
b174d42
c71b7dd
89c14ba
b174d42
c71b7dd
 
 
b174d42
c71b7dd
 
 
 
 
 
b174d42
c71b7dd
 
b174d42
c71b7dd
 
b174d42
c71b7dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b174d42
c71b7dd
 
 
 
 
 
 
 
b174d42
c71b7dd
 
 
 
 
b174d42
c71b7dd
 
 
b174d42
89c14ba
 
 
 
 
b174d42
89c14ba
 
 
 
b174d42
89c14ba
 
 
b174d42
89c14ba
b174d42
 
 
89c14ba
 
b174d42
89c14ba
b174d42
89c14ba
b174d42
 
89c14ba
b174d42
 
89c14ba
 
 
b174d42
89c14ba
 
 
 
 
 
 
b174d42
89c14ba
 
 
b174d42
89c14ba
b174d42
 
89c14ba
b174d42
 
c71b7dd
 
 
 
b174d42
c71b7dd
b174d42
28fa73f
b9ad814
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from hf_agent import HuggingFaceAgent, SmolagentsGAIAAgent
import requests
import pandas as pd
import os
import time
import json

DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"

ON_SPACES = os.environ.get("SPACE_ID") is not None

class DummyProfile:
    def __init__(self, username="local_user"):
        self.username = username

def fetch_questions(api_url):
    """Fetch GAIA evaluation questions from the API"""
    questions_url = f"{api_url}/questions"
    try:
        response = requests.get(questions_url, timeout=15)
        response.raise_for_status()
        return response.json()
    except Exception as e:
        print(f"Error fetching questions: {e}")
        return []

def submit_answers(api_url, username, agent_code, answers):
    """Submit answers to the GAIA evaluation API with retry logic"""
    submit_url = f"{api_url}/submit"
    submission_data = {
        "username": username.strip(),
        "agent_code": agent_code,
        "answers": answers
    }

    max_retries = 3
    retry_delay = 5

    for attempt in range(max_retries):
        try:
            print(f"Submission attempt {attempt + 1}/{max_retries}")
            print(f"Submitting to: {submit_url}")
            print(f"Username: {username}")
            print(f"Number of answers: {len(answers)}")

            headers = {
                'Content-Type': 'application/json',
                'User-Agent': 'Smolagents-GAIA-Agent/1.0'
            }

            response = requests.post(
                submit_url,
                json=submission_data,
                headers=headers,
                timeout=60
            )

            print(f"Response status: {response.status_code}")
            print(f"Response headers: {dict(response.headers)}")

            if response.status_code == 200:
                result = response.json()
                print(f"Submission successful: {result}")
                return result
            else:
                print(f"Server returned status {response.status_code}")
                print(f"Response text: {response.text}")
                response.raise_for_status()

        except requests.exceptions.Timeout:
            print(f"Timeout on attempt {attempt + 1}")
            if attempt < max_retries - 1:
                print(f"Retrying in {retry_delay} seconds...")
                time.sleep(retry_delay)
                continue
            else:
                return {"error": "Request timed out after multiple attempts"}

        except requests.exceptions.ConnectionError:
            print(f"Connection error on attempt {attempt + 1}")
            if attempt < max_retries - 1:
                print(f"Retrying in {retry_delay} seconds...")
                time.sleep(retry_delay)
                continue
            else:
                return {"error": "Unable to connect to server after multiple attempts"}

        except requests.exceptions.HTTPError as e:
            if response.status_code >= 500:
                print(f"Server error {response.status_code} on attempt {attempt + 1}")
                if attempt < max_retries - 1:
                    print(f"Retrying in {retry_delay} seconds...")
                    time.sleep(retry_delay)
                    retry_delay *= 2
                    continue
                else:
                    return {"error": f"Server error {response.status_code}: {response.text}"}
            else:
                print(f"Client error {response.status_code}: {response.text}")
                return {"error": f"Client error {response.status_code}: {response.text}"}

        except Exception as e:
            print(f"Unexpected error on attempt {attempt + 1}: {e}")
            if attempt < max_retries - 1:
                print(f"Retrying in {retry_delay} seconds...")
                time.sleep(retry_delay)
                continue
            else:
                return {"error": f"Unexpected error: {str(e)}"}

    return {"error": "All retry attempts failed"}

def save_results_locally(username, answers_payload, results_log):
    """Save evaluation results locally when server submission fails"""
    timestamp = pd.Timestamp.now().strftime("%Y%m%d_%H%M%S")
    filename = f"gaia_evaluation_{username}_{timestamp}.json"

    local_results = {
        "timestamp": timestamp,
        "username": username,
        "agent_type": "Smolagents GAIA Agent",
        "total_questions": len(answers_payload),
        "answers": answers_payload,
        "detailed_log": results_log
    }

    try:
        with open(filename, 'w') as f:
            json.dump(local_results, f, indent=2, default=str)

        print(f"Results saved locally to: {filename}")
        return filename
    except Exception as e:
        print(f"Failed to save results locally: {e}")
        return None

def run_evaluation(profile):
    """Run the full GAIA evaluation using the smolagents-based agent"""
    api_url = DEFAULT_API_URL
    space_id = "tjrtm"
    agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"

    if not profile:
        return "Please login to Hugging Face.", None

    username = getattr(profile, "username", "local_user")

    try:
        agent = SmolagentsGAIAAgent()
        print("Successfully initialized SmolagentsGAIAAgent")
    except Exception as e:
        print(f"Failed to initialize SmolagentsGAIAAgent: {e}")
        try:
            agent = HuggingFaceAgent()
            print("Using HuggingFaceAgent wrapper as fallback")
        except Exception as e2:
            return f"Failed to initialize any agent: {e2}", None

    questions = fetch_questions(api_url)
    if not questions:
        return "No questions fetched from server. Please check your connection.", None

    answers_payload = []
    results_log = []

    print(f"Processing {len(questions)} GAIA questions...")

    for i, item in enumerate(questions, 1):
        task_id = item.get("task_id")
        question_text = item.get("question")

        if not task_id or question_text is None:
            print(f"Skipping invalid question {i}")
            continue

        print(f"Processing question {i}/{len(questions)}: {task_id}")

        try:
            answer = agent(question_text)

            if isinstance(answer, str):
                cleaned_answer = answer.strip()
            else:
                cleaned_answer = str(answer).strip()

            answers_payload.append({
                "task_id": task_id,
                "submitted_answer": cleaned_answer
            })

            results_log.append({
                "Task ID": task_id,
                "Question": question_text[:100] + "..." if len(question_text) > 100 else question_text,
                "Submitted Answer": cleaned_answer[:200] + "..." if len(cleaned_answer) > 200 else cleaned_answer
            })

            print(f"Successfully processed question {task_id}")

        except Exception as e:
            error_msg = f"AGENT ERROR: {str(e)}"
            print(f"Error processing question {task_id}: {e}")

            results_log.append({
                "Task ID": task_id,
                "Question": question_text[:100] + "..." if len(question_text) > 100 else question_text,
                "Submitted Answer": error_msg
            })

    if not answers_payload:
        return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)

    print(f"Submitting {len(answers_payload)} answers to GAIA API...")

    result_data = submit_answers(api_url, username, agent_code, answers_payload)

    if "error" in result_data:
        save_results_locally(username, answers_payload, results_log)
        return f"Submission Failed: {result_data['error']}", pd.DataFrame(results_log)

    final_status = (
        f"Submission Successful!\n"
        f"User: {result_data.get('username')}\n"
        f"Overall Score: {result_data.get('score', 'N/A')}% "
        f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
        f"Message: {result_data.get('message', 'No message received.')}\n\n"
        f"Agent: Smolagents-based GAIA Agent\n"
        f"Questions Processed: {len(questions)}\n"
        f"Answers Submitted: {len(answers_payload)}"
    )

    return final_status, pd.DataFrame(results_log)

def agent_qa(question, files):
    """Handle individual Q&A with the smolagents agent"""
    try:
        agent = SmolagentsGAIAAgent()
    except Exception as e:
        print(f"Failed to initialize SmolagentsGAIAAgent, using fallback: {e}")
        agent = HuggingFaceAgent()

    try:
        answer = agent(question, files)
        return answer
    except Exception as e:
        return f"Error processing your question: {str(e)}. Please try rephrasing your question."

def file_preview(files):
    """Generate preview widgets for uploaded files"""
    previews = []
    for file in files or []:
        name = file.name
        ext = name.split('.')[-1].lower()
        if ext in ["png", "jpg", "jpeg"]:
            previews.append(gr.Image(value=file, label=name))
        else:
            previews.append(gr.Textbox(value=f"Uploaded: {name}", label=name))
    return previews

with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 900px !important;}") as demo:
    gr.Markdown("""

    <span style='color:#555'>
    - **Smolagents CodeAgent** - Advanced reasoning with code execution
    - **Real-time web search** with DuckDuckGo integration
    - **Article content extraction** - reads full articles from search results
    - **Intelligent synthesis** - combines information from multiple sources
    - **Custom tools** - Wikipedia search, calculator, file processing
    - **GAIA benchmark optimized** - designed for complex multi-step reasoning
    - Handles all question types and file attachments
    - Beautiful, modern UI
    - Robust agentic flows for GAIA evaluation
    </span>
    """)

    gr.Markdown("""
    **Instructions:**
    1. Login with your Hugging Face account (required for evaluation submission).
    2. Ask any question, optionally upload files (PDF, CSV, TXT, DOCX, images).
    3. **Web Search**: Ask for latest news, current information, or real-time data.
    4. **Article Extraction**: Use keywords like "detailed", "full analysis", or "comprehensive" for in-depth article reading.
    5. **Calculations**: Ask math questions and the agent will use its calculator tool.
    6. **Wikipedia**: Ask factual questions and the agent will search Wikipedia.
    7. Or run the full GAIA evaluation and submit your answers.

    **Search Tips:**
    - For quick results: "brief news about X" or "quick summary of Y"
    - For detailed analysis: "comprehensive report on X" or "detailed analysis of Y"
    - For news: "latest news in [location]" automatically extracts article content
    - For calculations: "calculate the area of a circle with radius 5"
    - For facts: "what is the capital of France"
    """)

    if not ON_SPACES:
        gr.Markdown("<span style='color:red'><b>Warning:</b> OAuth login and profile are only available on Hugging Face Spaces. Evaluation will use a dummy profile.</span>")

    gr.LoginButton(visible=ON_SPACES)

    with gr.Tab("Ask a Question"):
        with gr.Row():
            question = gr.Textbox(
                label="Your Question",
                lines=2,
                scale=3,
                placeholder="Ask me anything! I can search the web, do calculations, and process files..."
            )
            files = gr.File(
                label="Attach Files",
                file_types=[".txt", ".pdf", ".csv", ".docx", ".xlsx", ".png", ".jpg", ".jpeg"],
                file_count="multiple",
                scale=2
            )

        file_previews = gr.Group()
        answer = gr.Textbox(label="Agent Answer", lines=8)
        ask_btn = gr.Button("Get Answer", variant="primary")

        ask_btn.click(agent_qa, inputs=[question, files], outputs=answer)

    with gr.Tab("GAIA Evaluation"):
        gr.Markdown("""
        **GAIA Benchmark Evaluation**

        This will run the full GAIA evaluation using the smolagents-based agent:
        - Fetch all GAIA questions from the official API
        - Process each question using the CodeAgent with tools
        - Submit answers for scoring
        - Display results and performance metrics

        **Note**: This may take several minutes to complete as the agent processes complex multi-step questions.
        """)

        status_output = gr.Textbox(
            label="Run Status / Submission Result",
            lines=8,
            interactive=False,
            placeholder="Click 'Run Evaluation' to start the GAIA benchmark test..."
        )

        results_table = gr.DataFrame(
            label="Questions and Agent Answers",
            wrap=True,
            headers=["Task ID", "Question", "Submitted Answer"]
        )

        eval_btn = gr.Button("Run Evaluation & Submit All Answers", variant="primary", size="lg")

        if ON_SPACES:
            def run_evaluation_with_oauth(request: gr.Request):
                class RequestProfile:
                    def __init__(self, username):
                        self.username = username or "tjrtm"

                profile = RequestProfile(getattr(request, 'username', None))
                return run_evaluation(profile)

            eval_btn.click(run_evaluation_with_oauth, outputs=[status_output, results_table])
        else:
            eval_btn.click(lambda: run_evaluation(DummyProfile()), outputs=[status_output, results_table])

    with gr.Tab("Model Configuration"):
        gr.Markdown("""

        Choose your preferred model strategy for the GAIA evaluation:
        """)

        strategy_selector = gr.Radio(
            choices=[
                ("Local Models", "local"),
                ("Remote (HuggingFace)", "remote"),
                ("Auto Select", "auto")
            ],
            value="local",
            label="Model Strategy",
            info="Select which type of models to use for inference"
        )

        with gr.Tab("Local Models"):
            gr.Markdown("""

            Run with models downloaded locally for privacy and offline usage:
            """)

            with gr.Row():
                with gr.Column():
                    gr.Markdown("### Quick Setup")
                    model_size = gr.Radio(
                        choices=["light", "medium", "full"],
                        value="light",
                        label="Model Size",
                        info="Light: ~20GB, Medium: ~18GB, Full: ~155GB"
                    )
                    hf_token = gr.Textbox(
                        label="HuggingFace Token (optional)",
                        placeholder="hf_...",
                        type="password",
                        info="Required for some gated models"
                    )
                    download_btn = gr.Button("Download Models", variant="primary")

                with gr.Column():
                    gr.Markdown("### Manual Setup")
                    llm_path = gr.Textbox(
                        label="LLM Model Path",
                        placeholder="./models/Llama-3.2-3B-Instruct",
                        info="Path to your local LLM"
                    )
                    fallback_path = gr.Textbox(
                        label="Fallback Model Path",
                        placeholder="./models/Qwen2.5-7B-Instruct",
                        info="Path to your fallback model"
                    )
                    embedding_path = gr.Textbox(
                        label="Embedding Model Path",
                        placeholder="./models/all-MiniLM-L6-v2",
                        info="Path to your embedding model"
                    )
                    set_paths_btn = gr.Button("Set Model Paths", variant="secondary")

        download_status = gr.Textbox(
            label="Status",
            interactive=False,
            lines=10
        )

        def download_models_interface(size, token):
            try:
                import subprocess
                import sys

                cmd = [sys.executable, "download_models.py", "--model-size", size]
                if token:
                    cmd.extend(["--token", token])

                result = subprocess.run(
                    cmd,
                    capture_output=True,
                    text=True,
                    cwd="."
                )

                if result.returncode == 0:
                    return f" Successfully downloaded {size} models!\n\n{result.stdout}"
                else:
                    return f" Download failed:\n{result.stderr}\n{result.stdout}"

            except Exception as e:
                return f" Error running download script: {str(e)}"

        def set_model_paths_interface(llm, fallback, embedding):
            try:
                from config import set_local_model_paths, set_model_strategy

                paths_set = []
                if llm and os.path.exists(llm):
                    paths_set.append(f"LLM: {llm}")
                if fallback and os.path.exists(fallback):
                    paths_set.append(f"Fallback: {fallback}")
                if embedding and os.path.exists(embedding):
                    paths_set.append(f"Embedding: {embedding}")

                if paths_set:
                    set_local_model_paths(llm, fallback, embedding)
                    set_model_strategy("local")
                    return f" Local model paths updated:\n" + "\n".join(paths_set) + "\n\nRestart the application to use local models."
                else:
                    return " No valid model paths found. Please check that the directories exist."

            except Exception as e:
                return f" Error setting model paths: {str(e)}"

        def set_strategy_interface(strategy):
            try:
                from config import set_model_strategy
                set_model_strategy(strategy)
                return f" Model strategy set to: {strategy}\n\nRestart the application to apply changes."
            except Exception as e:
                return f" Error setting strategy: {str(e)}"

        download_btn.click(
            fn=download_models_interface,
            inputs=[model_size, hf_token],
            outputs=download_status
        )

        set_paths_btn.click(
            fn=set_model_paths_interface,
            inputs=[llm_path, fallback_path, embedding_path],
            outputs=download_status
        )

        strategy_selector.change(
            fn=set_strategy_interface,
            inputs=strategy_selector,
            outputs=download_status
        )

if __name__ == "__main__":
    demo.launch()