Faham commited on
Commit
97db5ba
Β·
1 Parent(s): 2d26153

UPDATE: remove redundant code

Browse files
Files changed (1) hide show
  1. Home.py +2 -131
Home.py CHANGED
@@ -862,62 +862,6 @@ def create_basic_stock_chart(ticker: str):
862
  return None
863
 
864
 
865
- async def execute_tool_call(tool_call):
866
- """Execute a tool call using MCP servers."""
867
- try:
868
- tool_name = tool_call.function.name
869
-
870
- # Clean and validate the arguments JSON
871
- arguments_str = tool_call.function.arguments.strip()
872
-
873
- # Try to extract valid JSON if there's extra content
874
- try:
875
- arguments = json.loads(arguments_str)
876
- except json.JSONDecodeError:
877
- # Try to find JSON within the string
878
-
879
- json_match = re.search(r"\{[^{}]*\}", arguments_str)
880
- if json_match:
881
- try:
882
- arguments = json.loads(json_match.group())
883
- except json.JSONDecodeError:
884
- st.error(f"❌ Could not parse tool arguments: {arguments_str}")
885
- return f"Error: Invalid tool arguments format"
886
- else:
887
- st.error(f"❌ Could not parse tool arguments: {arguments_str}")
888
- return f"Error: Invalid tool arguments format"
889
-
890
- ticker = arguments.get("ticker")
891
-
892
- with st.status(
893
- f"πŸ› οΈ Executing {tool_name} for {ticker}...", expanded=True
894
- ) as status:
895
- if tool_name == "get_latest_news":
896
- result = await get_news_data(ticker)
897
- if "Error" in result or "Failed" in result:
898
- status.update(label=f"❌ {result}", state="error")
899
- else:
900
- status.update(
901
- label=f"βœ… {tool_name} completed for {ticker}", state="complete"
902
- )
903
- return result
904
- elif tool_name == "get_historical_stock_data":
905
- result = await get_stock_data(ticker)
906
- if "Error" in result or "Failed" in result:
907
- status.update(label=f"❌ {result}", state="error")
908
- else:
909
- status.update(
910
- label=f"βœ… {tool_name} completed for {ticker}", state="complete"
911
- )
912
- return result
913
- else:
914
- status.update(label=f"❌ Unknown tool: {tool_name}", state="error")
915
- return f"Unknown tool: {tool_name}"
916
- except Exception as e:
917
- st.error(f"❌ Error executing tool {tool_call.function.name}: {e}")
918
- return f"Error executing tool {tool_call.function.name}: {e}"
919
-
920
-
921
  # The master prompt that defines the agent's behavior
922
  system_prompt = """
923
  You are a financial assistant that provides comprehensive analysis based on real-time data. You MUST use tools to get data and then curate the information to answer the user's specific question.
@@ -943,79 +887,6 @@ You are FORBIDDEN from responding without calling both tools. Always call both t
943
  """
944
 
945
 
946
- async def run_agent(user_query, selected_ticker):
947
- """Run the financial agent with the given query and ticker."""
948
-
949
- # Construct the query to always fetch both data types
950
- full_query = f"Based on the latest news and stock performance data for {selected_ticker}, {user_query}"
951
-
952
- messages = [
953
- {"role": "system", "content": system_prompt},
954
- {"role": "user", "content": full_query},
955
- ]
956
-
957
- try:
958
- # Get initial response from the model
959
- with st.spinner("πŸ€– Generating analysis..."):
960
- response = client.chat.completions.create(
961
- model=model_name,
962
- messages=messages,
963
- tools=discovered_tools,
964
- tool_choice="required",
965
- )
966
-
967
- if not response.choices or len(response.choices) == 0:
968
- st.error("❌ Error: No response from model")
969
- return
970
-
971
- response_message = response.choices[0].message
972
-
973
- # Truncate tool call IDs if they're too long (max 40 chars)
974
- if hasattr(response_message, "tool_calls") and response_message.tool_calls:
975
- for tool_call in response_message.tool_calls:
976
- if len(tool_call.id) > 40:
977
- tool_call.id = tool_call.id[:40]
978
-
979
- messages.append(response_message)
980
-
981
- # Execute tool calls if any
982
- if response_message.tool_calls:
983
- st.info("πŸ› οΈ Executing data collection...")
984
- for tool_call in response_message.tool_calls:
985
- # Execute the tool call
986
- tool_result = await execute_tool_call(tool_call)
987
-
988
- # Add tool result to messages
989
- messages.append(
990
- {
991
- "role": "tool",
992
- "tool_call_id": tool_call.id[:40], # Truncate to max 40 chars
993
- "content": tool_result if tool_result else "No data available",
994
- }
995
- )
996
-
997
- # Get final response from the model
998
- with st.spinner("πŸ€– Finalizing analysis..."):
999
- final_response = client.chat.completions.create(
1000
- model=model_name,
1001
- messages=messages,
1002
- )
1003
-
1004
- if final_response.choices and len(final_response.choices) > 0:
1005
- final_content = final_response.choices[0].message.content
1006
- return final_content if final_content else "Empty response"
1007
- else:
1008
- return "No response generated"
1009
- else:
1010
- return (
1011
- response_message.content if response_message.content else "No response"
1012
- )
1013
-
1014
- except Exception as e:
1015
- st.error(f"❌ Error: {e}")
1016
- return "Please try again with a different question."
1017
-
1018
-
1019
  async def initialize_mcp_agent(model, tools):
1020
  """Initialize the MCP agent using LangGraph React agent"""
1021
  try:
@@ -1628,7 +1499,7 @@ def main():
1628
  if message["role"] == "user":
1629
  st.markdown(
1630
  f"""
1631
- <div style="background-color: #e3f2fd; padding: 10px; border-radius: 10px; margin: 5px 0; border: 1px solid #bbdefb;">
1632
  <strong>You:</strong> {message["content"]}
1633
  </div>
1634
  """,
@@ -1637,7 +1508,7 @@ def main():
1637
  else:
1638
  st.markdown(
1639
  f"""
1640
- <div style="background-color: #f5f5f5; padding: 10px; border-radius: 10px; margin: 5px 0; border: 1px solid #e0e0e0;">
1641
  <strong>Agent:</strong>
1642
  </div>
1643
  """,
 
862
  return None
863
 
864
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
865
  # The master prompt that defines the agent's behavior
866
  system_prompt = """
867
  You are a financial assistant that provides comprehensive analysis based on real-time data. You MUST use tools to get data and then curate the information to answer the user's specific question.
 
887
  """
888
 
889
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
890
  async def initialize_mcp_agent(model, tools):
891
  """Initialize the MCP agent using LangGraph React agent"""
892
  try:
 
1499
  if message["role"] == "user":
1500
  st.markdown(
1501
  f"""
1502
+ <div style="padding: 10px; border-radius: 10px; margin: 5px 0; border: 1px solid #bbdefb;">
1503
  <strong>You:</strong> {message["content"]}
1504
  </div>
1505
  """,
 
1508
  else:
1509
  st.markdown(
1510
  f"""
1511
+ <div style="padding: 10px; border-radius: 10px; margin: 5px 0; border: 1px solid #e0e0e0;">
1512
  <strong>Agent:</strong>
1513
  </div>
1514
  """,