jan01 commited on
Commit
54e4dae
·
verified ·
1 Parent(s): 7d933aa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -22
app.py CHANGED
@@ -2,46 +2,37 @@ import os
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
5
- import openai # NEW: import OpenAI SDK
6
 
7
  # --- Constants ---
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
 
10
- # --- Basic Agent Definition ---
11
- # Modified to use OpenAI GPT-4 API for Q&A
12
  class BasicAgent:
13
  def __init__(self):
14
- self.api_key = os.getenv("OPEN_API_KEY")
15
- if not self.api_key:
16
  raise ValueError("OPENAI_API_KEY environment variable is not set!")
17
- openai.api_key = self.api_key
18
- print("BasicAgent initialized with OpenAI API key.")
19
-
20
  def __call__(self, question: str) -> str:
21
- print(f"Agent received question (first 50 chars): {question[:50]}...")
22
  try:
23
  response = openai.ChatCompletion.create(
24
- model="gpt-4",
25
  messages=[
26
  {"role": "system", "content": "You are a helpful assistant."},
27
  {"role": "user", "content": question}
28
  ],
29
- max_tokens=200,
30
- temperature=0
31
  )
32
  answer = response['choices'][0]['message']['content'].strip()
33
- print(f"Agent returning answer: {answer}")
34
  return answer
35
  except Exception as e:
36
- print(f"Error calling OpenAI API: {e}")
37
  return "Sorry, I couldn't answer that."
38
 
39
  def run_and_submit_all(profile: gr.OAuthProfile | None):
40
- """
41
- Fetches all questions, runs the BasicAgent on them, submits all answers,
42
- and displays the results.
43
- """
44
- space_id = os.getenv("SPACE_ID") # For link to your codebase
45
 
46
  if profile:
47
  username = f"{profile.username}"
@@ -63,7 +54,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
63
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Code repo link unavailable"
64
  print(agent_code)
65
 
66
- # Fetch questions
67
  try:
68
  response = requests.get(questions_url, timeout=15)
69
  response.raise_for_status()
@@ -152,8 +142,8 @@ with gr.Blocks() as demo:
152
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
153
  ---
154
  **Disclaimers:**
155
- Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
156
- This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
157
  """
158
  )
159
 
 
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
5
+ import openai # Added openai import
6
 
7
  # --- Constants ---
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
 
10
+ # --- Basic Agent using OpenAI GPT ---
 
11
  class BasicAgent:
12
  def __init__(self):
13
+ openai.api_key = os.getenv("OPENAI_API_KEY")
14
+ if not openai.api_key:
15
  raise ValueError("OPENAI_API_KEY environment variable is not set!")
16
+
 
 
17
  def __call__(self, question: str) -> str:
 
18
  try:
19
  response = openai.ChatCompletion.create(
20
+ model="gpt-4", # or "gpt-3.5-turbo"
21
  messages=[
22
  {"role": "system", "content": "You are a helpful assistant."},
23
  {"role": "user", "content": question}
24
  ],
25
+ max_tokens=150,
26
+ temperature=0.7
27
  )
28
  answer = response['choices'][0]['message']['content'].strip()
 
29
  return answer
30
  except Exception as e:
31
+ print(f"OpenAI API error: {e}")
32
  return "Sorry, I couldn't answer that."
33
 
34
  def run_and_submit_all(profile: gr.OAuthProfile | None):
35
+ space_id = os.getenv("SPACE_ID")
 
 
 
 
36
 
37
  if profile:
38
  username = f"{profile.username}"
 
54
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Code repo link unavailable"
55
  print(agent_code)
56
 
 
57
  try:
58
  response = requests.get(questions_url, timeout=15)
59
  response.raise_for_status()
 
142
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
143
  ---
144
  **Disclaimers:**
145
+ Once clicking on the "submit" button, it can take quite some time (this is the time for the agent to go through all the questions).
146
+ This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance, for the delay process of the submit button, a solution could be to cache the answers and submit in a separate action or even to answer the questions asynchronously.
147
  """
148
  )
149