gabejavitt commited on
Commit
0e12b45
Β·
verified Β·
1 Parent(s): c754ac5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -81
app.py CHANGED
@@ -769,93 +769,93 @@ Your goal: Provide the EXACT answer in the EXACT format requested.
769
  **REMEMBER:** One step at a time. Use tools. Format JSON correctly.
770
  """
771
 
772
- # --- *** UPDATED: Initialize Google Gemini LLM *** ---
773
- print("Initializing Google Gemini LLM...")
774
- try:
775
- # --- Initialize ONE Powerful LLM for all tasks ---
776
- self.planner_llm = ChatGoogleGenerativeAI(
777
- model="gemini-2.0-flash-exp", # ← Same model, different config
778
- google_api_key=GEMINI_API_KEY,
779
- temperature=0,
780
- convert_system_message_to_human=True,
781
- max_output_tokens=1024 # Planner needs less tokens
782
- )
783
- print("βœ… Planner LLM (Gemini 2.0 Flash) initialized.")
784
 
785
- except Exception as e:
786
- print(f"❌ Error initializing Gemini: {e}")
787
- raise
788
- # --- *** END UPDATE *** ---
 
 
 
 
 
 
 
789
 
790
- # --- Node 1: The Agent ---
791
- def agent_node(state: AgentState):
792
- current_turn = state.get('turn', 0) + 1
793
- print(f"\n{'='*60}")
794
- print(f"AGENT TURN {current_turn}/{MAX_TURNS}")
795
- print('='*60)
796
-
797
- # Note: Max turns is also checked in should_continue, but good to have here
798
- if current_turn > MAX_TURNS:
799
- return {"messages": [SystemMessage(content="Max turns reached.")]}
800
 
801
- max_retries = 3
802
- ai_message = None
803
- for attempt in range(max_retries):
804
- try:
805
- # Call the single, powerful LLM
806
- ai_message = self.llm_with_tools.invoke(state["messages"])
807
- break
808
- except Exception as e:
809
- print(f"⚠️ LLM attempt {attempt+1}/{max_retries} failed: {e}")
810
- if attempt == max_retries - 1:
811
- ai_message = AIMessage(
812
- content=f"Error: LLM failed after {max_retries} attempts: {e}"
813
- )
814
- time.sleep(2 ** attempt)
815
-
816
- # --- Fallback Parsing Logic ---
817
- if not ai_message.tool_calls and isinstance(ai_message.content, str) and ai_message.content.strip():
818
- parsed_tool_calls = parse_tool_call_from_string(ai_message.content, self.tools)
819
- if parsed_tool_calls:
820
- print("πŸ”§ Fallback SUCCESS: Rebuilding tool call(s).")
821
- ai_message.tool_calls = parsed_tool_calls
822
- ai_message.content = "" # Clear the text content
823
- else:
824
- print(f"⚠️ Fallback FAILED: Could not parse any tool call from content:\n{ai_message.content[:200]}...")
825
-
826
- if ai_message.tool_calls:
827
- print(f"πŸ”§ Agent Tool Call: {ai_message.tool_calls[0]['name']}")
828
- else:
829
- print(f"πŸ’­ Agent Reasoning: {ai_message.content[:200]}...")
830
-
831
- return {"messages": [ai_message], "turn": current_turn}
832
-
833
- # --- Tool Node ---
834
- tool_node = ToolNode(self.tools)
835
-
836
- # --- Build Graph ---
837
- print("Building Single-Agent graph...")
838
- graph_builder = StateGraph(AgentState)
839
-
840
- graph_builder.add_node("agent", agent_node)
841
- graph_builder.add_node("tools", tool_node)
842
-
843
- graph_builder.add_edge(START, "agent")
844
 
845
- graph_builder.add_conditional_edges(
846
- "agent",
847
- should_continue, # Use the reverted conditional function
848
- {
849
- "tools": "tools",
850
- "agent": "agent", # For loop prevention
851
- END: END
852
- }
853
- )
854
 
855
- graph_builder.add_edge("tools", "agent") # Loop back to agent
 
 
 
856
 
857
- self.graph = graph_builder.compile()
858
- print("βœ… Single-Agent graph compiled successfully.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
859
 
860
  def __call__(self, question: str) -> str:
861
  print(f"\n--- Starting Agent Run for Question ---")
 
769
  **REMEMBER:** One step at a time. Use tools. Format JSON correctly.
770
  """
