AnhLee0 commited on
Commit
f80d56c
·
verified ·
1 Parent(s): 54083d9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -13
app.py CHANGED
@@ -4,30 +4,52 @@ from typing import List, Tuple
4
  import requests
5
  import gradio as gr
6
  import pandas as pd
 
 
7
 
8
  # --- Constants ---
9
  QUESTIONS_URL = "https://agents-course-unit4-scoring.hf.space/questions"
10
  SUBMIT_URL = "https://agents-course-unit4-scoring.hf.space/submit"
11
  FILES_URL = "https://agents-course-unit4-scoring.hf.space/files"
12
  FILES_DIR = "files"
13
- SYSTEM_PROMPT = "You are a helpful AI assistant tasked with answering questions accurately."
 
 
 
 
14
 
15
  # --- AssistantAgent Implementation ---
16
  class AssistantAgent:
17
  def __init__(self, system_prompt: str):
18
  self.system_prompt = system_prompt
 
19
 
20
  def __call__(self, question: str, file_path: str = None) -> str:
21
- # Triển khai đơn giản: trả về câu trả lời dựa trên câu hỏi
22
- # Thay bằng logic AI thực tế (ví dụ: gọi API Hugging Face, Grok, hoặc mô hình khác)
 
 
23
  if file_path:
24
- try:
25
- with open(file_path, 'r') as f:
26
- file_content = f.read()
27
- return f"Answer to '{question}' with file content: {file_content}"
28
- except Exception as e:
29
- return f"Error reading file: {e}"
30
- return f"Answer to '{question}' (prompt: {self.system_prompt})"
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
  # --- Functions ---
33
  def run_and_submit_all(profile: gr.OAuthProfile | None) -> Tuple[str, pd.DataFrame]:
@@ -148,8 +170,6 @@ def download_question_file(question_uuid: str, question_file: str) -> str:
148
  return file_dst
149
  except requests.exceptions.RequestException as e:
150
  raise RuntimeError(f"Error downloading file: {e}")
151
- except requests.exceptions.JSONDecodeError as e:
152
- raise RuntimeError(f"Error decoding JSON response from files endpoint: {e}. Response text: {response.text[:500]}")
153
  except Exception as e:
154
  raise RuntimeError(f"An unexpected error occurred downloading file: {e}")
155
 
@@ -200,7 +220,7 @@ with gr.Blocks() as demo:
200
  1. Log in to your Hugging Face account using the button below.
201
  2. Click 'Run Evaluation & Submit All Answers' to fetch questions, run the agent, and submit answers.
202
  ---
203
- **Note:** This is a basic setup for the Final Assignment Template. Update AssistantAgent logic for better performance.
204
  """
205
  )
206
 
 
4
  import requests
5
  import gradio as gr
6
  import pandas as pd
7
+ import mimetypes
8
+ import google.generativeai as genai
9
 
10
  # --- Constants ---
11
  QUESTIONS_URL = "https://agents-course-unit4-scoring.hf.space/questions"
12
  SUBMIT_URL = "https://agents-course-unit4-scoring.hf.space/submit"
13
  FILES_URL = "https://agents-course-unit4-scoring.hf.space/files"
14
  FILES_DIR = "files"
15
+ SYSTEM_PROMPT = "You are a helpful AI assistant tasked with answering questions accurately. Provide concise and accurate answers."
16
+ GEMINI_API_KEY = "AIzaSyBO46AIuY3Lmq3-k2bZkABgc0gL6A1RV20"
17
+
18
+ # Configure Gemini API
19
+ genai.configure(api_key=GEMINI_API_KEY)
20
 
21
  # --- AssistantAgent Implementation ---
22
  class AssistantAgent:
23
  def __init__(self, system_prompt: str):
24
  self.system_prompt = system_prompt
25
+ self.model = genai.GenerativeModel('gemini-1.5-pro')
26
 
27
  def __call__(self, question: str, file_path: str = None) -> str:
28
+ # Prepare the prompt
29
+ prompt = f"{self.system_prompt}\nQuestion: {question}"
30
+
31
+ # Handle file if provided
32
  if file_path:
33
+ # Determine file type
34
+ mime_type, _ = mimetypes.guess_type(file_path)
35
+ if mime_type and mime_type.startswith('text'):
36
+ try:
37
+ with open(file_path, 'r', encoding='utf-8') as f:
38
+ file_content = f.read()
39
+ prompt += f"\nFile content:\n{file_content}"
40
+ except UnicodeDecodeError as e:
41
+ return f"Error reading file: {e}. File may not be a valid text file."
42
+ except Exception as e:
43
+ return f"Error reading file: {e}"
44
+ else:
45
+ return "Error: Gemini API does not support non-text files (e.g., images, videos). Please provide a text description instead."
46
+
47
+ # Call Gemini API
48
+ try:
49
+ response = self.model.generate_content(prompt)
50
+ return response.text.strip()
51
+ except Exception as e:
52
+ return f"Error calling Gemini API: {e}"
53
 
54
  # --- Functions ---
55
  def run_and_submit_all(profile: gr.OAuthProfile | None) -> Tuple[str, pd.DataFrame]:
 
170
  return file_dst
171
  except requests.exceptions.RequestException as e:
172
  raise RuntimeError(f"Error downloading file: {e}")
 
 
173
  except Exception as e:
174
  raise RuntimeError(f"An unexpected error occurred downloading file: {e}")
175
 
 
220
  1. Log in to your Hugging Face account using the button below.
221
  2. Click 'Run Evaluation & Submit All Answers' to fetch questions, run the agent, and submit answers.
222
  ---
223
+ **Note:** This is a basic setup for the Final Assignment Template. Agent uses Gemini API for answering.
224
  """
225
  )
226