akashraut commited on
Commit
ace675a
Β·
verified Β·
1 Parent(s): 969de73

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -49
app.py CHANGED
@@ -1,101 +1,118 @@
1
  import os
2
  import gradio as gr
3
  from langchain_groq import ChatGroq
4
- from langchainhub import hub
5
  from langchain.agents import AgentExecutor, create_openai_tools_agent
6
  from langchain_mcp_adapters.client import MultiServerMCPClient
7
  import nest_asyncio
8
  import asyncio
9
 
10
- # Apply async patch for Hugging Face runtime
11
  nest_asyncio.apply()
12
 
13
- # --- Environment and API Key Setup ---
 
 
14
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
15
 
16
- # NOTE: METAL_API_KEY is no longer needed but we check for its existence
17
- # to avoid breaking old Hugging Face secret configurations.
18
  if not GROQ_API_KEY:
19
- raise ValueError("GROQ_API_KEY secret is not set in your Hugging Face Space!")
20
 
21
  print("βœ… Groq API key loaded successfully.")
22
- # --- End Setup ---
23
 
24
- # --- Agent and Tool Initialization ---
25
- # This section runs once when the application starts.
 
26
  agent_executor = None
 
27
  try:
28
- print("πŸš€ Initializing MCP Client and Tools...")
29
- # 1. Initialize the client that runs prices_server.py
30
- # No API key needs to be passed to the yfinance version.
 
31
  client = MultiServerMCPClient({
32
  "price": {
33
- "command": "python",
34
- "args": ["prices_server.py"],
35
  "transport": "stdio",
36
- "env": {} # No environment variables needed for yfinance
37
  }
38
  })
39
 
40
- # 2. Asynchronously get the tools from the client
41
- tools = asyncio.run(client.get_tools())
 
 
42
  if not tools:
43
- raise RuntimeError("No MCP tools found! Check prices_server.py logs.")
44
- print(f"βœ… Tools successfully found: {[tool.name for tool in tools]}")
45
 
46
- # 3. Set up the LLM with the stable Mixtral model
 
 
 
47
  llm = ChatGroq(model="mixtral-8x7b-32768", temperature=0)
48
 
49
- # 4. Pull the prompt from the LangChain Hub
50
- prompt = hub.pull("hwchase17/openai-tools-agent")
 
 
51
 
52
- # 5. Create the agent using the robust 'create_openai_tools_agent'
 
53
  agent = create_openai_tools_agent(llm, tools, prompt)
54
- agent_executor = AgentExecutor(
55
- agent=agent,
56
- tools=tools,
57
- verbose=True, # Shows the agent's thoughts in your logs
58
- )
59
- print("βœ… Agent Executor initialized successfully!")
60
 
61
  except Exception as e:
62
- print(f"πŸ”₯ FAILED to initialize the agent: {e}")
63
  agent_executor = None
64
- # --- End Initialization ---
65
 
66
 
67
- # --- Gradio Interface Logic ---
 
 
68
  async def metal_agent(message, history):
69
- """Asynchronous wrapper for the Gradio interface."""
70
  if agent_executor is None:
71
- return "Sorry, the agent failed to initialize. Please check the application logs."
72
-
73
- # Format the chat history for the agent
74
  chat_history = []
75
  for user_msg, ai_msg in history:
76
- from langchain_core.messages import HumanMessage, AIMessage
77
  chat_history.append(HumanMessage(content=user_msg))
78
  chat_history.append(AIMessage(content=ai_msg))
79
 
80
- # Invoke the agent
81
- response = await agent_executor.ainvoke({
82
- "input": message,
83
- "chat_history": chat_history
84
- })
85
- return response["output"]
 
 
 
86
 
87
  def launch_ui():
88
- """Launch the Gradio chat interface."""
89
  iface = gr.ChatInterface(
90
  fn=metal_agent,
91
  title="πŸ’° Metal Price Agent (Yahoo Finance + MCP + ChatGroq)",
92
- description="Ask for live & predicted gold/silver prices.",
93
  examples=[
94
  ["Show me the report for gold"],
95
- ["What is the 3 day forecast for silver?"],
96
- ]
 
97
  )
98
- iface.queue().launch(share=False)
 
 
 
 
 
 
99
 
100
  if __name__ == "__main__":
101
- launch_ui()
 
1
  import os
2
  import gradio as gr
3
  from langchain_groq import ChatGroq
