File size: 3,517 Bytes
6241bf7
cc2626e
 
6241bf7
 
 
cc2626e
 
 
 
 
 
6241bf7
 
cc2626e
 
 
 
 
6241bf7
cc2626e
6241bf7
cc2626e
 
6241bf7
cc2626e
 
 
 
c5afa27
cc2626e
 
6241bf7
cc2626e
 
6241bf7
cc2626e
 
6241bf7
cc2626e
 
 
 
 
 
 
 
6241bf7
 
cc2626e
 
 
 
 
 
 
 
 
 
6241bf7
 
cc2626e
 
 
 
6241bf7
 
cc2626e
6241bf7
 
cc2626e
 
6241bf7
cc2626e
 
 
 
a6fbb28
cc2626e
6241bf7
cc2626e
 
 
 
 
 
6241bf7
cc2626e
 
6241bf7
cc2626e
 
 
 
 
8ddcfdd
cc2626e
 
 
 
 
 
 
 
 
 
862f3f2
cc2626e
 
6241bf7
 
cc2626e
 
 
 
 
 
 
 
 
 
6241bf7
1afb8ef
6241bf7
cc2626e
 
0831aee
cc2626e
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
"""
Gradio ChatInterface for Survey Agent V2 - Simplified Version
Uses ChatInterface to avoid API generation bugs
"""

import os
import sys
from pathlib import Path

# Add parent directory to path for imports
sys.path.append(str(Path(__file__).parent))

from survey_agent import SurveyAnalysisAgent

try:
    from dotenv import load_dotenv
    load_dotenv()
except ImportError:
    pass

import gradio as gr

# Global agent
agent = None


def initialize_agent():
    """Initialize the survey analysis agent"""
    global agent
    
    if agent is not None:
        return agent
    
    openai_api_key = os.getenv("OPENAI_API_KEY")
    pinecone_api_key = os.getenv("PINECONE_API_KEY")
    
    if not openai_api_key or not pinecone_api_key:
        raise ValueError("Missing API keys")
    
    print("Initializing Survey Analysis Agent...")
    agent = SurveyAnalysisAgent(
        openai_api_key=openai_api_key,
        pinecone_api_key=pinecone_api_key,
        verbose=True
    )
    print("✅ Agent initialized!")
    return agent


def respond(message, history):
    """Process user message and return bot response"""
    global agent
    
    # Initialize agent if needed
    if agent is None:
        try:
            agent = initialize_agent()
        except Exception as e:
            return f"⚠️ Error: {str(e)}"
    
    try:
        # Use a default thread ID
        thread_id = "gradio_session"
        response = agent.query(message, thread_id=thread_id)
        return response
        
    except Exception as e:
        return f"❌ Error: {str(e)}\n\nPlease try rephrasing your question."


# Create the interface
print("Creating Gradio interface...")

# Create a custom chatbot with larger height
chatbot = gr.Chatbot(
    height=650,  # Increased height for better readability
    show_copy_button=True,  # Allow copying responses
    type='messages',  # Use openai-style message format
)

demo = gr.ChatInterface(
    respond,
    chatbot=chatbot,
    title="🗳️ Vanderbilt Unity Poll Survey Agent",
    description="""
    ### AI-Powered Analysis of Survey Data
    
    Ask questions about American public opinion using natural language.
    The system will search through survey data and provide comprehensive answers.
    
    **Example questions:**
    - What do Americans think about immigration in June 2025?
    - How has Biden's approval rating changed over time?
    - Show me views on the economy by political party
    - Break that down by gender
    
    **Available data:**
    - 9 polls from 2023-2025
    - 125 questions across topics like immigration, economy, healthcare, etc.
    - Demographic breakdowns by party, gender, age, and more
    """,
    examples=[
        "What do Americans think about immigration in June 2025?",
        "How has Biden's approval rating changed?",
        "Show me views on the economy by political party",
    ],
    cache_examples=False,  # Disable example caching to avoid running queries during startup
    theme=gr.themes.Soft(),
)

if __name__ == "__main__":
    print("\nLaunching Gradio interface...")
    print("The interface will open at http://127.0.0.1:7860")
    print("\nPress Ctrl+C to stop.\n")
    
    # Pre-initialize the agent
    try:
        initialize_agent()
    except Exception as e:
        print(f"⚠️ Warning: {e}")
    
    demo.launch(
        server_name="0.0.0.0",  # Bind to all interfaces for Hugging Face deployment
        server_port=7860,
        share=False,
        show_error=True
    )