771
 
772
+ # --- *** UPDATED: Initialize Google Gemini LLM *** ---
773
+ print("Initializing Google Gemini LLM...")
774
+ try:
775
+ # --- Initialize ONE Powerful LLM for all tasks ---
776
+ self.planner_llm = ChatGoogleGenerativeAI(
777
+ model="gemini-2.0-flash-exp", # ← Same model, different config
778
+ google_api_key=GEMINI_API_KEY,
779
+ temperature=0,
780
+ convert_system_message_to_human=True,
781
+ max_output_tokens=1024 # Planner needs less tokens
782
+ )
783
+ print("βœ… Planner LLM (Gemini 2.0 Flash) initialized.")
784
 
785
+ except Exception as e:
786
+ print(f"❌ Error initializing Gemini: {e}")
787
+ raise
788
+ # --- *** END UPDATE *** ---
789
+
790
+ # --- Node 1: The Agent ---
791
+ def agent_node(state: AgentState):
792
+ current_turn = state.get('turn', 0) + 1
793
+ print(f"\n{'='*60}")
794
+ print(f"AGENT TURN {current_turn}/{MAX_TURNS}")
795
+ print('='*60)
796
 
797
+ # Note: Max turns is also checked in should_continue, but good to have here
798
+ if current_turn > MAX_TURNS:
799
+ return {"messages": [SystemMessage(content="Max turns reached.")]}
 
 
 
 
 
 
 
800
 
801
+ max_retries = 3
802
+ ai_message = None
803
+ for attempt in range(max_retries):
804
+ try:
805
+ # Call the single, powerful LLM
806
+ ai_message = self.llm_with_tools.invoke(state["messages"])
807
+ break
808
+ except Exception as e:
809
+ print(f"⚠️ LLM attempt {attempt+1}/{max_retries} failed: {e}")
810
+ if attempt == max_retries - 1:
811
+ ai_message = AIMessage(
812
+ content=f"Error: LLM failed after {max_retries} attempts: {e}"
813
+ )
814
+ time.sleep(2 ** attempt)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
815
 
816
+ # --- Fallback Parsing Logic ---
817
+ if not ai_message.tool_calls and isinstance(ai_message.content, str) and ai_message.content.strip():
818
+ parsed_tool_calls = parse_tool_call_from_string(ai_message.content, self.tools)
819
+ if parsed_tool_calls:
820
+ print("πŸ”§ Fallback SUCCESS: Rebuilding tool call(s).")
821
+ ai_message.tool_calls = parsed_tool_calls
822
+ ai_message.content = "" # Clear the text content
823
+ else:
824
+ print(f"⚠️ Fallback FAILED: Could not parse any tool call from content:\n{ai_message.content[:200]}...")
825
 
826
+ if ai_message.tool_calls:
827
+ print(f"πŸ”§ Agent Tool Call: {ai_message.tool_calls[0]['name']}")
828
+ else:
829
+ print(f"πŸ’­ Agent Reasoning: {ai_message.content[:200]}...")
830
 
831
+ return {"messages": [ai_message], "turn": current_turn}
832
+
833
+ # --- Tool Node ---
834
+ tool_node = ToolNode(self.tools)
835
+
836
+ # --- Build Graph ---
837
+ print("Building Single-Agent graph...")
838
+ graph_builder = StateGraph(AgentState)
839
+
840
+ graph_builder.add_node("agent", agent_node)
841
+ graph_builder.add_node("tools", tool_node)
842
+
843
+ graph_builder.add_edge(START, "agent")
844
+
845
+ graph_builder.add_conditional_edges(
846
+ "agent",
847
+ should_continue, # Use the reverted conditional function
848
+ {
849
+ "tools": "tools",
850
+ "agent": "agent", # For loop prevention
851
+ END: END
852
+ }
853
+ )
854
+
855
+ graph_builder.add_edge("tools", "agent") # Loop back to agent
856
+
857
+ self.graph = graph_builder.compile()
858
+ print("βœ… Single-Agent graph compiled successfully.")
859
 
860
  def __call__(self, question: str) -> str:
861
  print(f"\n--- Starting Agent Run for Question ---")