4
+ import langchainhub
5
  from langchain.agents import AgentExecutor, create_openai_tools_agent
6
  from langchain_mcp_adapters.client import MultiServerMCPClient
7
  import nest_asyncio
8
  import asyncio
9
 
10
+ # Apply async patch (important for Hugging Face runtime)
11
  nest_asyncio.apply()
12
 
13
+ # ==========================
14
+ # Environment Setup
15
+ # ==========================
16
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
17
 
 
 
18
  if not GROQ_API_KEY:
19
+ raise ValueError("🚨 GROQ_API_KEY secret is not set in your Hugging Face Space!")
20
 
21
  print("βœ… Groq API key loaded successfully.")
 
22
 
23
+ # ==========================
24
+ # Agent + MCP Initialization
25
+ # ==========================
26
  agent_executor = None
27
+
28
  try:
29
+ print("\nπŸš€ Starting initialization sequence...")
30
+
31
+ # 1. Initialize MCP Client
32
+ print("🧩 Launching MCP Client to connect with prices_server.py ...")
33
  client = MultiServerMCPClient({
34
  "price": {
35
+ "command": "python3",
36
+ "args": ["-u", "prices_server.py"], # unbuffered logs
37
  "transport": "stdio",
38
+ "env": {}
39
  }
40
  })
41
 
42
+ # 2. Retrieve tools asynchronously
43
+ loop = asyncio.get_event_loop()
44
+ tools = loop.run_until_complete(client.get_tools())
45
+
46
  if not tools:
47
+ raise RuntimeError("❌ No MCP tools found. Check prices_server.py logs!")
 
48
 
49
+ print(f"βœ… Tools successfully discovered: {[tool.name for tool in tools]}")
50
+
51
+ # 3. Initialize LLM (Mixtral via Groq)
52
+ print("🧠 Initializing Groq LLM model (mixtral-8x7b-32768)...")
53
  llm = ChatGroq(model="mixtral-8x7b-32768", temperature=0)
54
 
55
+ # 4. Load LangChain Hub prompt
56
+ print("🧾 Fetching base prompt from LangChain Hub...")
57
+ prompt = langchainhub.pull("hwchase17/openai-tools-agent")
58
+ print("βœ… Prompt loaded successfully.")
59
 
60
+ # 5. Create the agent
61
+ print("πŸ› οΈ Creating agent executor...")
62
  agent = create_openai_tools_agent(llm, tools, prompt)
63
+ agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
64
+
65
+ print("βœ… Agent Executor initialized successfully.")
66
+ print("🎯 Initialization complete. Ready for user queries.\n")
 
 
67
 
68
  except Exception as e:
69
+ print(f"πŸ”₯ Initialization failed: {e}")
70
  agent_executor = None
 
71
 
72
 
73
+ # ==========================
74
+ # Gradio Chat Interface
75
+ # ==========================
76
  async def metal_agent(message, history):
77
+ """Handles user chat asynchronously."""
78
  if agent_executor is None:
79
+ return "⚠️ Agent initialization failed. Please check Space logs."
80
+
81
+ from langchain_core.messages import HumanMessage, AIMessage
82
  chat_history = []
83
  for user_msg, ai_msg in history:
 
84
  chat_history.append(HumanMessage(content=user_msg))
85
  chat_history.append(AIMessage(content=ai_msg))
86
 
87
+ try:
88
+ response = await agent_executor.ainvoke({
89
+ "input": message,
90
+ "chat_history": chat_history
91
+ })
92
+ return response["output"]
93
+ except Exception as e:
94
+ return f"❌ Error while processing your query: {e}"
95
+
96
 
97
  def launch_ui():
98
+ """Launches the Gradio interface."""
99
  iface = gr.ChatInterface(
100
  fn=metal_agent,
101
  title="πŸ’° Metal Price Agent (Yahoo Finance + MCP + ChatGroq)",
102
+ description="Ask for live metal rates (Gold/Silver) and 3-day forecasts using Yahoo Finance + Groq AI.",
103
  examples=[
104
  ["Show me the report for gold"],
105
+ ["What is the 3-day forecast for silver?"],
106
+ ["Give me today’s gold rate and upcoming trend"]
107
+ ],
108
  )
109
+
110
+ iface.queue().launch(
111
+ share=False,
112
+ server_name="0.0.0.0",
113
+ server_port=7860
114
+ )
115
+
116
 
117
  if __name__ == "__main__":
118
+ launch_ui()