Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1072,117 +1072,87 @@ Turn 7: final_answer_tool("1.796 trillion")
|
|
| 1072 |
self.graph = graph_builder.compile()
|
| 1073 |
print("β
Planning & Reflection Agent graph compiled successfully.")
|
| 1074 |
|
|
|
|
|
|
|
| 1075 |
def __call__(self, question: str) -> str:
|
| 1076 |
-
print(f"\n
|
| 1077 |
-
print(f"
|
| 1078 |
-
print(f"{'='*70}")
|
| 1079 |
-
print(f"Q: {question[:200]}{'...' if len(question) > 200 else ''}")
|
| 1080 |
-
print(f"{'='*70}\n")
|
| 1081 |
|
| 1082 |
graph_input = {
|
| 1083 |
"messages": [
|
| 1084 |
SystemMessage(content=self.system_prompt),
|
| 1085 |
HumanMessage(content=question)
|
| 1086 |
],
|
| 1087 |
-
"turn": 0
|
| 1088 |
-
"has_plan": False,
|
| 1089 |
-
"consecutive_errors": 0,
|
| 1090 |
-
"tool_history": []
|
| 1091 |
}
|
| 1092 |
|
| 1093 |
final_answer = "AGENT FAILED TO PRODUCE ANSWER"
|
| 1094 |
try:
|
| 1095 |
-
config = {"recursion_limit": MAX_TURNS +
|
| 1096 |
for event in self.graph.stream(graph_input, stream_mode="values", config=config):
|
| 1097 |
|
| 1098 |
-
if
|
| 1099 |
-
|
| 1100 |
-
|
| 1101 |
-
|
| 1102 |
|
| 1103 |
# Check for final answer extraction
|
| 1104 |
if isinstance(last_message, AIMessage) and last_message.tool_calls:
|
| 1105 |
if last_message.tool_calls[0].get("name") == "final_answer_tool":
|
| 1106 |
final_answer_args = last_message.tool_calls[0].get('args', {})
|
| 1107 |
if 'answer' in final_answer_args:
|
| 1108 |
-
|
| 1109 |
-
|
| 1110 |
-
|
| 1111 |
-
print(f"{'='*70}\n")
|
| 1112 |
-
break
|
| 1113 |
else:
|
| 1114 |
-
|
| 1115 |
-
|
| 1116 |
-
|
| 1117 |
|
| 1118 |
elif isinstance(last_message, ToolMessage):
|
| 1119 |
-
|
| 1120 |
-
print(f"π Tool Result: {result_preview}...")
|
| 1121 |
elif isinstance(last_message, AIMessage) and not last_message.tool_calls:
|
| 1122 |
-
print(f"
|
|
|
|
|
|
|
|
|
|
| 1123 |
|
| 1124 |
-
# Final Answer Cleaning
|
| 1125 |
cleaned_answer = str(final_answer).strip()
|
| 1126 |
-
|
| 1127 |
-
|
| 1128 |
-
prefixes_to_remove = [
|
| 1129 |
-
"The answer is:", "Here is the answer:", "Based on the information:",
|
| 1130 |
-
"Final Answer:", "Answer:", "The final answer is:", "My answer is:",
|
| 1131 |
-
"According to", "I found that", "The result is:"
|
| 1132 |
-
]
|
| 1133 |
for prefix in prefixes_to_remove:
|
| 1134 |
if cleaned_answer.lower().startswith(prefix.lower()):
|
| 1135 |
potential_answer = cleaned_answer[len(prefix):].strip()
|
| 1136 |
-
if potential_answer:
|
| 1137 |
cleaned_answer = potential_answer
|
| 1138 |
-
break
|
| 1139 |
|
| 1140 |
-
# Remove code fences
|
| 1141 |
cleaned_answer = remove_fences_simple(cleaned_answer)
|
| 1142 |
-
|
| 1143 |
-
|
| 1144 |
-
|
| 1145 |
-
|
| 1146 |
-
|
| 1147 |
-
# Remove quotes if they wrap the entire answer
|
| 1148 |
-
if (cleaned_answer.startswith('"') and cleaned_answer.endswith('"')) or \
|
| 1149 |
-
(cleaned_answer.startswith("'") and cleaned_answer.endswith("'")):
|
| 1150 |
-
cleaned_answer = cleaned_answer[1:-1].strip()
|
| 1151 |
-
|
| 1152 |
-
# Remove trailing periods for non-sentence answers
|
| 1153 |
-
if cleaned_answer.endswith('.') and len(cleaned_answer.split()) < 10:
|
| 1154 |
-
cleaned_answer = cleaned_answer[:-1]
|
| 1155 |
-
|
| 1156 |
-
print(f"\n{'='*70}")
|
| 1157 |
-
print(f"π FINAL CLEANED ANSWER")
|
| 1158 |
-
print(f"{'='*70}")
|
| 1159 |
-
print(f"{cleaned_answer}")
|
| 1160 |
-
print(f"{'='*70}\n")
|
| 1161 |
-
|
| 1162 |
return cleaned_answer
|
| 1163 |
|
| 1164 |
except Exception as e:
|
| 1165 |
-
print(f"
|
| 1166 |
tb_str = traceback.format_exc()
|
| 1167 |
print(tb_str)
|
| 1168 |
return f"AGENT GRAPH ERROR: {e}"
|
| 1169 |
|
| 1170 |
|
| 1171 |
-
#
|
| 1172 |
-
#
|
| 1173 |
-
|
| 1174 |
try:
|
| 1175 |
-
|
| 1176 |
-
|
| 1177 |
-
|
| 1178 |
-
print("β
Global PlanningReflectionAgent instantiated successfully.")
|
| 1179 |
-
if asr_pipeline is None:
|
| 1180 |
-
print("β οΈ Global ASR Pipeline failed to load.")
|
| 1181 |
except Exception as e:
|
| 1182 |
print(f"β FATAL: Could not instantiate global agent: {e}")
|
| 1183 |
traceback.print_exc()
|
| 1184 |
agent = None
|
| 1185 |
-
|
| 1186 |
|
| 1187 |
# ====================================================
|
| 1188 |
# --- (Original Template Code - Mock Questions Version) ---
|
|
@@ -1358,5 +1328,4 @@ if __name__ == "__main__":
|
|
| 1358 |
except FileNotFoundError: print("Warning: CWD listing failed.")
|
| 1359 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 1360 |
print("Launching Gradio Interface...")
|
| 1361 |
-
demo.queue().launch(debug=True, share=False)
|
| 1362 |
-
|
|
|
|
| 1072 |
self.graph = graph_builder.compile()
|
| 1073 |
print("β
Planning & Reflection Agent graph compiled successfully.")
|
| 1074 |
|
| 1075 |
+
|
| 1076 |
+
|
| 1077 |
def __call__(self, question: str) -> str:
|
| 1078 |
+
print(f"\n--- Starting Agent Run for Question ---")
|
| 1079 |
+
print(f"Agent received question (first 100 chars): {question[:100]}...")
|
|
|
|
|
|
|
|
|
|
| 1080 |
|
| 1081 |
graph_input = {
|
| 1082 |
"messages": [
|
| 1083 |
SystemMessage(content=self.system_prompt),
|
| 1084 |
HumanMessage(content=question)
|
| 1085 |
],
|
| 1086 |
+
"turn": 0
|
|
|
|
|
|
|
|
|
|
| 1087 |
}
|
| 1088 |
|
| 1089 |
final_answer = "AGENT FAILED TO PRODUCE ANSWER"
|
| 1090 |
try:
|
| 1091 |
+
config = {"recursion_limit": MAX_TURNS + 5}
|
| 1092 |
for event in self.graph.stream(graph_input, stream_mode="values", config=config):
|
| 1093 |
|
| 1094 |
+
if event.get('messages'): # Ensure messages exist
|
| 1095 |
+
last_message = event["messages"][-1]
|
| 1096 |
+
else:
|
| 1097 |
+
continue # Skip if no messages yet
|
| 1098 |
|
| 1099 |
# Check for final answer extraction
|
| 1100 |
if isinstance(last_message, AIMessage) and last_message.tool_calls:
|
| 1101 |
if last_message.tool_calls[0].get("name") == "final_answer_tool":
|
| 1102 |
final_answer_args = last_message.tool_calls[0].get('args', {})
|
| 1103 |
if 'answer' in final_answer_args:
|
| 1104 |
+
final_answer = final_answer_args['answer']
|
| 1105 |
+
print(f"--- Final Answer Captured from tool call: '{final_answer}' ---")
|
| 1106 |
+
break
|
|
|
|
|
|
|
| 1107 |
else:
|
| 1108 |
+
print(f"β οΈ Final Answer tool called without 'answer' argument: {final_answer_args}")
|
| 1109 |
+
final_answer = "ERROR: FINAL_ANSWER_TOOL CALLED WITHOUT ANSWER"
|
| 1110 |
+
break
|
| 1111 |
|
| 1112 |
elif isinstance(last_message, ToolMessage):
|
| 1113 |
+
print(f"Tool Result ({last_message.tool_call_id}): {last_message.content[:500]}...")
|
|
|
|
| 1114 |
elif isinstance(last_message, AIMessage) and not last_message.tool_calls:
|
| 1115 |
+
print(f"AI Message (Reasoning): {last_message.content[:500]}...")
|
| 1116 |
+
elif isinstance(last_message, SystemMessage):
|
| 1117 |
+
print(f"System Message: {last_message.content[:500]}...")
|
| 1118 |
+
|
| 1119 |
|
| 1120 |
+
# --- Final Answer Cleaning ---
|
| 1121 |
cleaned_answer = str(final_answer).strip()
|
| 1122 |
+
prefixes_to_remove = ["The answer is:", "Here is the answer:", "Based on the information:", "Final Answer:", "Answer:"]
|
| 1123 |
+
original_cleaned = cleaned_answer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1124 |
for prefix in prefixes_to_remove:
|
| 1125 |
if cleaned_answer.lower().startswith(prefix.lower()):
|
| 1126 |
potential_answer = cleaned_answer[len(prefix):].strip()
|
| 1127 |
+
if potential_answer:
|
| 1128 |
cleaned_answer = potential_answer
|
| 1129 |
+
break
|
| 1130 |
|
|
|
|
| 1131 |
cleaned_answer = remove_fences_simple(cleaned_answer)
|
| 1132 |
+
if cleaned_answer.startswith("`") and cleaned_answer.endswith("`"):
|
| 1133 |
+
cleaned_answer = cleaned_answer[1:-1].strip()
|
| 1134 |
+
|
| 1135 |
+
print(f"Agent returning final answer (cleaned): '{cleaned_answer}'")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1136 |
return cleaned_answer
|
| 1137 |
|
| 1138 |
except Exception as e:
|
| 1139 |
+
print(f"Error running agent graph: {e}")
|
| 1140 |
tb_str = traceback.format_exc()
|
| 1141 |
print(tb_str)
|
| 1142 |
return f"AGENT GRAPH ERROR: {e}"
|
| 1143 |
|
| 1144 |
|
| 1145 |
+
# ====================================================
|
| 1146 |
+
# --- Global Agent Instantiation ---
|
| 1147 |
+
|
| 1148 |
try:
|
| 1149 |
+
agent = BasicAgent()
|
| 1150 |
+
print("β
Global BasicAgent instantiated successfully.")
|
| 1151 |
+
if asr_pipeline is None: print("β οΈ Global ASR Pipeline failed load.")
|
|
|
|
|
|
|
|
|
|
| 1152 |
except Exception as e:
|
| 1153 |
print(f"β FATAL: Could not instantiate global agent: {e}")
|
| 1154 |
traceback.print_exc()
|
| 1155 |
agent = None
|
|
|
|
| 1156 |
|
| 1157 |
# ====================================================
|
| 1158 |
# --- (Original Template Code - Mock Questions Version) ---
|
|
|
|
| 1328 |
except FileNotFoundError: print("Warning: CWD listing failed.")
|
| 1329 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 1330 |
print("Launching Gradio Interface...")
|
| 1331 |
+
demo.queue().launch(debug=True, share=False)
|
|
|