Update app.py
Browse files
app.py
CHANGED
|
@@ -1,101 +1,118 @@
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
from langchain_groq import ChatGroq
|
| 4 |
-
|
| 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 |
-
#
|
|
|
|
|
|
|
| 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 |
-
#
|
| 25 |
-
#
|
|
|
|
| 26 |
agent_executor = None
|
|
|
|
| 27 |
try:
|
| 28 |
-
print("π
|
| 29 |
-
|
| 30 |
-
#
|
|
|
|
| 31 |
client = MultiServerMCPClient({
|
| 32 |
"price": {
|
| 33 |
-
"command": "
|
| 34 |
-
"args": ["prices_server.py"],
|
| 35 |
"transport": "stdio",
|
| 36 |
-
"env": {}
|
| 37 |
}
|
| 38 |
})
|
| 39 |
|
| 40 |
-
# 2.
|
| 41 |
-
|
|
|
|
|
|
|
| 42 |
if not tools:
|
| 43 |
-
raise RuntimeError("No MCP tools found
|
| 44 |
-
print(f"β
Tools successfully found: {[tool.name for tool in tools]}")
|
| 45 |
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
| 47 |
llm = ChatGroq(model="mixtral-8x7b-32768", temperature=0)
|
| 48 |
|
| 49 |
-
# 4.
|
| 50 |
-
prompt
|
|
|
|
|
|
|
| 51 |
|
| 52 |
-
# 5. Create the agent
|
|
|
|
| 53 |
agent = create_openai_tools_agent(llm, tools, prompt)
|
| 54 |
-
agent_executor = AgentExecutor(
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
)
|
| 59 |
-
print("β
Agent Executor initialized successfully!")
|
| 60 |
|
| 61 |
except Exception as e:
|
| 62 |
-
print(f"π₯
|
| 63 |
agent_executor = None
|
| 64 |
-
# --- End Initialization ---
|
| 65 |
|
| 66 |
|
| 67 |
-
#
|
|
|
|
|
|
|
| 68 |
async def metal_agent(message, history):
|
| 69 |
-
"""
|
| 70 |
if agent_executor is None:
|
| 71 |
-
return "
|
| 72 |
-
|
| 73 |
-
|
| 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 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
def launch_ui():
|
| 88 |
-
"""
|
| 89 |
iface = gr.ChatInterface(
|
| 90 |
fn=metal_agent,
|
| 91 |
title="π° Metal Price Agent (Yahoo Finance + MCP + ChatGroq)",
|
| 92 |
-
description="Ask for live
|
| 93 |
examples=[
|
| 94 |
["Show me the report for gold"],
|
| 95 |
-
["What is the 3
|
| 96 |
-
|
|
|
|
| 97 |
)
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|