gabejavitt commited on
Commit
2541381
Β·
verified Β·
1 Parent(s): a12ca6e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -0
app.py CHANGED
@@ -1215,6 +1215,102 @@ Turn 7: final_answer_tool("1.796 trillion")
1215
  print("βœ… Planning & Reflection Agent graph compiled successfully.")
1216
 
1217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1218
  # =============================================================================
1219
  # GLOBAL AGENT INSTANTIATION
1220
  # =============================================================================
 
1215
  print("βœ… Planning & Reflection Agent graph compiled successfully.")
1216
 
1217
 
1218
+ def __call__(self, question: str) -> str:
1219
+ print(f"\n{'='*70}")
1220
+ print(f"🎯 NEW QUESTION")
1221
+ print(f"{'='*70}")
1222
+ print(f"Q: {question[:200]}{'...' if len(question) > 200 else ''}")
1223
+ print(f"{'='*70}\n")
1224
+
1225
+ graph_input = {
1226
+ "messages": [
1227
+ SystemMessage(content=self.system_prompt),
1228
+ HumanMessage(content=question)
1229
+ ],
1230
+ "turn": 0,
1231
+ "has_plan": False,
1232
+ "consecutive_errors": 0,
1233
+ "tool_history": []
1234
+ }
1235
+
1236
+ final_answer = "AGENT FAILED TO PRODUCE ANSWER"
1237
+ try:
1238
+ config = {"recursion_limit": MAX_TURNS + 10}
1239
+ for event in self.graph.stream(graph_input, stream_mode="values", config=config):
1240
+
1241
+ if not event.get('messages'):
1242
+ continue
1243
+
1244
+ last_message = event["messages"][-1]
1245
+
1246
+ # Check for final answer extraction
1247
+ if isinstance(last_message, AIMessage) and last_message.tool_calls:
1248
+ if last_message.tool_calls[0].get("name") == "final_answer_tool":
1249
+ final_answer_args = last_message.tool_calls[0].get('args', {})
1250
+ if 'answer' in final_answer_args:
1251
+ final_answer = final_answer_args['answer']
1252
+ print(f"\n{'='*70}")
1253
+ print(f"βœ… FINAL ANSWER CAPTURED: '{final_answer}'")
1254
+ print(f"{'='*70}\n")
1255
+ break
1256
+ else:
1257
+ print(f"⚠️ final_answer_tool called without 'answer' argument")
1258
+ final_answer = "ERROR: FINAL_ANSWER_TOOL CALLED WITHOUT ANSWER"
1259
+ break
1260
+
1261
+ elif isinstance(last_message, ToolMessage):
1262
+ result_preview = last_message.content[:300].replace('\n', ' ')
1263
+ print(f"πŸ“Š Tool Result: {result_preview}...")
1264
+ elif isinstance(last_message, AIMessage) and not last_message.tool_calls:
1265
+ print(f"πŸ’­ AI Reasoning: {last_message.content[:300]}...")
1266
+
1267
+ # Final Answer Cleaning
1268
+ cleaned_answer = str(final_answer).strip()
1269
+
1270
+ # Remove common prefixes
1271
+ prefixes_to_remove = [
1272
+ "The answer is:", "Here is the answer:", "Based on the information:",
1273
+ "Final Answer:", "Answer:", "The final answer is:", "My answer is:",
1274
+ "According to", "I found that", "The result is:"
1275
+ ]
1276
+ for prefix in prefixes_to_remove:
1277
+ if cleaned_answer.lower().startswith(prefix.lower()):
1278
+ potential_answer = cleaned_answer[len(prefix):].strip()
1279
+ if potential_answer:
1280
+ cleaned_answer = potential_answer
1281
+ break
1282
+
1283
+ # Remove code fences
1284
+ cleaned_answer = remove_fences_simple(cleaned_answer)
1285
+
1286
+ # Remove surrounding backticks
1287
+ while cleaned_answer.startswith("`") and cleaned_answer.endswith("`"):
1288
+ cleaned_answer = cleaned_answer[1:-1].strip()
1289
+
1290
+ # Remove quotes if they wrap the entire answer
1291
+ if (cleaned_answer.startswith('"') and cleaned_answer.endswith('"')) or \
1292
+ (cleaned_answer.startswith("'") and cleaned_answer.endswith("'")):
1293
+ cleaned_answer = cleaned_answer[1:-1].strip()
1294
+
1295
+ # Remove trailing periods for non-sentence answers
1296
+ if cleaned_answer.endswith('.') and len(cleaned_answer.split()) < 10:
1297
+ cleaned_answer = cleaned_answer[:-1]
1298
+
1299
+ print(f"\n{'='*70}")
1300
+ print(f"πŸŽ‰ FINAL CLEANED ANSWER")
1301
+ print(f"{'='*70}")
1302
+ print(f"{cleaned_answer}")
1303
+ print(f"{'='*70}\n")
1304
+
1305
+ return cleaned_answer
1306
+
1307
+ except Exception as e:
1308
+ print(f"❌ Error running agent graph: {e}")
1309
+ tb_str = traceback.format_exc()
1310
+ print(tb_str)
1311
+ return f"AGENT GRAPH ERROR: {e}"
1312
+
1313
+
1314
  # =============================================================================
1315
  # GLOBAL AGENT INSTANTIATION
1316
  # =============================================================================