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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea63030
f8cfca9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
HF Agents Course Unit 4 Final Assignment
app.py - Part 1

Requirements:
- smolagents==1.21.3
- LiteLLMModel
- Cerebras GPT-OSS
- DuckDuckGoSearchTool
- VisitWebpageTool
"""

from __future__ import annotations

import hashlib
import json
import logging
import os
import pickle
import re
import time
from pathlib import Path
from typing import Dict, Any, Optional

from smolagents import (
    CodeAgent,
    LiteLLMModel,
    ToolCallingAgent,
)

from smolagents import (
    DuckDuckGoSearchTool,
    VisitWebpageTool,
)

###############################################################################
# Configuration
###############################################################################

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s | %(levelname)s | %(message)s",
)

logger = logging.getLogger("gaia-agent")

CACHE_DIR = Path(".cache")
CACHE_DIR.mkdir(exist_ok=True)

MAX_RETRIES = 3
RETRY_DELAY = 2

MODEL_NAME = os.getenv(
    "MODEL_ID",
    "cerebras/gpt-oss-120b",
)

API_KEY = os.getenv("CEREBRAS_API_KEY")

###############################################################################
# LiteLLM Model
###############################################################################

model = LiteLLMModel(
    model_id=MODEL_NAME,
    api_key=API_KEY,
    temperature=0.2,
    max_tokens=4096,
)

###############################################################################
# Tools
###############################################################################

search_tool = DuckDuckGoSearchTool()

visit_tool = VisitWebpageTool()

TOOLS = [
    search_tool,
    visit_tool,
]

###############################################################################
# Cache
###############################################################################

class FileCache:

    def __init__(self, folder: Path):
        self.folder = folder

    def _path(self, key: str):
        digest = hashlib.sha256(
            key.encode()
        ).hexdigest()
        return self.folder / f"{digest}.pkl"

    def get(self, key):

        path = self._path(key)

        if path.exists():

            with open(path, "rb") as f:
                return pickle.load(f)

        return None

    def set(self, key, value):

        with open(self._path(key), "wb") as f:
            pickle.dump(value, f)

cache = FileCache(CACHE_DIR)

###############################################################################
# Retry helper
###############################################################################

def retry(fn):

    for attempt in range(MAX_RETRIES):

        try:
            return fn()

        except Exception as e:

            logger.warning(
                "Attempt %d failed: %s",
                attempt + 1,
                e,
            )

            if attempt == MAX_RETRIES - 1:
                raise

            time.sleep(RETRY_DELAY)

###############################################################################
# Cleaning
###############################################################################

ANSWER_PATTERNS = [
    r"^Answer\s*:",
    r"^Final Answer\s*:",
    r"```",
]

def clean_answer(answer: str) -> str:

    answer = answer.strip()

    for pattern in ANSWER_PATTERNS:
        answer = re.sub(
            pattern,
            "",
            answer,
            flags=re.IGNORECASE,
        )

    answer = answer.strip()

    return answer

###############################################################################
# Routing
###############################################################################

def classify_question(question: str):

    q = question.lower()

    if any(
        word in q
        for word in [
            "who",
            "when",
            "where",
            "latest",
            "website",
            "news",
            "search",
        ]
    ):
        return "web"

    return "reasoning"

###############################################################################
# Agent Factory
###############################################################################

def build_web_agent():

    return ToolCallingAgent(
        tools=TOOLS,
        model=model,
        max_steps=8,
    )


def build_reasoning_agent():

    return CodeAgent(
        tools=TOOLS,
        model=model,
        max_steps=10,
    )

web_agent = build_web_agent()
reasoning_agent = build_reasoning_agent()

###############################################################################
# Hybrid Router
###############################################################################

class HybridGAIAAgent:
    """
    Routes questions between a web-search oriented agent and a
    reasoning-oriented agent.
    """

    def __init__(
        self,
        web_agent,
        reasoning_agent,
        cache,
    ):
        self.web_agent = web_agent
        self.reasoning_agent = reasoning_agent
        self.cache = cache

    def _run_agent(self, agent, prompt: str) -> str:
        """
        Execute an agent with retries.
        """

        def _execute():
            return agent.run(prompt)

        return retry(_execute)

    def answer(self, question: str) -> str:
        """
        Main inference entrypoint.
        """

        cache_key = question.strip()

        cached = self.cache.get(cache_key)

        if cached is not None:
            logger.info("Cache hit.")
            return cached

        route = classify_question(question)

        logger.info("Selected route: %s", route)

        if route == "web":
            raw_answer = self._run_agent(
                self.web_agent,
                question,
            )
        else:
            raw_answer = self._run_agent(
                self.reasoning_agent,
                question,
            )

        cleaned = clean_answer(str(raw_answer))

        self.cache.set(cache_key, cleaned)

        return cleaned


###############################################################################
# Prompt Templates
###############################################################################

SYSTEM_PROMPT = """
You are an expert GAIA benchmark assistant.

Guidelines:

- Think carefully.
- Search the web whenever necessary.
- Visit webpages when search results require deeper inspection.
- Never fabricate facts.
- Return only the final answer.
"""

WEB_PROMPT = """
Use search tools whenever required.

