Psiska commited on
Commit
28b236b
·
1 Parent(s): 66abe20

Comments in submission in app.py

Browse files
Files changed (2) hide show
  1. agent.py +15 -59
  2. app.py +49 -55
agent.py CHANGED
@@ -1,72 +1,28 @@
1
- #import os
2
- #from PIL import Image
3
- #from smolagents import CodeAgent, HfApiModel, InferenceClientModel
4
 
5
- #import tools.tools as tls
6
 
7
  # --- Basic Agent Definition ---
8
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
9
 
10
- #class BasicAgent:
11
- # def __init__(self):
12
- # print("BasicAgent initialized.")
13
- # def __call__(self, question: str) -> str:
14
- # model = HfApiModel(model_id="https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud", provider="together", use_auth_token=True)
15
- #
16
- # agent = CodeAgent(
17
- # tools=[tls.search_tool, tls.calculate_cargo_travel_time],
18
- # model=InferenceClientModel(),
19
- # additional_authorized_imports=["pandas"],
20
- # max_steps=20,
21
- # )
22
-
23
- # fixed_answer = agent.run(question)
24
-
25
- # print(f"Agent received question (first 50 chars): {question[:50]}...")
26
- # # fixed_answer = "This is a default answer."
27
- # print(f"Agent returning fixed answer: {fixed_answer}")
28
- # return str(fixed_answer)
29
-
30
-
31
- # agent.py
32
- import os
33
- from smolagents import CodeAgent, InferenceClientModel, HfApiModel
34
- import tools.tools as tls
35
-
36
  class BasicAgent:
37
  def __init__(self):
38
- print("BasicAgent initialized.")
39
-
40
- # Initialize model (e.g. HfApiModel or InferenceClientModel)
41
- self.model = HfApiModel(
42
- model_id="https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud",
43
- provider="together",
44
- use_auth_token=True
45
- )
46
 
47
- # Initialize agent once
48
- self.agent = CodeAgent(
49
  tools=[tls.search_tool, tls.calculate_cargo_travel_time],
50
- model=self.model, # <-- use self.model instead of re-instantiating
51
  additional_authorized_imports=["pandas"],
52
- max_steps=20
53
  )
54
 
55
- self.chat_history = [] # Optional: for memory support later
56
-
57
- def __call__(self, question: str) -> str:
58
- print(f"\n🧠 Received question: {question[:50]}...")
59
-
60
- # Optionally include memory
61
- context = "\n".join([f"User: {u}\nAssistant: {a}" for u, a in self.chat_history])
62
- prompt = f"{context}\nUser: {question}\nAssistant:".strip()
63
-
64
- try:
65
- response = self.agent.run(prompt)
66
- except Exception as e:
67
- response = f"[Agent Error]: {e}"
68
-
69
- self.chat_history.append((question, response))
70
 
71
- print("📤 Returning answer:", response[:80])
72
- return response
 
 
 
1
+ import os
2
+ from PIL import Image
3
+ from smolagents import CodeAgent, HfApiModel, InferenceClientModel
4
 
5
+ import tools.tools as tls
6
 
7
  # --- Basic Agent Definition ---
8
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  class BasicAgent:
11
  def __init__(self):
12
+ print("BasicAgent initialized.")
13
+ def __call__(self, question: str) -> str:
14
+ model = HfApiModel(model_id="https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud", provider="together", use_auth_token=True)
 
 
 
 
 
15
 
16
+ agent = CodeAgent(
 
17
  tools=[tls.search_tool, tls.calculate_cargo_travel_time],
18
+ model=InferenceClientModel(),
19
  additional_authorized_imports=["pandas"],
20
+ max_steps=20,
21
  )
22
 
23
+ fixed_answer = agent.run(question)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
26
+ # fixed_answer = "This is a default answer."
27
+ print(f"Agent returning fixed answer: {fixed_answer}")
28
+ return str(fixed_answer)
app.py CHANGED
@@ -62,6 +62,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
62
  print(f"An unexpected error occurred fetching questions: {e}")
63
  return f"An unexpected error occurred fetching questions: {e}", None
64
 
 
65
  # 3. Run your Agent
66
  results_log = []
67
  answers_payload = []
@@ -83,53 +84,56 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
83
  if not answers_payload:
84
  print("Agent did not produce any answers to submit.")
85
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
86
-
 
87
  # 4. Prepare Submission
88
- #submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
89
- #status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
90
- #print(status_update)
91
 
92
  # 5. Submit
