File size: 2,910 Bytes
f4fb91f
 
cab98c4
 
 
 
f4fb91f
cab98c4
 
f4fb91f
5ac9b4d
 
 
cab98c4
5ac9b4d
 
 
 
 
 
cab98c4
 
 
 
f4fb91f
 
cab98c4
 
 
 
 
 
f4fb91f
 
 
 
 
 
 
 
 
 
 
 
cab98c4
 
 
 
 
 
 
 
 
 
 
f4fb91f
cab98c4
 
 
 
f4fb91f
cab98c4
f4fb91f
cab98c4
 
f4fb91f
cab98c4
 
 
 
f4fb91f
cab98c4
f4fb91f
cab98c4
 
 
 
 
 
 
 
f4fb91f
 
cab98c4
 
f4fb91f
 
 
cab98c4
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93


import os
import gradio as gr
from langchain_groq import ChatGroq
from langchain_community.tools import DuckDuckGoSearchRun
from langchain_community.tools import TavilySearchResults # Added this import
from langgraph.prebuilt import create_react_agent

# --- 1. SECURE KEY ---
# --- 1. Fetch the Secrets ---
groq_api_key = os.environ.get("GROQ_API_KEY")
tavily_api_key = os.environ.get("TAVILY_API_KEY")

# --- 2. Security Check (Governance) ---
if not groq_api_key:
    raise ValueError("❌ CRITICAL ERROR: 'GROQ_API_KEY' not found. Please add it to your Space Secrets.")
if not tavily_api_key:
    # Optional: You can just warn if Tavily is not critical
    print("⚠️ Warning: 'TAVILY_API_KEY' not found. Search may not work.")

# --- 2. INITIALIZE THE BRAIN (Groq + Llama 3) ---
try:
    llm = ChatGroq(
        api_key=os.environ["GROQ_API_KEY"],
        model="llama-3.3-70b-versatile",
        temperature=0
    )
except Exception as e:
    raise ValueError(f"❌ Failed to connect to Groq: {e}")

# --- 3. INITIALIZE TOOLS ---

# Requires 'tavily-python' in requirements.txt
# If you don't have a key, this line will fail.
try:
    search = TavilySearchResults(max_results=2)
    tools = [search]
except Exception:
    raise ValueError("❌ TAVILY_API_KEY missing. Please add it to Secrets or switch back to DuckDuckGo.")


# search = DuckDuckGoSearchRun()
# tools = [search]

# --- 4. CREATE THE AGENT ---
agent_executor = create_react_agent(llm, tools)

# --- 5. DEFINE THE INTERACTION ---
def chat_function(message, history):
    """
    Wrapper function for Gradio.
    Takes user message, runs agent, returns answer.
    """
    print(f"\n[GOVERNANCE LOG] User Query: {message}") # Audit Log

    try:
        # Run the agent logic
        response = agent_executor.invoke(
            {"messages": [("user", message)]},
            config={"recursion_limit": 10} # Cost Control
        )

        # Extract the final answer text
        final_answer = response['messages'][-1].content

        # Log the tool usage to the internal console (Governance)
        for msg in response['messages']:
            if msg.type == 'tool':
                print(f"[GOVERNANCE LOG] Tool Used: {str(msg.content)[:100]}...")

        return final_answer

    except Exception as e:
        error_msg = f"❌ System Error: {str(e)}"
        print(f"[GOVERNANCE LOG] {error_msg}")
        return error_msg

# --- 6. BUILD THE UI ---
demo = gr.ChatInterface(
    fn=chat_function,
    title="AI Financial Analyst",
    description="**Governance-Focused AI Agent** | Powered by Llama 3.3 (Groq) & LangGraph.\n\nAsk me about stock prices, market trends, or financial concepts.",
    examples=[
        "What is the current price of NVDA?",
        "Compare the P/E ratio of Ford and GM.",
        "What are the latest risks for Tesla?"
    ],
)

# --- 7. LAUNCH ---
if __name__ == "__main__":
    demo.launch()