Psiska commited on
Commit
a1fa38c
·
1 Parent(s): e401df7

Refactor app.py for chat interface and update agent logic

Browse files
Files changed (2) hide show
  1. agent.py +58 -14
  2. app.py +54 -45
agent.py CHANGED
@@ -1,28 +1,72 @@
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)
 
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
 
 
app.py CHANGED
@@ -85,52 +85,51 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
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
- status_message = f"Submission Failed: {error_detail}"
116
- print(status_message)
117
- results_df = pd.DataFrame(results_log)
118
- return status_message, results_df
119
- except requests.exceptions.Timeout:
120
- status_message = "Submission Failed: The request timed out."
121
- print(status_message)
122
- results_df = pd.DataFrame(results_log)
123
- return status_message, results_df
124
- except requests.exceptions.RequestException as e:
125
- status_message = f"Submission Failed: Network error - {e}"
126
- print(status_message)
127
- results_df = pd.DataFrame(results_log)
128
- return status_message, results_df
129
- except Exception as e:
130
- status_message = f"An unexpected error occurred during submission: {e}"
131
- print(status_message)
132
- results_df = pd.DataFrame(results_log)
133
- return status_message, results_df
134
 
135
  def test_init_agent_for_chat(text_input, history):
136
  # 1. Instantiate Agent ( modify this part to create your agent)
@@ -144,6 +143,15 @@ def test_init_agent_for_chat(text_input, history):
144
 
145
  return submitted_answer
146
 
 
 
 
 
 
 
 
 
 
147
  # --- Build Gradio Interface using Blocks ---
148
  with gr.Blocks() as demo:
149
  gr.Markdown("# Basic Agent Evaluation Runner")
@@ -164,7 +172,8 @@ with gr.Blocks() as demo:
164
 
165
  # gr.LoginButton()
166
 
167
- gr.ChatInterface(test_init_agent_for_chat, type="messages")
 
168
 
169
  # run_button = gr.Button("Run Evaluation & Submit All Answers")
170
 
 
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
 
144
  return submitted_answer
145
 
146
+ # --- Agent Logic for Chat Interface ---
147
+ def handle_chat(message, history):
148
+ try:
149
+ agent = BasicAgent()
150
+ response = agent(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
 
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