File size: 1,878 Bytes
d10ae74
 
 
 
f0eb1da
d10ae74
 
 
 
 
 
f0eb1da
d10ae74
 
 
 
 
 
f0eb1da
d10ae74
 
 
 
f0eb1da
 
 
 
 
 
 
 
 
 
d10ae74
f0eb1da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d10ae74
 
 
f0eb1da
d10ae74
e86c6c0
d10ae74
 
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
import requests
import os
from typing import List, Dict, Any


class ApiClient:
    def __init__(self, api_url="https://agents-course-unit4-scoring.hf.space"):
        self.api_url = api_url
        self.questions_url = f"{api_url}/questions"
        self.submit_url = f"{api_url}/submit"
        self.files_url = f"{api_url}/files"

    def get_questions(self, limit=20) -> List[Dict[str, Any]]:
        limit = min(limit, 20)
        limit = max(limit, 1)
        response = requests.get(self.questions_url)
        response.raise_for_status()
        return response.json()[:limit]

    def get_random_question(self) -> Dict[str, Any]:
        response = requests.get(f"{self.api_url}/random-question")
        response.raise_for_status()
        return response.json()

    def get_file(self, task_id, file_name: str) -> bytes:
        # check if file already exists
        file_path = os.path.join("src/temp/files", file_name)
        if os.path.exists(file_path):
            return file_path

        # Download the file
        os.makedirs(os.path.dirname(file_path), exist_ok=True)
        response = requests.get(f"{self.files_url}/{task_id}", stream=True)
        response.raise_for_status()

        # Save the file
        with open(file_path, "wb") as f:
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)
            print(f"File saved to {file_path}")

        return file_path

    def submit_answers(
        self,
        username: str,
        agent_code: str,
        answers_payload: List[Dict[str, Any]],
    ) -> Dict[str, Any]:
        data = {
            "username": username,
            "agent_code": agent_code,
            "answers": answers_payload,
        }
        response = requests.post(self.submit_url, json=data, timeout=60)
        response.raise_for_status()
        return response.json()