File size: 3,609 Bytes
81769c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from pydantic import BaseModel
import requests
import json

USERNAME = "juancitro"
SPACE_ID = "juancitro/Final_Assignment_Template"
AGENT_CODE = f"https://huggingface.co/spaces/{SPACE_ID}/tree/main"
API_URL = "https://agents-course-unit4-scoring.hf.space"  # Replace with actual API URL


def extract_json(response: str) -> dict | None:
    """
    Extract the JSON part of the LLM response, and remove some invalid caracters.
    """
    try:
        json_start = response.index("{")
        json_end = response.rfind("}")
        json_str_response = response[json_start:json_end + 1]
        json_str_response = json_str_response.replace('\n', ' ')
        json_response = json.loads(json_str_response)
    except (ValueError, json.JSONDecodeError) as e:
        print(f"JSON can't be parsed: {e}. Original response: {response}")
        return None
    return json_response


class GAIAQuestions(BaseModel):
    task_id: str
    question: str
    Level: str
    answer: str | None = None
    file_name: str | None = None


def load_qa_data(file_path: str) -> list[GAIAQuestions]:
    import json
    with open(file_path, 'r') as f:
        questions = json.load(f)
    return [GAIAQuestions(**question) for question in questions]


def submit(questions: list[GAIAQuestions], username=USERNAME, agent_code=AGENT_CODE, submit_url = f"{API_URL}/submit") -> str:
    answers_payload = []
    results_log = []
    for item in questions:
        answers_payload.append({"task_id": item.task_id, "submitted_answer": item.answer})
        results_log.append({"Task ID": item.task_id, "Question": item.question, "Submitted Answer": item.answer})
    
    submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
    status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
    print(status_update)

     # 5. Submit
    print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
    try:
        response = requests.post(submit_url, json=submission_data, timeout=60)
        response.raise_for_status()
        result_data = response.json()
        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.')}"
        )
        print("Submission successful.")
        return final_status
    except requests.exceptions.HTTPError as e:
        error_detail = f"Server responded with status {e.response.status_code}."
        try:
            error_json = e.response.json()
            error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
        except requests.exceptions.JSONDecodeError:
            error_detail += f" Response: {e.response.text[:500]}"
        status_message = f"Submission Failed: {error_detail}"
        print(status_message)
        return status_message
    except requests.exceptions.Timeout:
        status_message = "Submission Failed: The request timed out."
        print(status_message)
        return status_message
    except requests.exceptions.RequestException as e:
        status_message = f"Submission Failed: Network error - {e}"
        print(status_message)
        return status_message
    except Exception as e:
        status_message = f"An unexpected error occurred during submission: {e}"
        print(status_message)
        return status_message