dpernes commited on
Commit
9c945ec
·
verified ·
1 Parent(s): a33a2ba

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -5
app.py CHANGED
@@ -1,20 +1,58 @@
 
1
  import os
 
 
2
 
3
  import gradio as gr
4
  import pandas as pd
5
  import requests
6
  from smolagents import (
 
7
  DuckDuckGoSearchTool,
8
  FinalAnswerPromptTemplate,
9
- InferenceClientModel,
10
  ManagedAgentPromptTemplate,
11
  Model,
 
12
  PlanningPromptTemplate,
13
  PromptTemplates,
 
14
  ToolCallingAgent,
15
  VisitWebpageTool,
16
  )
17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  # (Keep Constants as is)
19
  # --- Constants ---
20
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
@@ -45,12 +83,36 @@ class GAIAgent:
45
  prompt_templates=prompt_templates,
46
  )
47
 
48
- def __call__(self, question: str) -> str:
49
  print(f"Agent received question (first 50 chars): {question[:50]}...")
 
 
 
50
  answer = self.agent.run(question)
51
  print(f"Agent returning answer: {answer}")
52
  return answer
53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
  def run_and_submit_all(profile: gr.OAuthProfile | None):
56
  """
@@ -73,8 +135,10 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
73
 
74
  # 1. Instantiate Agent ( modify this part to create your agent)
75
  try:
76
- model = InferenceClientModel(
77
- model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
 
 
78
  )
79
  agent = GAIAgent(model=model)
80
  except Exception as e:
@@ -112,11 +176,12 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
112
  for item in questions_data:
113
  task_id = item.get("task_id")
114
  question_text = item.get("question")
 
115
  if not task_id or question_text is None:
116
  print(f"Skipping item with missing task_id or question: {item}")
117
  continue
118
  try:
119
- submitted_answer = agent(question_text)
120
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
121
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
122
  except Exception as e:
 
1
+ import base64
2
  import os
3
+ import tempfile
4
+ from io import BytesIO
5
 
6
  import gradio as gr
7
  import pandas as pd
8
  import requests
9
  from smolagents import (
10
+ AmazonBedrockServerModel,
11
  DuckDuckGoSearchTool,
12
  FinalAnswerPromptTemplate,
 
13
  ManagedAgentPromptTemplate,
14
  Model,
15
+ OpenAIServerModel,
16
  PlanningPromptTemplate,
17
  PromptTemplates,
18
+ Tool,
19
  ToolCallingAgent,
20
  VisitWebpageTool,
21
  )
22
 
23
+
24
+ class CustomAmazonBedrockServerModel(AmazonBedrockServerModel):
25
+ """
26
+ Fixed model class to handle Amazon Bedrock model.
27
+ """
28
+
29
+ def _prepare_completion_kwargs(
30
+ self,
31
+ messages: list[dict[str, str]],
32
+ stop_sequences: list[str] | None = None,
33
+ grammar: str | None = None,
34
+ tools_to_call_from: list[Tool] | None = None,
35
+ custom_role_conversions: dict[str, str] | None = None,
36
+ convert_images_to_image_urls: bool = False,
37
+ **kwargs,
38
+ ) -> dict:
39
+ """Remove invalid keys."""
40
+ completion_kwargs = super()._prepare_completion_kwargs(
41
+ messages=messages,
42
+ stop_sequences=None, # Bedrock support stop_sequence using Inference Config
43
+ grammar=None, # Bedrock doesn't support grammar
44
+ tools_to_call_from=tools_to_call_from,
45
+ custom_role_conversions=custom_role_conversions,
46
+ convert_images_to_image_urls=convert_images_to_image_urls,
47
+ **kwargs,
48
+ )
49
+
50
+ completion_kwargs.pop("tools")
51
+ completion_kwargs.pop("tool_choice")
52
+
53
+ return completion_kwargs
54
+
55
+
56
  # (Keep Constants as is)
57
  # --- Constants ---
58
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
83
  prompt_templates=prompt_templates,
84
  )
85
 
86
+ def __call__(self, task_id: str, question: str, file_name: str | None = None) -> str:
87
  print(f"Agent received question (first 50 chars): {question[:50]}...")
88
+ if file_name:
89
+ attachment_text = self._process_attachment(task_id, file_name)
90
+ question += f"\n{attachment_text}"
91
  answer = self.agent.run(question)
92
  print(f"Agent returning answer: {answer}")
93
  return answer
94
 
95
+ def _process_attachment(self, task_id: str, file_name: str) -> str:
96
+ api_url = DEFAULT_API_URL
97
+ get_associated_files_url = f"{api_url}/files/{task_id}"
98
+ response = requests.get(get_associated_files_url, timeout=15)
99
+ response.raise_for_status()
100
+
101
+ if file_name.endswith(".mp3"):
102
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as f:
103
+ f.write(response.content)
104
+ return f".mp3 file path: {f.name}\n"
105
+ elif file_name.endswith(".py"):
106
+ file_content = response.text
107
+ return "Python code:\n```python\n" + file_content + "\n```\n"
108
+ elif file_name.endswith(".xlsx"):
109
+ xlsx_io = BytesIO(response.content)
110
+ csv_data = pd.read_excel(xlsx_io).to_csv(index=False)
111
+ return "Excel file (as CSV):\n```csv\n" + csv_data + "\n```\n"
112
+ elif file_name.endswith(".png"):
113
+ base64_str = base64.b64encode(response.content).decode("utf-8")
114
+ return ".png image (in base64 format):\n\n```base64\n" + base64_str + "\n```\n"
115
+
116
 
117
  def run_and_submit_all(profile: gr.OAuthProfile | None):
118
  """
 
135
 
136
  # 1. Instantiate Agent ( modify this part to create your agent)
137
  try:
138
+ model = OpenAIServerModel(
139
+ model_id="gpt-4o-mini",
140
+ api_base=os.environ["OPENAI_URL"],
141
+ api_key=os.environ["OPENAI_API_KEY"],
142
  )
143
  agent = GAIAgent(model=model)
144
  except Exception as e:
 
176
  for item in questions_data:
177
  task_id = item.get("task_id")
178
  question_text = item.get("question")
179
+ file_name = item.get("file_name")
180
  if not task_id or question_text is None:
181
  print(f"Skipping item with missing task_id or question: {item}")
182
  continue
183
  try:
184
+ submitted_answer = agent(task_id, question_text, file_name)
185
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
186
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
187
  except Exception as e: