GoodLuckChuck commited on
Commit
d902a13
·
verified ·
1 Parent(s): 39e97b9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -18
app.py CHANGED
@@ -25,7 +25,8 @@ print("DEBUG: typing imported")
25
  # Import necessary components from smolagents
26
  try:
27
  from smolagents import CodeAgent, Tool, OpenAIServerModel
28
- print("DEBUG: smolagents components (CodeAgent, Tool, OpenAIServerModel) imported successfully.")
 
29
  except ImportError as e: # Catch the specific error for better logging
30
  print(f"DEBUG: Failed to import smolagents. Error: {e}")
31
  logging.error(f"Failed to import smolagents. Please ensure it is installed and not corrupted. Error: {e}")
@@ -51,7 +52,21 @@ except ImportError as e: # Catch the specific error for better logging
51
  def __init__(self, *args, **kwargs):
52
  print("DEBUG: Dummy OpenAIServerModel initialized because smolagents failed to import.")
53
  logging.error("Dummy OpenAIServerModel initialized because smolagents failed to import.")
 
 
 
 
 
 
 
54
  pass
 
 
 
 
 
 
 
55
 
56
  from datetime import datetime
57
  print("DEBUG: datetime imported")
@@ -92,13 +107,12 @@ Follow this process for every question:
92
  5. THOUGHT: Analyze the observation. Is it what you expected? Do you have enough information to answer the user's question now? If not, refine your search or decide on the next step.
93
  6. If you have the information, formulate the final answer according to the formatting rules.
94
 
95
- **ULTRA-CRITICAL FINAL ANSWER INSTRUCTIONS - READ CAREFULLY:**
96
- Your *entire textual response* for this turn, after all THOUGHTs, CODE, and OBSERVATIONs, MUST end with the final answer.
97
- This final answer MUST begin on a **brand new line** with the exact literal string "FINAL ANSWER: " (note the space after the colon).
98
- The value of the answer should immediately follow this prefix.
99
- ABSOLUTELY NO other text, thoughts, explanations, or conversational remarks should come *after* the "FINAL ANSWER: [Your Answer Value]" line. Your response for the turn stops immediately after the answer value.
100
 
101
- **Example of a PERFECT Full Agent Response Structure (this is what your complete text output should look like):**
102
  THOUGHT: The user is asking for the capital of France. I should use web_search to find this.
103
  CODE:
104
  ```python
@@ -109,17 +123,25 @@ OBSERVATION: Title: Paris - Wikipedia Snippet: Paris is the capital and most pop
109
  THOUGHT: The search result clearly states that Paris is the capital of France. I have sufficient information. I will provide this as the final answer, following the formatting rules for a string.
110
  FINAL ANSWER: Paris
111
 
112
- **Another Example (for a question "what is the opposite of left?"):**
113
  THOUGHT: The question asks for the opposite of the word "left". This is general knowledge and does not require a tool. The opposite of "left" is "right". I will provide this as the final answer.
114
  FINAL ANSWER: right
115
 
116
- **Formatting rules for the value that comes *after* the "FINAL ANSWER: " prefix:**
117
  - If the question asks for a number: Provide only the number itself (e.g., `FINAL ANSWER: 42`). Do not use commas for thousands separation (e.g., use `FINAL ANSWER: 1234` not `FINAL ANSWER: 1,234`). Do not include units like '$' or '%' unless the question specifically asks for it and it's part of the answer.
118
  - If the question asks for a string: Provide the most concise string possible (e.g., `FINAL ANSWER: right`). Avoid articles (a, an, the) unless grammatically essential. Avoid common abbreviations (e.g., for cities like "NYC" for "New York City") unless the question implies it. Write out numerical digits as words (e.g., `FINAL ANSWER: two` instead of `FINAL ANSWER: 2`) unless numerical digits are requested.
119
  - If the question asks for a comma-separated list: Apply the above string/number rules to each element. Ensure elements are separated ONLY by a comma (e.g., `FINAL ANSWER: item one,item two,three`). NO space after the comma unless it's part of the item itself.
120
  - If the answer is a calculation result, provide just the number (e.g., `FINAL ANSWER: 10`).
121
 
122
- **IMPORTANT REMINDER**: The "FINAL ANSWER: " prefix is a literal string you must output as the very last part of your response text for the current turn. Do not confuse this with any internal `final_answer()` Python function you might generate in your CODE block; this instruction is about the final textual output of your entire multi-step reasoning.
 
 
 
 
 
 
 
 
123
  """
124
 
125
  CONFIG = AppConfig()
@@ -155,7 +177,7 @@ print("DEBUG: Utility functions defined.")
155
  # --- Tool Definitions ---
156
  print("DEBUG: Defining GoogleSearchTool.")
157
  class GoogleSearchTool(Tool):
158
- name = "web_search" # This is the name the LLM will use to call the tool
159
  description = "Searches the web using Serper API for information. Input: a string search query. Output: formatted search results string."
160
  inputs = {
161
  "query": {"type": "string", "description": "The search query to execute."},
@@ -167,11 +189,11 @@ class GoogleSearchTool(Tool):
167
  }
168
  }
169
  output_type = "string"
170
- is_async = True # Important for smolagents to know this tool's forward method is async
171
 
172
  def __init__(self, session: aiohttp.ClientSession):
173
  super().__init__()
174
- self._session = session # Use the session passed from ChuckAgent
175
  print("DEBUG: GoogleSearchTool instance created.")
176
 
177
  async def forward(self, query: str, provider: str = "serpapi") -> str:
@@ -263,7 +285,7 @@ class QuestionAnsweringAgent(CodeAgent):
263
  super().__init__(**minimal_super_args)
264
  print("DEBUG: QuestionAnsweringAgent super().__init__ successful (workaround active).")
265
 
266
- self.system_prompt = CONFIG.AGENT_SYSTEM_PROMPT
267
  print(f"DEBUG: QuestionAnsweringAgent explicitly set self.system_prompt.")
268
 
269
  if hasattr(self, 'verbosity_level'):
@@ -293,7 +315,7 @@ class QuestionAnsweringAgent(CodeAgent):
293
  exc_info=True
294
  )
295
  raise
296
- except Exception as e: # This will catch other exceptions like the AssertionError from smolagents
297
  print(f"DEBUG: ERROR - QuestionAnsweringAgent Unexpected error during __init__ (possibly from tool validation): {type(e).__name__} - {e}")
298
  logger.error(f"Unexpected error during QuestionAnsweringAgent __init__: {e}", exc_info=True)
299
  raise
@@ -326,9 +348,32 @@ class QuestionAnsweringAgent(CodeAgent):
326
  final_answer_for_submission = match.group(1).strip()
327
  print(f"DEBUG: QuestionAnsweringAgent extracted FINAL ANSWER: '{final_answer_for_submission}'")
328
  else:
329
- logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Using full response as fallback.")
330
- print("DEBUG: WARNING - QuestionAnsweringAgent could not find 'FINAL ANSWER:' in agent's response.")
331
- final_answer_for_submission = full_agent_response.strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
332
 
333
  if not final_answer_for_submission:
334
  logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
@@ -748,3 +793,4 @@ if __name__ == "__main__":
748
  print("\n" + "="*15 + " Application Shutdown " + "="*15)
749
  else:
750
  print("DEBUG: Script is being imported, not run as main.")
 
 
25
  # Import necessary components from smolagents
26
  try:
27
  from smolagents import CodeAgent, Tool, OpenAIServerModel
28
+ from smolagents.agent_types import AgentMessage # Needed for constructing messages for the model
29
+ print("DEBUG: smolagents components (CodeAgent, Tool, OpenAIServerModel, AgentMessage) imported successfully.")
30
  except ImportError as e: # Catch the specific error for better logging
31
  print(f"DEBUG: Failed to import smolagents. Error: {e}")
32
  logging.error(f"Failed to import smolagents. Please ensure it is installed and not corrupted. Error: {e}")
 
52
  def __init__(self, *args, **kwargs):
53
  print("DEBUG: Dummy OpenAIServerModel initialized because smolagents failed to import.")
54
  logging.error("Dummy OpenAIServerModel initialized because smolagents failed to import.")
55
+ async def generate_reply(self, messages, **kwargs): # Add dummy async method
56
+ print("DEBUG: Dummy OpenAIServerModel generate_reply called.")
57
+ # Return a dummy AgentMessage-like object
58
+ class DummyAgentMessage:
59
+ text = "Error: smolagents.OpenAIServerModel not loaded."
60
+ return DummyAgentMessage()
61
+
62
  pass
63
+
64
+ class AgentMessage: # Dummy for when smolagents fails to import
65
+ def __init__(self, role: str, text: str):
66
+ self.role = role
67
+ self.text = text
68
+ print(f"DEBUG: Dummy AgentMessage created for role {role}.")
69
+
70
 
71
  from datetime import datetime
72
  print("DEBUG: datetime imported")
 
107
  5. THOUGHT: Analyze the observation. Is it what you expected? Do you have enough information to answer the user's question now? If not, refine your search or decide on the next step.
108
  6. If you have the information, formulate the final answer according to the formatting rules.
109
 
110
+ CRITICAL FINAL ANSWER INSTRUCTIONS:
111
+ Your *entire response text*, after all thoughts and tool use, MUST CULMINATE in the final answer.
112
+ This final answer MUST be on its own new line and MUST start with the exact literal string "FINAL ANSWER: " (note the space after the colon).
113
+ Only the answer value itself should follow this "FINAL ANSWER: " prefix. Do NOT include any of your thought process, conversational text, or additional explanations *after* this "FINAL ANSWER: " prefix and its value. Your response effectively stops there.
 
114
 
115
+ Example of a full agent response structure (what you should output):
116
  THOUGHT: The user is asking for the capital of France. I should use web_search to find this.
117
  CODE:
118
  ```python
 
123
  THOUGHT: The search result clearly states that Paris is the capital of France. I have sufficient information. I will provide this as the final answer, following the formatting rules for a string.
124
  FINAL ANSWER: Paris
125
 
126
+ Another Example (for a question "what is the opposite of left?"):
127
  THOUGHT: The question asks for the opposite of the word "left". This is general knowledge and does not require a tool. The opposite of "left" is "right". I will provide this as the final answer.
128
  FINAL ANSWER: right
129
 
130
+ Formatting rules for the value that comes *after* "FINAL ANSWER: ":
131
  - If the question asks for a number: Provide only the number itself (e.g., `FINAL ANSWER: 42`). Do not use commas for thousands separation (e.g., use `FINAL ANSWER: 1234` not `FINAL ANSWER: 1,234`). Do not include units like '$' or '%' unless the question specifically asks for it and it's part of the answer.
132
  - If the question asks for a string: Provide the most concise string possible (e.g., `FINAL ANSWER: right`). Avoid articles (a, an, the) unless grammatically essential. Avoid common abbreviations (e.g., for cities like "NYC" for "New York City") unless the question implies it. Write out numerical digits as words (e.g., `FINAL ANSWER: two` instead of `FINAL ANSWER: 2`) unless numerical digits are requested.
133
  - If the question asks for a comma-separated list: Apply the above string/number rules to each element. Ensure elements are separated ONLY by a comma (e.g., `FINAL ANSWER: item one,item two,three`). NO space after the comma unless it's part of the item itself.
134
  - If the answer is a calculation result, provide just the number (e.g., `FINAL ANSWER: 10`).
135
 
136
+ Remember, the "FINAL ANSWER: " prefix is a literal string you must output as the very last part of your response, followed by the actual answer value. Do not confuse this with any internal `final_answer()` function you might use in your generated code; this is about the final textual output of your entire turn.
137
+ """
138
+
139
+ SUMMARIZER_SYSTEM_PROMPT = """You are an expert at extracting concise answers from text.
140
+ Given an original question and a detailed reasoning process that attempted to answer it, your task is to provide a very short, direct answer to the original question.
141
+ This concise answer MUST strictly adhere to the provided formatting rules.
142
+ Do NOT include "FINAL ANSWER:" or any other prefix in your response. Just output the value.
143
+ Do NOT explain your reasoning for the concise answer. Only provide the answer value.
144
+ If the reasoning provided does not contain a clear answer to the original question, output the phrase "Could not determine answer from reasoning."
145
  """
146
 
147
  CONFIG = AppConfig()
 
177
  # --- Tool Definitions ---
178
  print("DEBUG: Defining GoogleSearchTool.")
179
  class GoogleSearchTool(Tool):
180
+ name = "web_search"
181
  description = "Searches the web using Serper API for information. Input: a string search query. Output: formatted search results string."
182
  inputs = {
183
  "query": {"type": "string", "description": "The search query to execute."},
 
189
  }
190
  }
191
  output_type = "string"
192
+ is_async = True
193
 
194
  def __init__(self, session: aiohttp.ClientSession):
195
  super().__init__()
196
+ self._session = session
197
  print("DEBUG: GoogleSearchTool instance created.")
198
 
199
  async def forward(self, query: str, provider: str = "serpapi") -> str:
 
285
  super().__init__(**minimal_super_args)
286
  print("DEBUG: QuestionAnsweringAgent super().__init__ successful (workaround active).")
287
 
288
+ self.system_prompt = CONFIG.AGENT_SYSTEM_PROMPT # This is the main system prompt for the agent's reasoning
289
  print(f"DEBUG: QuestionAnsweringAgent explicitly set self.system_prompt.")
290
 
291
  if hasattr(self, 'verbosity_level'):
 
315
  exc_info=True
316
  )
317
  raise
318
+ except Exception as e:
319
  print(f"DEBUG: ERROR - QuestionAnsweringAgent Unexpected error during __init__ (possibly from tool validation): {type(e).__name__} - {e}")
320
  logger.error(f"Unexpected error during QuestionAnsweringAgent __init__: {e}", exc_info=True)
321
  raise
 
348
  final_answer_for_submission = match.group(1).strip()
349
  print(f"DEBUG: QuestionAnsweringAgent extracted FINAL ANSWER: '{final_answer_for_submission}'")
350
  else:
351
+ logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Attempting LLM summarization fallback.")
352
+ print("DEBUG: WARNING - QuestionAnsweringAgent could not find 'FINAL ANSWER:' in agent's response. Initiating LLM summarization fallback.")
353
+
354
+ # Fallback: Ask the LLM to summarize the full_agent_response into a concise answer
355
+ summarizer_messages = [
356
+ AgentMessage(role="system", text=CONFIG.SUMMARIZER_SYSTEM_PROMPT),
357
+ AgentMessage(role="user", text=f"Original Question: {question_text}\n\nAgent's Reasoning and Full Response:\n{full_agent_response}\n\nBased on the reasoning, provide a concise answer to the original question, strictly following the formatting rules mentioned in the system prompt for this summarization task. Your response should be ONLY the answer value.")
358
+ ]
359
+ print(f"DEBUG: Summarizer LLM call with messages: {summarizer_messages}")
360
+ try:
361
+ # Assuming self.model is the initialized OpenAIServerModel instance
362
+ # and it has an async generate_reply method
363
+ summary_response_obj = await self.model.generate_reply(messages=summarizer_messages)
364
+ if summary_response_obj and summary_response_obj.text:
365
+ final_answer_for_submission = summary_response_obj.text.strip()
366
+ print(f"DEBUG: LLM summarization fallback successful. Concise answer: '{final_answer_for_submission}'")
367
+ logger.info(f"LLM summarization fallback used. Extracted concise answer: '{final_answer_for_submission}'")
368
+ else:
369
+ print("DEBUG: ERROR - LLM summarization fallback returned empty or invalid response. Using full response as ultimate fallback.")
370
+ logger.error("LLM summarization fallback returned empty. Using full response as ultimate fallback.")
371
+ final_answer_for_submission = full_agent_response.strip() # Ultimate fallback
372
+ except Exception as e_summary:
373
+ print(f"DEBUG: ERROR - Exception during LLM summarization fallback: {type(e_summary).__name__} - {str(e_summary)}. Using full response as ultimate fallback.")
374
+ logger.error(f"Exception during LLM summarization fallback: {e_summary}. Using full response as ultimate fallback.", exc_info=True)
375
+ final_answer_for_submission = full_agent_response.strip() # Ultimate fallback
376
+
377
 
378
  if not final_answer_for_submission:
379
  logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
 
793
  print("\n" + "="*15 + " Application Shutdown " + "="*15)
794
  else:
795
  print("DEBUG: Script is being imported, not run as main.")
796
+