Question:

{question}
"""

REASONING_PROMPT = """
Solve the problem carefully.

Question:

{question}
"""

###############################################################################
# Formatting Utilities
###############################################################################

def build_prompt(question: str) -> str:

    route = classify_question(question)

    if route == "web":
        body = WEB_PROMPT.format(
            question=question,
        )
    else:
        body = REASONING_PROMPT.format(
            question=question,
        )

    return (
        SYSTEM_PROMPT
        + "\n\n"
        + body
    )


###############################################################################
# JSON Helpers
###############################################################################

def safe_json_loads(text: str) -> Optional[Dict[str, Any]]:

    try:
        return json.loads(text)

    except Exception:
        return None


def looks_like_json(text: str) -> bool:

    text = text.strip()

    return (
        text.startswith("{")
        and text.endswith("}")
    )


###############################################################################
# Validation
###############################################################################

def validate_answer(answer: str) -> str:

    if answer is None:
        return ""

    answer = str(answer)

    answer = clean_answer(answer)

    if looks_like_json(answer):

        parsed = safe_json_loads(answer)

        if parsed is not None:

            if "answer" in parsed:
                return str(parsed["answer"]).strip()

            if "final_answer" in parsed:
                return str(parsed["final_answer"]).strip()

    return answer.strip()


###############################################################################
# Instantiate Hybrid Agent
###############################################################################

hybrid_agent = HybridGAIAAgent(
    web_agent=web_agent,
    reasoning_agent=reasoning_agent,
    cache=cache,
)

###############################################################################
# GAIA Solver
###############################################################################

class GAIASolver:
    """
    High-level wrapper around the HybridGAIAAgent.
    Responsible for preparing prompts, handling retries,
    validating answers, and providing a stable interface.
    """

    def __init__(self, agent: HybridGAIAAgent):
        self.agent = agent

    def solve(self, question: str) -> str:
        prompt = build_prompt(question)

        logger.info("=" * 80)
        logger.info("Incoming Question")
        logger.info(question)
        logger.info("=" * 80)

        answer = retry(
            lambda: self.agent.answer(prompt)
        )

        answer = validate_answer(answer)

        logger.info("Final Answer:")
        logger.info(answer)

        return answer


###############################################################################
# Statistics
###############################################################################

class AgentStatistics:

    def __init__(self):
        self.total_requests = 0
        self.cache_hits = 0
        self.failures = 0

    def request(self):
        self.total_requests += 1

    def cache_hit(self):
        self.cache_hits += 1

    def failure(self):
        self.failures += 1

    def summary(self):

        return {
            "requests": self.total_requests,
            "cache_hits": self.cache_hits,
            "failures": self.failures,
        }


stats = AgentStatistics()

###############################################################################
# Public API
###############################################################################

solver = GAIASolver(hybrid_agent)


def solve(question: str) -> str:
    """
    Main API expected by evaluation scripts.
    """

    stats.request()

    cache_value = cache.get(question)

    if cache_value is not None:
        stats.cache_hit()
        return cache_value

    try:
        answer = solver.solve(question)

        cache.set(question, answer)

        return answer

    except Exception as exc:

        stats.failure()

        logger.exception(exc)

        return ""


###############################################################################
# Batch Solver
###############################################################################

def solve_batch(questions):

    outputs = []

    for question in questions:

        outputs.append(
            solve(question)
        )

    return outputs


###############################################################################
# Optional CLI Utilities
###############################################################################

def interactive():

    print("=" * 70)
    print("Hybrid GAIA Agent")
    print("Type 'exit' to quit.")
    print("=" * 70)

    while True:

        question = input("\nQuestion> ").strip()

        if not question:
            continue

        if question.lower() in {
            "exit",
            "quit",
        }:
            break

        answer = solve(question)

        print("\nAnswer:")
        print(answer)

###############################################################################
# HF Unit 4 Entry Points
###############################################################################

def predict(question: str) -> str:
    """
    Prediction entry point used by many evaluation scripts.
    """
    return solve(question)


def answer(question: str) -> str:
    """
    Alias for compatibility with some templates.
    """
    return solve(question)


###############################################################################
# Diagnostics
###############################################################################

def print_statistics():

    print("\n")
    print("=" * 80)
    print("Agent Statistics")
    print("=" * 80)

    summary = stats.summary()

    for key, value in summary.items():
        print(f"{key:15}: {value}")

    print("=" * 80)


###############################################################################
# Health Check
###############################################################################

def healthcheck():

    try:

        logger.info("Running health check...")

        test_question = "What is 2 + 2?"

        result = solve(test_question)

        logger.info("Health check completed.")
        logger.info(result)

        return True

    except Exception as exc:

        logger.exception(exc)

        return False


###############################################################################
# Main
###############################################################################

if __name__ == "__main__":
    print("GAIA Agent loaded successfully.")
    if args.healthcheck:

        ok = healthcheck()

        print("OK" if ok else "FAILED")

    elif args.interactive:

        interactive()

    elif args.question:

        print(solve(args.question))

    else:

        interactive()

    if args.stats:

        print_statistics()