Lasdw commited on
Commit
080a6ff
·
1 Parent(s): 64d4d94

updated app.py display

Browse files
Files changed (2) hide show
  1. agent.py +153 -57
  2. app.py +5 -3
agent.py CHANGED
@@ -295,10 +295,79 @@ def assistant(state: AgentState) -> Dict[str, Any]:
295
  messages_for_llm = [system_msg] + llm_input_core_messages
296
 
297
  # Get response from the assistant
298
- response = chat_with_tools.invoke(messages_for_llm, stop=["Observation:"])
299
- print(f"Assistant response type: {type(response)}")
300
- content_preview = response.content[:300].replace('\n', ' ')
301
- print(f"Response content (first 300 chars): {content_preview}...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
302
 
303
  # Extract the action JSON from the response text
304
  action_json = extract_json_from_text(response.content)
@@ -580,67 +649,94 @@ def python_code_node(state: AgentState) -> Dict[str, Any]:
580
  """Node that executes Python code."""
581
  print("Python Code Tool Called...\n\n")
582
 
 
 
 
583
  # Extract tool arguments
584
  action_input = state.get("action_input", {})
585
  print(f"Python code action_input: {action_input}")
586
  print(f"Action input type: {type(action_input)}")
587
 
588
- # First try our specialized extraction function that handles nested structures
589
- code = extract_python_code_from_complex_input(action_input)
 
590
 
591
- # If extraction failed or returned the same complex structure, fallback to regex
592
- if code == action_input or (isinstance(code, str) and code.strip().startswith('{') and '"code"' in code):
593
- # Convert the action_input to string for regex processing if it's a dictionary
594
- if isinstance(action_input, dict):
595
- action_input_str = json.dumps(action_input)
596
- else:
597
- action_input_str = str(action_input)
598
-
599
- # First, attempt direct regex extraction which is most robust for nested structures
600
- import re
601
-
602
- # Try to extract code using regex patterns for different nesting levels
603
- # Pattern for deeply nested code
604
- deep_pattern = re.search(r'"code"\s*:\s*"(.*?)(?<!\\)"\s*}\s*}\s*}', action_input_str, re.DOTALL)
605
- if deep_pattern:
606
- extracted_code = deep_pattern.group(1)
607
- # Unescape the extracted code
608
- extracted_code = extracted_code.replace('\\n', '\n').replace('\\"', '"').replace("\\'", "'")
609
- code = extracted_code
610
- print(f"Extracted deeply nested code using regex: {repr(code[:100])}")
611
-
612
- # Pattern for single level nesting
613
- elif '"code"' in action_input_str:
614
- pattern = re.search(r'"code"\s*:\s*"(.*?)(?<!\\)"', action_input_str, re.DOTALL)
615
- if pattern:
616
- extracted_code = pattern.group(1)
617
- # Unescape the extracted code
618
- extracted_code = extracted_code.replace('\\n', '\n').replace('\\"', '"').replace("\\'", "'")
619
- code = extracted_code
620
- print(f"Extracted code using regex: {repr(code[:100])}")
621
-
622
- # If regex extraction failed, try dictionary approaches
623
- if code == action_input and isinstance(action_input, dict):
624
- # Direct code access
625
- if "code" in action_input:
626
- code = action_input["code"]
627
- print(f"Extracted code directly from dict: {repr(code[:100])}")
628
-
629
- # Nested JSON structure handling
630
- elif isinstance(action_input.get("code", ""), str) and action_input.get("code", "").strip().startswith('{'):
631
  try:
632
- nested_json = json.loads(action_input["code"])
633
- if "action_input" in nested_json and isinstance(nested_json["action_input"], dict) and "code" in nested_json["action_input"]:
634
- code = nested_json["action_input"]["code"]
635
- print(f"Extracted code from nested JSON: {repr(code[:100])}")
636
  except:
637
- # If parsing fails, use the code field as-is
638
- pass
639
-
640
- # If still no code, use the action_input directly (string case)
641
- if code == action_input and isinstance(action_input, str):
642
- code = action_input
643
- print(f"Using action_input as code: {repr(code[:100])}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
644
 
645
  print(f"Final code to execute: {repr(code[:100])}...")
646
 
 
295
  messages_for_llm = [system_msg] + llm_input_core_messages
296
 
297
  # Get response from the assistant
298
+ try:
299
+ response = chat_with_tools.invoke(messages_for_llm, stop=["Observation:"])
300
+ print(f"Assistant response type: {type(response)}")
301
+
302
+ # Check for empty response
303
+ if response is None or not hasattr(response, 'content') or not response.content or len(response.content.strip()) < 20:
304
+ print("Warning: Received empty or very short response from LLM")
305
+
306
+ # Create a new response object if it's None
307
+ if response is None:
308
+ from langchain_core.messages import AIMessage
309
+ response = AIMessage(content="")
310
+ print("Created new AIMessage object for None response")
311
+
312
+ # Check what kind of information we have in the last observation
313
+ last_observation = None
314
+ for msg in reversed(core_history):
315
+ if isinstance(msg, AIMessage) and "Observation:" in msg.content:
316
+ last_observation = msg.content
317
+ break
318
+
319
+ # Create an appropriate fallback response
320
+ if last_observation and "python_code" in state.get("current_tool", ""):
321
+ # If last tool was Python code, try to formulate a reasonable next step
322
+ print("Creating fallback response for empty response after Python code execution")
323
+ fallback_content = (
324
+ "Thought: I've analyzed the results of the code execution. Based on the observations, "
325
+ "I need to determine the final answer.\n\n"
326
+ "Final Answer: "
327
+ )
328
+
329
+ # Look for common patterns in Python output that might indicate results
330
+ import re
331
+ result_match = re.search(r'(\[.+?\]|\{.+?\}|[A-Za-z,\s]+)$', last_observation)
332
+ if result_match:
333
+ fallback_content += result_match.group(1).strip()
334
+ else:
335
+ # Generic fallback based on the executed code
336
+ fallback_content += "Based on the code analysis, but the exact result was unclear from the output."
337
+ else:
338
+ # Generic fallback suggesting a reasonable next search
339
+ print("Creating generic fallback response for empty LLM response")
340
+
341
+ # Make sure we have a valid query
342
+ query = ""
343
+ if full_current_history and hasattr(full_current_history[0], 'content'):
344
+ query = full_current_history[0].content[:100] # Limit to first 100 chars
345
+ else:
346
+ query = "additional information for this question"
347
+
348
+ fallback_content = (
349
+ "Thought: I need more information to answer this question correctly. Let me search for additional details.\n\n"
350
+ "Action: \n```json\n"
351
+ "{\n"
352
+ ' "action": "tavily_search",\n'
353
+ f' "action_input": {{"query": "{query}", "search_depth": "comprehensive"}}\n'
354
+ "}\n```"
355
+ )
356
+
357
+ # Use our fallback content instead of the empty response
358
+ response.content = fallback_content
359
+ print(f"Created fallback response: {fallback_content[:100]}...")
360
+ else:
361
+ content_preview = response.content[:300].replace('\n', ' ')
362
+ print(f"Response content (first 300 chars): {content_preview}...")
363
+ except Exception as e:
364
+ print(f"Error in LLM invocation: {str(e)}")
365
+ # Create a fallback response in case of LLM errors
366
+ from langchain_core.messages import AIMessage
367
+ response = AIMessage(content=(
368
+ "Thought: I encountered an error in processing. Let me try to proceed with what I know.\n\n"
369
+ "Final Answer: Unable to complete the task due to an error in processing."
370
+ ))
371
 
372
  # Extract the action JSON from the response text
373
  action_json = extract_json_from_text(response.content)
 
649
  """Node that executes Python code."""
650
  print("Python Code Tool Called...\n\n")
651
 
652
+ # Ensure AIMessage is available in this scope
653
+ from langchain_core.messages import AIMessage
654
+
655
  # Extract tool arguments
656
  action_input = state.get("action_input", {})
657
  print(f"Python code action_input: {action_input}")
658
  print(f"Action input type: {type(action_input)}")
659
 
660
+ # Extract code using specialized functions
661
+ # First try the extract_python_code_from_complex_input function from tools
662
+ from tools import extract_python_code_from_complex_input
663
 
664
+ # Debugging: Print full action_input for analysis
665
+ if isinstance(action_input, dict) and "code" in action_input:
666
+ print(f"Original code field (first 100 chars): {repr(action_input['code'][:100])}")
667
+ elif isinstance(action_input, str):
668
+ print(f"Original string input (first 100 chars): {repr(action_input[:100])}")
669
+
670
+ # Try to detect and fix double nesting issues
671
+ if isinstance(action_input, dict) and "code" in action_input:
672
+ code_value = action_input["code"]
673
+ if isinstance(code_value, str) and code_value.strip().startswith('{') and '"action"' in code_value:
674
+ print("Detected doubly nested JSON structure - attempting to fix")
675
+ try:
676
+ import json
677
+ import re
678
+
679
+ # First try to fix common escape issues that might cause JSON decode errors
680
+ # Replace escaped single quotes with temporary placeholders
681
+ fixed_code = code_value.replace("\\'", "___SQUOTE___")
682
+ # Replace escaped double quotes with proper JSON escapes
683
+ fixed_code = fixed_code.replace('\\"', '\\\\"')
684
+ # Fix newlines
685
+ fixed_code = fixed_code.replace('\\n', '\\\\n')
686
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
687
  try:
688
+ # Try to parse the fixed JSON
689
+ nested_json = json.loads(fixed_code)
 
 
690
  except:
691
+ # If that fails, try a more aggressive approach with regex
692
+ print("JSON parsing failed, trying regex approach")
693
+ action_match = re.search(r'"action"\s*:\s*"([^"]+)"', code_value)
694
+ code_match = re.search(r'"code"\s*:\s*"((?:[^"\\]|\\.)*)"', code_value)
695
+
696
+ if action_match and code_match and action_match.group(1) == "python_code":
697
+ # Extract the inner code and unescape it
698
+ extracted_code = code_match.group(1)
699
+ extracted_code = extracted_code.replace('\\n', '\n').replace('\\"', '"').replace("\\'", "'")
700
+ print(f"Extracted Python code using regex: {extracted_code[:100]}")
701
+ # Get run_python_code from tools
702
+ return {
703
+ "messages": state["messages"] + [AIMessage(content=f"Observation: {run_python_code(extracted_code)}")],
704
+ "current_tool": None,
705
+ "action_input": None
706
+ }
707
+
708
+ if isinstance(nested_json, dict) and "action" in nested_json and nested_json["action"] == "python_code":
709
+ if "action_input" in nested_json and isinstance(nested_json["action_input"], dict) and "code" in nested_json["action_input"]:
710
+ # We have a doubly nested structure - extract the innermost code
711
+ actual_code = nested_json["action_input"]["code"]
712
+ # Replace our placeholders back
713
+ if isinstance(actual_code, str):
714
+ actual_code = actual_code.replace("___SQUOTE___", "'")
715
+ print(f"Successfully extracted code from doubly nested structure. First 100 chars: {repr(actual_code[:100])}")
716
+ code = actual_code
717
+ else:
718
+ code = code_value
719
+ else:
720
+ code = code_value
721
+ except Exception as e:
722
+ print(f"Error attempting to fix nested structure: {e}")
723
+ # Fall back to direct regex extraction
724
+ import re
725
+ code_match = re.search(r'code":\s*"((?:[^"\\]|\\.)*)(?<!\\)"', code_value)
726
+ if code_match:
727
+ extracted_code = code_match.group(1)
728
+ # Unescape the extracted code
729
+ extracted_code = extracted_code.replace('\\n', '\n').replace('\\"', '"').replace("\\'", "'")
730
+ code = extracted_code
731
+ print(f"Extracted code using fallback regex: {repr(code[:100])}")
732
+ else:
733
+ # If all parsing fails, try to use extract_python_code_from_complex_input
734
+ from tools import extract_python_code_from_complex_input
735
+ code = extract_python_code_from_complex_input(action_input)
736
+ else:
737
+ code = extract_python_code_from_complex_input(action_input)
738
+ else:
739
+ code = extract_python_code_from_complex_input(action_input)
740
 
741
  print(f"Final code to execute: {repr(code[:100])}...")
742
 
app.py CHANGED
@@ -66,13 +66,15 @@ def chat_with_agent(question: str, file_uploads, history: list) -> tuple:
66
  else:
67
  response = agent(question)
68
 
69
- # Add question and response to history
70
- history.append([question, response])
 
71
 
72
  return history, ""
73
  except Exception as e:
74
  error_message = f"Error: {str(e)}"
75
- history.append([question, error_message])
 
76
  return history, ""
77
 
78
  def clear_chat():
 
66
  else:
67
  response = agent(question)
68
 
69
+ # Add question and response to history in the correct format
70
+ history.append({"role": "user", "content": question})
71
+ history.append({"role": "assistant", "content": response})
72
 
73
  return history, ""
74
  except Exception as e:
75
  error_message = f"Error: {str(e)}"
76
+ history.append({"role": "user", "content": question})
77
+ history.append({"role": "assistant", "content": error_message})
78
  return history, ""
79
 
80
  def clear_chat():