Lasdw commited on
Commit
97d9a2e
·
1 Parent(s): 4a325e1

Fixed python code action detection

Browse files
Files changed (1) hide show
  1. agent.py +36 -29
agent.py CHANGED
@@ -703,37 +703,19 @@ supabase_operation: Perform database operations, args: {"operation_type": {"type
703
 
704
  IMPORTANT: Make sure your JSON is properly formatted with double quotes around keys and string values.
705
 
706
- Example use for Supabase:
707
 
708
- Insert data:
709
  ```json
710
  {
711
- "action": "supabase_operation",
712
- "action_input": {"operation_type": "insert", "table": "users", "data": {"name": "John Doe", "email": "john@example.com"}}
713
  }
714
  ```
715
-
716
- Select data:
717
- ```json
718
- {
719
- "action": "supabase_operation",
720
- "action_input": {"operation_type": "select", "table": "users", "filters": {"id": 1}}
721
- }
722
- ```
723
-
724
- Update data:
725
- ```json
726
- {
727
- "action": "supabase_operation",
728
- "action_input": {"operation_type": "update", "table": "users", "data": {"name": "Jane Doe"}, "filters": {"id": 1}}
729
- }
730
- ```
731
-
732
- Delete data:
733
  ```json
734
  {
735
- "action": "supabase_operation",
736
- "action_input": {"operation_type": "delete", "table": "users", "filters": {"id": 1}}
737
  }
738
  ```
739
 
@@ -919,7 +901,7 @@ def assistant(state: AgentState) -> Dict[str, Any]:
919
  # print(f"Messages for LLM (count: {len(messages_for_llm)}):")
920
  # for i, msg in enumerate(messages_for_llm):
921
  # print(f" {i}: Type={type(msg).__name__}, Content='{str(msg.content)[:100].replace('\\n', ' ')}...'")
922
-
923
  # Get response from the assistant
924
  response = chat_with_tools.invoke(messages_for_llm, stop=["Observation:"])
925
  print(f"Assistant response type: {type(response)}")
@@ -959,8 +941,29 @@ def assistant(state: AgentState) -> Dict[str, Any]:
959
  def extract_json_from_text(text: str) -> dict:
960
  """Extract JSON from text, handling markdown code blocks."""
961
  try:
 
 
962
  print(f"Attempting to extract JSON from text: {text[:200]}...")
963
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
964
  # Look for markdown code blocks - the most common pattern
965
  if "```" in text:
966
  print("Found markdown code block")
@@ -980,7 +983,7 @@ def extract_json_from_text(text: str) -> dict:
980
  if i < len(lines):
981
  # Found the end
982
  block_content = '\n'.join(lines[start_idx:i])
983
- blocks.append(block_content)
984
  i += 1
985
 
986
  # Try to parse each block as JSON
@@ -1002,7 +1005,7 @@ def extract_json_from_text(text: str) -> dict:
1002
 
1003
  # Look for JSON-like patterns in the text using a more precise regex
1004
  # Match balanced braces
1005
- import re
1006
 
1007
  # Try to find JSON objects with proper brace matching
1008
  brace_count = 0
@@ -1468,7 +1471,7 @@ class TurboNerd:
1468
  self.graph = create_agent_graph()
1469
  self.tools = tools_config
1470
  self.max_iterations = max_iterations # Maximum iterations for the graph
1471
-
1472
  # Set Apify API token if provided
1473
  if apify_api_token:
1474
  os.environ["APIFY_API_TOKEN"] = apify_api_token
@@ -1513,7 +1516,11 @@ class TurboNerd:
1513
  # Example usage:
1514
  if __name__ == "__main__":
1515
  agent = TurboNerd(max_iterations=25)
1516
- response = agent("""On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?""")
 
 
 
 
1517
  print("\nFinal Response:")
1518
  print(response)
1519
 
 
703
 
704
  IMPORTANT: Make sure your JSON is properly formatted with double quotes around keys and string values.
705
 
706
+ Example use for tools:
707
 
 
708
  ```json
709
  {
710
+ "action": "tavily_search",
711
+ "action_input": {"query": "What is the capital of France?", "search_depth": "basic"}
712
  }
713
  ```
714
+ or
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
715
  ```json
716
  {
717
+ "action": "python_code",
718
+ "action_input": {"code": "c = a + b"}
719
  }
720
  ```
721
 
 
901
  # print(f"Messages for LLM (count: {len(messages_for_llm)}):")
902
  # for i, msg in enumerate(messages_for_llm):
903
  # print(f" {i}: Type={type(msg).__name__}, Content='{str(msg.content)[:100].replace('\\n', ' ')}...'")
904
+
905
  # Get response from the assistant
906
  response = chat_with_tools.invoke(messages_for_llm, stop=["Observation:"])
907
  print(f"Assistant response type: {type(response)}")
 
941
  def extract_json_from_text(text: str) -> dict:
942
  """Extract JSON from text, handling markdown code blocks."""
943
  try:
944
+ import re # Import re at the beginning of the function
945
+
946
  print(f"Attempting to extract JSON from text: {text[:200]}...")
947
 
948
+ # Look for "Action:" followed by a markdown code block - common LLM output pattern
949
+ # This handles cases where the LLM outputs something like:
950
+ # Action:
951
+ # ```python
952
+ # code here
953
+ # ```
954
+ action_match = re.search(r"Action:\s*```(?:python|json)?\s*(.*?)```", text, re.DOTALL)
955
+ if action_match:
956
+ action_content = action_match.group(1).strip()
957
+ print(f"Found action content from markdown block: {action_content[:100]}...")
958
+
959
+ # If it looks like Python code, try to create a proper JSON structure
960
+ if "=" in action_content or "import" in action_content or "print" in action_content:
961
+ print("Detected Python code, formatting as action_input")
962
+ return {
963
+ "action": "python_code",
964
+ "action_input": {"code": action_content}
965
+ }
966
+
967
  # Look for markdown code blocks - the most common pattern
968
  if "```" in text:
969
  print("Found markdown code block")
 
983
  if i < len(lines):
984
  # Found the end
985
  block_content = '\n'.join(lines[start_idx:i])
986
+ blocks.append(block_content)
987
  i += 1
988
 
989
  # Try to parse each block as JSON
 
1005
 
1006
  # Look for JSON-like patterns in the text using a more precise regex
1007
  # Match balanced braces
1008
+ # No need to import re again here
1009
 
1010
  # Try to find JSON objects with proper brace matching
1011
  brace_count = 0
 
1471
  self.graph = create_agent_graph()
1472
  self.tools = tools_config
1473
  self.max_iterations = max_iterations # Maximum iterations for the graph
1474
+
1475
  # Set Apify API token if provided
1476
  if apify_api_token:
1477
  os.environ["APIFY_API_TOKEN"] = apify_api_token
 
1516
  # Example usage:
1517
  if __name__ == "__main__":
1518
  agent = TurboNerd(max_iterations=25)
1519
+ response = agent("""I'm making a grocery list for my mom, but she's a professor of botany and she's a real stickler when it comes to categorizing things. I need to add different foods to different categories on the grocery list, but if I make a mistake, she won't buy anything inserted in the wrong category. Here's the list I have so far:
1520
+
1521
+ milk, eggs, flour, whole bean coffee, Oreos, sweet potatoes, fresh basil, plums, green beans, rice, corn, bell pepper, whole allspice, acorns, broccoli, celery, zucchini, lettuce, peanuts
1522
+
1523
+ I need to make headings for the fruits and vegetables. Could you please create a list of just the vegetables from my list? If you could do that, then I can figure out how to categorize the rest of the list into the appropriate categories. But remember that my mom is a real stickler, so make sure that no botanical fruits end up on the vegetable list, or she won't get them when she's at the store. Please alphabetize the list of vegetables, and place each item in a comma separated list.""")
1524
  print("\nFinal Response:")
1525
  print(response)
1526