robbyray commited on
Commit
cab98c4
·
verified ·
1 Parent(s): f0ad482

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -0
app.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ from langchain_groq import ChatGroq
4
+ from langchain_community.tools import DuckDuckGoSearchRun
5
+ from langgraph.prebuilt import create_react_agent
6
+
7
+ # --- 1. SETUP & SECURITY ---
8
+ # We use os.environ.get() to grab the key you saved in Settings
9
+ groq_api_key = os.environ.get("GROQ_API_KEY")
10
+
11
+ if not groq_api_key:
12
+ # If this error happens, go to Settings -> Variables and secrets -> Add GROQ_API_KEY
13
+ raise ValueError("❌ CRITICAL ERROR: GROQ_API_KEY not found in Secrets.")
14
+
15
+ # --- 2. INITIALIZE THE BRAIN (Groq + Llama 3) ---
16
+ try:
17
+ llm = ChatGroq(
18
+ api_key=groq_api_key,
19
+ model="llama-3.3-70b-versatile",
20
+ temperature=0
21
+ )
22
+ except Exception as e:
23
+ raise ValueError(f"❌ Failed to connect to Groq: {e}")
24
+
25
+ # --- 3. INITIALIZE TOOLS ---
26
+ search = DuckDuckGoSearchRun()
27
+ tools = [search]
28
+
29
+ # --- 4. CREATE THE AGENT ---
30
+ agent_executor = create_react_agent(llm, tools)
31
+
32
+ # --- 5. DEFINE THE INTERACTION ---
33
+ def chat_function(message, history):
34
+ """
35
+ Wrapper function for Gradio.
36
+ Takes user message, runs agent, returns answer.
37
+ """
38
+ print(f"\n[GOVERNANCE LOG] User Query: {message}") # Audit Log
39
+
40
+ try:
41
+ # Run the agent logic
42
+ response = agent_executor.invoke(
43
+ {"messages": [("user", message)]},
44
+ config={"recursion_limit": 5} # Cost Control
45
+ )
46
+
47
+ # Extract the final answer text
48
+ final_answer = response['messages'][-1].content
49
+
50
+ # Log the tool usage to the internal console (Governance)
51
+ for msg in response['messages']:
52
+ if msg.type == 'tool':
53
+ print(f"[GOVERNANCE LOG] Tool Used: {str(msg.content)[:100]}...")
54
+
55
+ return final_answer
56
+
57
+ except Exception as e:
58
+ error_msg = f"❌ System Error: {str(e)}"
59
+ print(f"[GOVERNANCE LOG] {error_msg}")
60
+ return error_msg
61
+
62
+ # --- 6. BUILD THE UI ---
63
+ demo = gr.ChatInterface(
64
+ fn=chat_function,
65
+ title="🚀 AI Financial Analyst",
66
+ description="**Governance-Focused AI Agent** | Powered by Llama 3.3 (Groq) & LangGraph.\n\nAsk me about stock prices, market trends, or financial concepts.",
67
+ examples=[
68
+ "What is the current price of NVDA?",
69
+ "Compare the P/E ratio of Ford and GM.",
70
+ "What are the latest risks for Tesla?"
71
+ ],
72
+ theme="soft"
73
+ )
74
+
75
+ # --- 7. LAUNCH ---
76
+ if __name__ == "__main__":
77
+ demo.launch()