MohamedAliAmiraa commited on
Commit
7c505b4
·
verified ·
1 Parent(s): a216be4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +14 -35
app.py CHANGED
@@ -49,7 +49,6 @@ class BasicAgent:
49
  """Creates the master prompt, dynamically injecting a file-handling example if a URL is provided."""
50
  tool_docs = "\n".join([f"- {name}: {inspect.getdoc(func)}" for name, func in self.tools.items()])
51
 
52
- # Default web search example
53
  web_search_example = """
54
  **Example: Web Search**
55
  Question: Who was the prime minister of the UK in 1999?
@@ -64,39 +63,27 @@ Observation: [Page content confirming Tony Blair was Prime Minister from 1997 to
64
  Thought: I have confirmed the answer from a reliable source.
65
  Final Answer: Tony Blair"""
66
 
67
- # Dynamic file analysis example
68
  file_analysis_example = ""
69
  if file_url:
70
- code_snippet = "# This is a placeholder, will be replaced by a specific file handler\n"
71
  if file_url.endswith(('.xlsx', '.csv')):
72
  code_snippet = f"""
73
  import pandas as pd
74
  import requests
75
  import io
76
- # The user's file is at this URL, which MUST be used.
77
  url = '{file_url}'
78
  response = requests.get(url)
79
  df = pd.read_excel(io.BytesIO(response.content))
80
- # Now, I must analyze the dataframe `df` to answer the question.
81
- # For example, to see the first few rows, I can print(df.head()).
82
- # To calculate total sales, I would use print(df['Sales'].sum()).
83
- print(df.head())
84
  """
85
  elif file_url.endswith('.py'):
86
  code_snippet = f"""
87
  import requests
88
- # The user's Python code file is at this URL, which MUST be used.
89
  url = '{file_url}'
90
  response = requests.get(url)
91
- python_code = response.text
92
- # Now, I must execute this code to find the output.
93
- # I will use another python action to run the code.
94
- print("Code downloaded. Ready for execution in the next step.")
95
  """
96
- elif file_url.endswith(('.mp3', '.wav')):
97
- # Handling audio is complex and often requires external APIs or heavy libraries.
98
- # For this exam, we will state a clear limitation.
99
- file_analysis_example = "\n**Limitation:** I cannot process audio files. Please inform the user of this limitation."
100
 
101
  if code_snippet:
102
  file_analysis_example = f"""
@@ -112,10 +99,6 @@ Final Answer: [Answer based on the script's output]"""
112
 
113
  return f"""
114
  You are a helpful assistant that answers questions by thinking step-by-step and using the tools provided.
115
-
116
- You have access to the following tools:
117
- {tool_docs}
118
-
119
  **Process:**
120
  1. **Thought:** Analyze the user's question and create a plan. If you see an example below that matches your plan, follow it exactly.
121
  2. **Action:** Choose ONE tool from the list: {", ".join(self.tools.keys())}.
@@ -125,6 +108,9 @@ You have access to the following tools:
125
  6. **Thought:** Conclude that you have the final answer.
126
  7. **Final Answer:** Provide the final, direct answer to the user's question.
127
 
 
 
 
128
  {web_search_example}
129
  {file_analysis_example}
130
 
@@ -134,16 +120,13 @@ Begin!
134
  # --- Tool Definitions ---
135
  def search(self, query: str) -> str:
136
  """Searches the web with DuckDuckGo to find relevant URLs and information."""
137
- print(f"Tool: search, Query: {query}")
138
  try:
139
  with DDGS() as ddgs:
140
- results = [r for r in ddgs.text(query, max_results=4)]
141
- return str(results) if results else "No results found."
142
  except Exception as e: return f"Error during search: {e}"
143
 
144
  def browse(self, url: str) -> str:
145
  """Gets the full, clean text content of a single webpage URL."""
146
- print(f"Tool: browse, URL: {url}")
147
  try:
148
  response = requests.get(url, timeout=10, headers={'User-Agent': 'Mozilla/5.0'})
149
  soup = BeautifulSoup(response.content, 'html.parser')
@@ -152,7 +135,6 @@ Begin!
152
 
153
  def python(self, code: str) -> str:
154
  """Executes Python code to analyze data or files. Use `requests` to download files from URLs."""
155
- print(f"Tool: python, Code:\n{code}")
156
  code = code.strip().strip("`").replace("python\n", "").strip()
157
  buffer = io.StringIO()
158
  try:
@@ -164,17 +146,14 @@ Begin!
164
 
165
  def youtube_transcript(self, url: str) -> str:
166
  """Fetches the full transcript of a YouTube video from its URL."""
167
- print(f"Tool: youtube_transcript, URL: {url}")
168
  try:
169
  video_id = re.search(r"(?<=v=)[\w-]+", url).group(0)
170
- transcript_list = YouTubeTranscriptApi.get_transcript(video_id)
171
- return " ".join([item['text'] for item in transcript_list])
172
  except Exception as e: return f"Error fetching transcript: {e}"
173
 
174
  # --- Main ReAct Loop ---
175
  def __call__(self, task: Dict[str, Any]) -> str:
176
  file_url = task.get("files", [None])[0]
177
- # Dynamically create the prompt for each task
178
  system_prompt = self._create_system_prompt(file_url=file_url)
179
 
180
  question = task.get("question", "")
@@ -185,18 +164,18 @@ Begin!
185
  history = ""
186
 
187
  for i in range(8):
188
- print(f"--- Step {i+1} ---")
189
  full_prompt = prompt + history
190
  llm_response = self.llm.invoke(full_prompt).content.strip()
191
  history += f"\n{llm_response}"
192
 
193
  final_answer_match = re.search(r"Final Answer:\s*(.*)", llm_response, re.DOTALL)
194
  if final_answer_match:
195
- answer = final_answer_match.group(1).strip()
196
- print(f"Final Answer Found: {answer}")
197
- return answer
 
 
198
 
199
- action_match = re.search(r"Action:\s*(\w+)\s*Action Input:((.|\n)*)", ll.response)
200
  if action_match:
201
  tool_name = action_match.group(1).strip()
202
  tool_input = action_match.group(2).strip(' \n"`')
 
49
  """Creates the master prompt, dynamically injecting a file-handling example if a URL is provided."""
50
  tool_docs = "\n".join([f"- {name}: {inspect.getdoc(func)}" for name, func in self.tools.items()])
51
 
 
52
  web_search_example = """