93
- #print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
94
- #try:
95
- # response = requests.post(submit_url, json=submission_data, timeout=60)
96
- # response.raise_for_status()
97
- # result_data = response.json()
98
- # final_status = (
99
- # f"Submission Successful!\n"
100
- # f"User: {result_data.get('username')}\n"
101
- # f"Overall Score: {result_data.get('score', 'N/A')}% "
102
- # f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
103
- # f"Message: {result_data.get('message', 'No message received.')}"
104
- # )
105
- # print("Submission successful.")
106
- # results_df = pd.DataFrame(results_log)
107
- # return final_status, results_df
108
- #except requests.exceptions.HTTPError as e:
109
- # error_detail = f"Server responded with status {e.response.status_code}."
110
- # try:
111
- # error_json = e.response.json()
112
- # error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
113
- # except requests.exceptions.JSONDecodeError:
114
- # error_detail += f" Response: {e.response.text[:500]}"
115
- # print(status_message)
116
- # results_df = pd.DataFrame(results_log)
117
- # return status_message, results_df
118
- #except requests.exceptions.Timeout:
119
- # status_message = "Submission Failed: The request timed out."
120
- # print(status_message)
121
- # results_df = pd.DataFrame(results_log)
122
- # return status_message, results_df
123
- #except requests.exceptions.RequestException as e:
124
- # status_message = f"Submission Failed: Network error - {e}"
125
- # print(status_message)
126
- # results_df = pd.DataFrame(results_log)
127
- # return status_message, results_df
128
- #except Exception as e:
129
- # status_message = f"An unexpected error occurred during submission: {e}"
130
- # print(status_message)
131
- # results_df = pd.DataFrame(results_log)
132
- # return status_message, results_df
 
 
133
 
134
  def test_init_agent_for_chat(text_input, history):
135
  # 1. Instantiate Agent ( modify this part to create your agent)
@@ -143,15 +147,6 @@ def test_init_agent_for_chat(text_input, history):
143
 
144
  return submitted_answer
145
 
146
- # --- Agent Logic for Chat Interface ---
147
- def handle_chat(message, history):
148
- try:
149
- basicAgent = agent.BasicAgent()
150
- response = basicAgent(message)
151
- return response
152
- except Exception as e:
153
- return f"[ERROR] Agent failed: {str(e)}"
154
-
155
  # --- Build Gradio Interface using Blocks ---
156
  with gr.Blocks() as demo:
157
  gr.Markdown("# Basic Agent Evaluation Runner")
@@ -172,8 +167,7 @@ with gr.Blocks() as demo:
172
 
173
  # gr.LoginButton()
174
 
175
- #gr.ChatInterface(test_init_agent_for_chat, type="messages")
176
- gr.ChatInterface(handle_chat, chatbot=gr.Chatbot(), textbox=gr.Textbox(placeholder="Ask me anything about cargo travel..."))
177
 
178
  # run_button = gr.Button("Run Evaluation & Submit All Answers")
179
 
 
62
  print(f"An unexpected error occurred fetching questions: {e}")
63
  return f"An unexpected error occurred fetching questions: {e}", None
64
 
65
+
66
  # 3. Run your Agent
67
  results_log = []
68
  answers_payload = []
 
84
  if not answers_payload:
85
  print("Agent did not produce any answers to submit.")
86
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
87
+
88
+ '''
89
  # 4. Prepare Submission
90
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
91
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
92
+ print(status_update)
93
 
94
  # 5. Submit
95
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
96
+ try:
97
+ response = requests.post(submit_url, json=submission_data, timeout=60)
98
+ response.raise_for_status()
99
+ result_data = response.json()
100
+ final_status = (
101
+ f"Submission Successful!\n"
102
+ f"User: {result_data.get('username')}\n"
103
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
104
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
105
+ f"Message: {result_data.get('message', 'No message received.')}"
106
+ )
107
+ print("Submission successful.")
108
+ results_df = pd.DataFrame(results_log)
109
+ return final_status, results_df
110
+ except requests.exceptions.HTTPError as e:
111
+ error_detail = f"Server responded with status {e.response.status_code}."
112
+ try:
113
+ error_json = e.response.json()
114
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
115
+ except requests.exceptions.JSONDecodeError:
116
+ error_detail += f" Response: {e.response.text[:500]}"
117
+ status_message = f"Submission Failed: {error_detail}"
118
+ print(status_message)
119
+ results_df = pd.DataFrame(results_log)
120
+ return status_message, results_df
121
+ except requests.exceptions.Timeout:
122
+ status_message = "Submission Failed: The request timed out."
123
+ print(status_message)
124
+ results_df = pd.DataFrame(results_log)
125
+ return status_message, results_df
126
+ except requests.exceptions.RequestException as e:
127
+ status_message = f"Submission Failed: Network error - {e}"
128
+ print(status_message)
129
+ results_df = pd.DataFrame(results_log)
130
+ return status_message, results_df
131
+ except Exception as e:
132
+ status_message = f"An unexpected error occurred during submission: {e}"
133
+ print(status_message)
134
+ results_df = pd.DataFrame(results_log)
135
+ return status_message, results_df
136
+ '''
137
 
138
  def test_init_agent_for_chat(text_input, history):
139
  # 1. Instantiate Agent ( modify this part to create your agent)
 
147
 
148
  return submitted_answer
149
 
 
 
 
 
 
 
 
 
 
150
  # --- Build Gradio Interface using Blocks ---
151
  with gr.Blocks() as demo:
152
  gr.Markdown("# Basic Agent Evaluation Runner")
 
167
 
168
  # gr.LoginButton()
169
 
170
+ gr.ChatInterface(test_init_agent_for_chat, type="messages")
 
171
 
172
  # run_button = gr.Button("Run Evaluation & Submit All Answers")
173