pathmohd123 commited on
Commit
345402c
Β·
verified Β·
1 Parent(s): d591abb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -124
app.py CHANGED
@@ -1,116 +1,37 @@
1
  import os
2
  import json
3
  import requests
4
- import openai
5
  import traceback
6
  import gradio as gr
7
  import pandas as pd
8
  from typing import Optional
9
  from dotenv import load_dotenv
 
10
 
11
  # ──────────────── Load Environment ────────────────
12
  load_dotenv()
13
- openai.api_key = os.getenv("OPENAI_API_KEY")
14
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
15
 
16
- # ──────────────── Utility: Python Executor ────────────────
17
- def python_exec(code: str) -> str:
18
- try:
19
- safe_globals = {"__builtins__": {}}
20
- local_vars = {}
21
- exec(code, safe_globals, local_vars)
22
- if "result" in local_vars:
23
- return str(local_vars["result"])
24
- else:
25
- return "No variable named 'result' was produced."
26
- except Exception:
27
- return "Error during Python execution:\n" + traceback.format_exc()
28
-
29
- # ──────────────── Function Schema ────────────────
30
- function_definitions = [
31
- {
32
- "name": "python_exec",
33
- "description": "Execute Python code and return the value of `result` (or printed output).",
34
- "parameters": {
35
- "type": "object",
36
- "properties": {
37
- "code": {
38
- "type": "string",
39
- "description": "The Python code to execute. Must assign the final answer to a variable named `result`."
40
- }
41
- },
42
- "required": ["code"]
43
- }
44
- }
45
- ]
46
 
47
  # ──────────────── Agent Class ────────────────
48
- class BasicAgent:
49
  def __init__(self):
50
- if not openai.api_key:
51
- raise RuntimeError("Please set OPENAI_API_KEY in your .env file")
52
- print("βœ… BasicAgent initialized with GPT-4o-mini.")
53
 
54
  def __call__(self, question: str) -> str:
55
  try:
56
- first_resp = openai.chat.completions.create(
57
- model="gpt-4o-mini",
58
- messages=[
59
- {
60
- "role": "system",
61
- "content": "You are an assistant that can solve math/programming questions by calling python_exec when needed."
62
- },
63
- {"role": "user", "content": question}
64
- ],
65
- functions=function_definitions,
66
- function_call="auto"
67
- )
68
  except Exception as e:
69
- print(f"LLM call failed: {e}")
70
  return f"LLM Error: {e}"
71
 
72
- first_msg = first_resp.choices[0].message
73
-
74
- if first_msg.function_call is not None:
75
- fn_name = first_msg.function_call.name
76
- fn_args_str = first_msg.function_call.arguments
77
- try:
78
- fn_args = json.loads(fn_args_str)
79
- except json.JSONDecodeError:
80
- return "Error: could not parse function_call arguments."
81
-
82
- if fn_name == "python_exec":
83
- code_to_run = fn_args.get("code", "")
84
- python_output = python_exec(code_to_run)
85
-
86
- try:
87
- second_resp = openai.chat.completions.create(
88
- model="gpt-4o-mini",
89
- messages=[
90
- {
91
- "role": "system",
92
- "content": "You are an assistant that can call python_exec when needed."
93
- },
94
- {"role": "user", "content": question},
95
- {
96
- "role": "assistant",
97
- "content": None,
98
- "function_call": {
99
- "name": "python_exec",
100
- "arguments": json.dumps({"code": code_to_run})
101
- }
102
- },
103
- {"role": "function", "name": "python_exec", "content": python_output}
104
- ]
105
- )
106
- return second_resp.choices[0].message.content.strip()
107
- except Exception as e:
108
- return f"LLM Error: {e}"
109
- else:
110
- return f"Requested unknown function {fn_name}."
111
- else:
112
- return first_msg.content.strip()
113
-
114
  # ──────────────── API Helpers ────────────────
115
  def get_all_questions(api_url: str) -> list[dict]:
116
  resp = requests.get(f"{api_url}/questions", timeout=15)
@@ -128,20 +49,16 @@ def submit_answers(api_url: str, username: str, code_link: str, answers: list[di
128
  return resp.json()
129
 
130
  # ──────────────── Gradio Evaluation Logic ────────────────
131
- def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None, *args):
132
- if profile:
133
- if isinstance(profile, dict):
134
- username = profile.get("preferred_username", "").strip()
135
- else:
136
- username = str(profile).strip()
137
- else:
138
  return "❌ Please log in to Hugging Face using the button above.", None
 
139
 
140
  space_id = os.getenv("SPACE_ID", "")
141
  code_link = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else ""
142
 
143
  try:
144
- agent = BasicAgent()
145
  except Exception as e:
146
  return f"❌ Error initializing agent: {e}", None
147
 
@@ -152,6 +69,7 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None, *args):
152
 
153
  answers_payload = []
154
  results_log = []
 
155
  for item in questions_data:
156
  task_id = item.get("task_id")
157
  question_text = item.get("question", "")
@@ -193,7 +111,7 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None, *args):
193
 
194
  # ──────────────── Gradio UI ────────────────