53
  **Example: Web Search**
54
  Question: Who was the prime minister of the UK in 1999?
 
63
  Thought: I have confirmed the answer from a reliable source.
64
  Final Answer: Tony Blair"""
65
 
 
66
  file_analysis_example = ""
67
  if file_url:
68
+ code_snippet = ""
69
  if file_url.endswith(('.xlsx', '.csv')):
70
  code_snippet = f"""
71
  import pandas as pd
72
  import requests
73
  import io
 
74
  url = '{file_url}'
75
  response = requests.get(url)
76
  df = pd.read_excel(io.BytesIO(response.content))
77
+ print(df.to_string())
 
 
 
78
  """
79
  elif file_url.endswith('.py'):
80
  code_snippet = f"""
81
  import requests
 
82
  url = '{file_url}'
83
  response = requests.get(url)
84
+ python_code_to_run = response.text
85
+ print(python_code_to_run)
 
 
86
  """
 
 
 
 
87
 
88
  if code_snippet:
89
  file_analysis_example = f"""
 
99
 
100
  return f"""
101
  You are a helpful assistant that answers questions by thinking step-by-step and using the tools provided.
 
 
 
 
102
  **Process:**
103
  1. **Thought:** Analyze the user's question and create a plan. If you see an example below that matches your plan, follow it exactly.
104
  2. **Action:** Choose ONE tool from the list: {", ".join(self.tools.keys())}.
 
108
  6. **Thought:** Conclude that you have the final answer.
109
  7. **Final Answer:** Provide the final, direct answer to the user's question.
110
 
111
+ You have access to the following tools:
112
+ {tool_docs}
113
+
114
  {web_search_example}
115
  {file_analysis_example}
116
 
 
120
  # --- Tool Definitions ---
121
  def search(self, query: str) -> str:
122
  """Searches the web with DuckDuckGo to find relevant URLs and information."""
 
123
  try:
124
  with DDGS() as ddgs:
125
+ return str([r for r in ddgs.text(query, max_results=4)])
 
126
  except Exception as e: return f"Error during search: {e}"
127
 
128
  def browse(self, url: str) -> str:
129
  """Gets the full, clean text content of a single webpage URL."""
 
130
  try:
131
  response = requests.get(url, timeout=10, headers={'User-Agent': 'Mozilla/5.0'})
132
  soup = BeautifulSoup(response.content, 'html.parser')
 
135
 
136
  def python(self, code: str) -> str:
137
  """Executes Python code to analyze data or files. Use `requests` to download files from URLs."""
 
138
  code = code.strip().strip("`").replace("python\n", "").strip()
139
  buffer = io.StringIO()
140
  try:
 
146
 
147
  def youtube_transcript(self, url: str) -> str:
148
  """Fetches the full transcript of a YouTube video from its URL."""
 
149
  try:
150
  video_id = re.search(r"(?<=v=)[\w-]+", url).group(0)
151
+ return " ".join([item['text'] for item in YouTubeTranscriptApi.get_transcript(video_id)])
 
152
  except Exception as e: return f"Error fetching transcript: {e}"
153
 
154
  # --- Main ReAct Loop ---
155
  def __call__(self, task: Dict[str, Any]) -> str:
156
  file_url = task.get("files", [None])[0]
 
157
  system_prompt = self._create_system_prompt(file_url=file_url)
158
 
159
  question = task.get("question", "")
 
164
  history = ""
165
 
166
  for i in range(8):
 
167
  full_prompt = prompt + history
168
  llm_response = self.llm.invoke(full_prompt).content.strip()
169
  history += f"\n{llm_response}"
170
 
171
  final_answer_match = re.search(r"Final Answer:\s*(.*)", llm_response, re.DOTALL)
172
  if final_answer_match:
173
+ return final_answer_match.group(1).strip()
174
+
175
+ # *** THIS IS THE ONLY LINE THAT HAS BEEN CHANGED ***
176
+ # Corrected the typo from `ll.response` to `llm_response`
177
+ action_match = re.search(r"Action:\s*(\w+)\s*Action Input:((.|\n)*)", llm_response)
178
 
 
179
  if action_match:
180
  tool_name = action_match.group(1).strip()
181
  tool_input = action_match.group(2).strip(' \n"`')