akashraut commited on
Commit
71aebe3
·
verified ·
1 Parent(s): 5aeb8f1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +14 -105
app.py CHANGED
@@ -1,118 +1,27 @@
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()
 
 
 
 
 
 
 
 
1
  import asyncio
2
+ from langchain_mcp_adapters.client import MultiServerMCPClient
3
 
4
+ async def main():
5
+ print("🚀 Starting MCP client and launching price server...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
 
 
7
  client = MultiServerMCPClient({
8
  "price": {
9
+ "command": "python",
10
+ "args": ["prices_server.py"],
11
  "transport": "stdio",
 
12
  }
13
  })
14
 
15
+ print("🔍 Discovering MCP tools...")
16
+ tools = await client.get_tools()
17
+ print(f"✅ Discovered tools: {[t.name for t in tools]}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
+ print("📨 Calling `get_report` tool for Gold...")
20
+ result = await client.call_tool("price", "get_report", {"symbol": "XAU", "forecast_days": 3})
 
 
 
21
 
22
+ print("\n===== 🪙 GOLD PRICE REPORT =====\n")
23
+ print(result)
24
+ print("\n===============================\n")
25
 
26
  if __name__ == "__main__":
27
+ asyncio.run(main())