195
  with gr.Blocks() as demo:
196
- gr.Markdown("# 🧠 Basic Agent Evaluation")
197
  gr.Markdown(
198
  """
199
  **Instructions:**
@@ -201,8 +119,6 @@ with gr.Blocks() as demo:
201
  1. Copy this Space and define your own agent logic.
202
  2. Log in with your Hugging Face account.
203
  3. Click β€œRun Evaluation & Submit All Answers” to test and submit.
204
-
205
- - Format matters. Leaderboard uses exact match!
206
  """
207
  )
208
  gr.LoginButton()
@@ -210,28 +126,8 @@ with gr.Blocks() as demo:
210
  status_output = gr.Textbox(label="Status", lines=5, interactive=False)
211
  results_table = gr.DataFrame(label="Agent Answers", wrap=True)
212
 
213
- run_button.click(
214
- fn=run_and_submit_all,
215
- inputs=[],
216
- outputs=[status_output, results_table]
217
- )
218
 
219
- # ──────────────── Launch App ────────────────
220
  if __name__ == "__main__":
221
- space_host = os.getenv("SPACE_HOST")
222
- space_id = os.getenv("SPACE_ID")
223
-
224
- if space_host:
225
- print(f"βœ… SPACE_HOST found: {space_host}")
226
- print(f" Runtime URL: https://{space_host}.hf.space")
227
- else:
228
- print("ℹ️ SPACE_HOST not found (running locally)")
229
-
230
- if space_id:
231
- print(f"βœ… SPACE_ID found: {space_id}")
232
- print(f" Repo URL: https://huggingface.co/spaces/{space_id}")
233
- else:
234
- print("ℹ️ SPACE_ID not found")
235
-
236
  print("Launching Gradio Interface...")
237
- demo.launch(debug=True, server_name="0.0.0.0", server_port=7860)
 
1
  import os
2
  import json
3
  import requests
 
4
  import traceback
5
  import gradio as gr
6
  import pandas as pd
7
  from typing import Optional
8
  from dotenv import load_dotenv
9
+ from transformers import pipeline
10
 
11
  # ──────────────── Load Environment ────────────────
12
  load_dotenv()
13
+ hf_token = os.getenv("HF_TOKEN")
14
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
15
 
16
+ # ──────────────── Load Zephyr Model ────────────────
17
+ try:
18
+ pipe = pipeline("text-generation", model="HuggingFaceH4/zephyr-7b-alpha", token=hf_token)
19
+ except Exception as e:
20
+ raise RuntimeError(f"Model loading failed: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  # ──────────────── Agent Class ────────────────
23
+ class ZephyrAgent:
24
  def __init__(self):
25
+ print("βœ… ZephyrAgent initialized.")
 
 
26
 
27
  def __call__(self, question: str) -> str:
28
  try:
29
+ prompt = f"<|system|>\nYou are a helpful agent that answers questions correctly and concisely.\n<|user|>\n{question}\n<|assistant|>"
30
+ output = pipe(prompt, max_new_tokens=100, do_sample=False)
31
+ return output[0]["generated_text"].split("<|assistant|>")[-1].strip()
 
 
 
 
 
 
 
 
 
32
  except Exception as e:
 
33
  return f"LLM Error: {e}"
34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  # ──────────────── API Helpers ────────────────
36
  def get_all_questions(api_url: str) -> list[dict]:
37
  resp = requests.get(f"{api_url}/questions", timeout=15)
 
49
  return resp.json()
50
 
51
  # ──────────────── Gradio Evaluation Logic ────────────────
52
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
53
+ if not profile:
 
 
 
 
 
54
  return "❌ Please log in to Hugging Face using the button above.", None
55
+ username = profile.username.strip()
56
 
57
  space_id = os.getenv("SPACE_ID", "")
58
  code_link = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else ""
59
 
60
  try:
61
+ agent = ZephyrAgent()
62
  except Exception as e:
63
  return f"❌ Error initializing agent: {e}", None
64
 
 
69
 
70
  answers_payload = []
71
  results_log = []
72
+
73
  for item in questions_data:
74
  task_id = item.get("task_id")
75
  question_text = item.get("question", "")
 
111
 
112
  # ──────────────── Gradio UI ────────────────
113
  with gr.Blocks() as demo:
114
+ gr.Markdown("# 🧠 Zephyr-7B Agent Evaluation")
115
  gr.Markdown(
116
  """
117
  **Instructions:**
 
119
  1. Copy this Space and define your own agent logic.
120
  2. Log in with your Hugging Face account.
121
  3. Click β€œRun Evaluation & Submit All Answers” to test and submit.
 
 
122
  """
123
  )
124
  gr.LoginButton()
 
126
  status_output = gr.Textbox(label="Status", lines=5, interactive=False)
127
  results_table = gr.DataFrame(label="Agent Answers", wrap=True)
128
 
129
+ run_button.click(fn=run_and_submit_all, inputs=[], outputs=[status_output, results_table])
 
 
 
 
130
 
 
131
  if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  print("Launching Gradio Interface...")
133
+ demo.launch(debug=True, server_name="0.0.0.0", server_port=7860)