s1144662 commited on
Commit
7f1f76c
Β·
verified Β·
1 Parent(s): 513d33a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -25
app.py CHANGED
@@ -3,43 +3,73 @@ import gradio as gr
3
  import requests
4
  import pandas as pd
5
  from typing import Optional
6
- from duckduckgo_search import DDGS
7
 
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
10
 
11
  class BasicAgent:
12
  def __init__(self):
13
- """εˆε§‹εŒ–ζœε°‹ Agent"""
 
 
 
 
 
 
 
 
 
14
  self.agent = True
15
- print("βœ“ Search agent initialized")
16
 
17
  def __call__(self, question: str) -> str:
18
- """用 DuckDuckGo ζœε°‹ε›žη­”ε•ι‘Œ"""
 
 
 
19
  try:
20
- ddgs = DDGS()
21
- results = ddgs.text(question, max_results=5)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
- if not results:
24
- return "No search results found for this question."
 
 
 
25
 
26
- # η΅„εˆζœε°‹η΅ζžœ
27
- answer = ""
28
- for i, result in enumerate(results[:3], 1):
29
- title = result.get('title', 'Unknown')
30
- body = result.get('body', '')[:300]
31
- answer += f"{title}: {body}\n"
32
 
33
- return answer.strip() if answer else "Could not find relevant information"
 
34
  except Exception as e:
35
- print(f"Search error: {e}")
36
- return f"Unable to search: Please try again"
37
 
38
 
39
  def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
40
  """δΈ»θ¦θ©•δΌ°ε’ŒζδΊ€ε‡½ζ•Έ"""
41
 
42
- # ζͺ’ζŸ₯η™»ε…₯
43
  if profile is None:
44
  return "Please Login to Hugging Face with the button.", None
45
 
@@ -50,15 +80,13 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
50
  questions_url = f"{api_url}/questions"
51
  submit_url = f"{api_url}/submit"
52
 
53
- # εˆε§‹εŒ– Agent
54
  try:
55
  agent = BasicAgent()
56
  except Exception as e:
57
- return f"Error initializing agent: {str(e)}", None
58
 
59
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
60
 
61
- # η²ε–ε•ι‘Œ
62
  try:
63
  response = requests.get(questions_url, timeout=30)
64
  response.raise_for_status()
@@ -69,7 +97,6 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
69
  answers_payload = []
70
  results_log = []
71
 
72
- # ι€ε€‹ε›žη­”ε•ι‘Œ
73
  total = len(questions_data)
74
  for idx, item in enumerate(questions_data, 1):
75
  task_id = item.get("task_id")
@@ -100,7 +127,6 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
100
  "Answer": error_answer
101
  })
102
 
103
- # ζδΊ€η­”ζ‘ˆ
104
  submission_data = {
105
  "username": username,
106
  "agent_code": agent_code,
@@ -122,10 +148,9 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
122
  return status_msg, pd.DataFrame(results_log)
123
 
124
 
125
- # Gradio UI
126
  with gr.Blocks(title="Unit 4 Final Assignment") as demo:
127
  gr.Markdown("# Unit 4 Final Project: AI Agent")
128
- gr.Markdown("_Using DuckDuckGo Search to answer questions_")
129
 
130
  with gr.Row():
131
  gr.LoginButton(scale=1)
 
3
  import requests
4
  import pandas as pd
5
  from typing import Optional
 
6
 
7
  # --- Constants ---
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
+ HF_API_URL = "https://api-inference.huggingface.co/models"
10
 
11
  class BasicAgent:
12
  def __init__(self):
13
+ """用 HuggingFace Inference API"""
14
+ self.hf_token = os.getenv("HF_TOKEN")
15
+ self.model_name = "meta-llama/Llama-2-7b-chat-hf"
16
+
17
+ if not self.hf_token:
18
+ print("βœ— HF_TOKEN not found")
19
+ self.agent = None
20
+ return
21
+
22
+ self.agent_url = f"{HF_API_URL}/{self.model_name}"
23
  self.agent = True
24
+ print("βœ“ Agent initialized with HF API")
25
 
26
  def __call__(self, question: str) -> str:
27
+ """ι€ιŽ HF Inference API ε‘Όε«ζ¨‘εž‹"""
28
+ if self.agent is None:
29
+ return "HF_TOKEN not configured. Add to Secrets!"
30
+
31
  try:
32
+ headers = {"Authorization": f"Bearer {self.hf_token}"}
33
+
34
+ payload = {
35
+ "inputs": question,
36
+ "parameters": {
37
+ "max_new_tokens": 256,
38
+ "temperature": 0.7,
39
+ "top_p": 0.9
40
+ }
41
+ }
42
+
43
+ response = requests.post(
44
+ self.agent_url,
45
+ headers=headers,
46
+ json=payload,
47
+ timeout=60
48
+ )
49
+
50
+ if response.status_code != 200:
51
+ return f"API Error {response.status_code}"
52
+
53
+ result = response.json()
54
 
55
+ if isinstance(result, list) and len(result) > 0:
56
+ answer = result[0].get("generated_text", "")
57
+ # εŽ»ι™€ε•ι‘Œιƒ¨εˆ†οΌŒεͺδΏη•™η­”ζ‘ˆ
58
+ answer = answer.replace(question, "").strip()
59
+ return answer[:1000] if answer else "No answer generated"
60
 
61
+ return "Invalid response"
 
 
 
 
 
62
 
63
+ except requests.exceptions.Timeout:
64
+ return "API timeout - try again"
65
  except Exception as e:
66
+ print(f"Error: {e}")
67
+ return f"Error: {str(e)[:100]}"
68
 
69
 
70
  def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
71
  """δΈ»θ¦θ©•δΌ°ε’ŒζδΊ€ε‡½ζ•Έ"""
72
 
 
73
  if profile is None:
74
  return "Please Login to Hugging Face with the button.", None
75
 
 
80
  questions_url = f"{api_url}/questions"
81
  submit_url = f"{api_url}/submit"
82
 
 
83
  try:
84
  agent = BasicAgent()
85
  except Exception as e:
86
+ return f"Error: {str(e)}", None
87
 
88
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
89
 
 
90
  try:
91
  response = requests.get(questions_url, timeout=30)
92
  response.raise_for_status()
 
97
  answers_payload = []
98
  results_log = []
99
 
 
100
  total = len(questions_data)
101
  for idx, item in enumerate(questions_data, 1):
102
  task_id = item.get("task_id")
 
127
  "Answer": error_answer
128
  })
129
 
 
130
  submission_data = {
131
  "username": username,
132
  "agent_code": agent_code,
 
148
  return status_msg, pd.DataFrame(results_log)
149
 
150
 
 
151
  with gr.Blocks(title="Unit 4 Final Assignment") as demo:
152
  gr.Markdown("# Unit 4 Final Project: AI Agent")
153
+ gr.Markdown("_Using Hugging Face Inference API_")
154
 
155
  with gr.Row():
156
  gr.LoginButton(scale=1)