File size: 6,430 Bytes
65815f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import streamlit as st
import os
from langchain_groq import ChatGroq
from langchain.prompts import PromptTemplate
from langchain.schema import HumanMessage
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Configure Streamlit page
st.set_page_config(
    page_title="AI Research Assistant",
    page_icon="πŸ€–",
    layout="wide"
)

# App title and description
st.title("πŸ€– Agentic AI Research Assistant")
st.markdown("Enter a topic and get a structured research summary with key subtopics!")

# Sidebar for API key input
with st.sidebar:
    st.header("πŸ”‘ Configuration")
    # Try to get API key from environment variable first
    default_api_key = os.environ.get("GROQ_API_KEY", "")
    
    groq_api_key = st.text_input(
        "Enter your Groq API Key:",
        value=default_api_key,
        type="password",
        help="Get your free API key from https://console.groq.com/"
    )
    
    # Model selection
    model_choice = st.selectbox(
        "Choose Model:",
        ["llama-3.1-8b-instant", "mixtral-8x7b-32768"],
        help="LLaMA3 is faster, Mixtral is more capable"
    )

def initialize_agent(api_key, model_name):
    """Initialize the Groq LLM agent"""
    try:
        llm = ChatGroq(
            groq_api_key=api_key,
            model_name=model_name,
            temperature=0.3,
            max_tokens=1024
        )
        return llm
    except Exception as e:
        st.error(f"Error initializing agent: {str(e)}")
        return None

def create_research_prompt():
    """Create the research prompt template"""
    template = """
You are an AI research assistant. Your task is to analyze a given topic and break it down into subtopics with summaries.

TOPIC: {topic}

INSTRUCTIONS:
1. Break the topic into exactly 3 relevant subtopics
2. For each subtopic, provide 3-5 bullet points summary
3. Keep summaries concise and informative
4. Focus on the most important and current aspects

FORMAT YOUR RESPONSE EXACTLY LIKE THIS:

## Subtopic 1: [Subtopic Name]
β€’ [Bullet point 1]
β€’ [Bullet point 2]
β€’ [Bullet point 3]
β€’ [Bullet point 4]
β€’ [Bullet point 5]

## Subtopic 2: [Subtopic Name]
β€’ [Bullet point 1]
β€’ [Bullet point 2]
β€’ [Bullet point 3]
β€’ [Bullet point 4]

## Subtopic 3: [Subtopic Name]
β€’ [Bullet point 1]
β€’ [Bullet point 2]
β€’ [Bullet point 3]
β€’ [Bullet point 4]
β€’ [Bullet point 5]

Topic to analyze: {topic}
"""
    return PromptTemplate(template=template, input_variables=["topic"])

def process_research_query(agent, topic):
    """Process the research query using the agent"""
    try:
        # Create prompt
        prompt_template = create_research_prompt()
        formatted_prompt = prompt_template.format(topic=topic)
        
        # Get response from agent
        with st.spinner("πŸ” Researching and analyzing..."):
            response = agent.invoke([HumanMessage(content=formatted_prompt)])
            
        return response.content
    
    except Exception as e:
        st.error(f"Error processing query: {str(e)}")
        return None

def display_results(results):
    """Display the research results in a formatted way"""
    if results:
        st.markdown("## πŸ“Š Research Summary")
        st.markdown(results)
        
        # Add download option
        st.download_button(
            label="πŸ“₯ Download Summary",
            data=results,
            file_name="research_summary.md",
            mime="text/markdown"
        )

def main():
    # Check if API key is provided
    if not groq_api_key:
        st.warning("⚠️ Please enter your Groq API key in the sidebar to get started.")
        st.markdown("""
        ### How to get your Groq API key:
        1. Visit [Groq Console](https://console.groq.com/)
        2. Sign up for a free account
        3. Navigate to API Keys section
        4. Create a new API key
        5. Copy and paste it in the sidebar
        """)
        return
    
    # Initialize the agent
    agent = initialize_agent(groq_api_key, model_choice)
    if not agent:
        return
    
    # Main interface
    col1, col2 = st.columns([2, 1])
    
    with col1:
        # Topic input
        topic = st.text_input(
            "🎯 Enter your research topic:",
            placeholder="e.g., Latest AI tools for teachers",
            help="Be specific for better results"
        )
    
    with col2:
        st.markdown("<br>", unsafe_allow_html=True)  # Add space
        research_button = st.button("πŸš€ Start Research", type="primary")
    
    # Process query when button is clicked
    if research_button and topic:
        if len(topic.strip()) < 3:
            st.error("Please enter a more specific topic (at least 3 characters)")
            return
            
        # Process the research query
        results = process_research_query(agent, topic.strip())
        
        if results:
            display_results(results)
    
    elif research_button and not topic:
        st.error("Please enter a research topic first!")
    
    # Example topics
    st.markdown("---")
    st.markdown("### πŸ’‘ Example Topics:")
    example_topics = [
        "Latest AI tools for teachers",
        "Sustainable energy solutions 2024", 
        "Remote work productivity strategies",
        "Cybersecurity trends for small businesses",
        "Digital marketing for startups"
    ]
    
    cols = st.columns(len(example_topics))
    for i, example in enumerate(example_topics):
        with cols[i]:
            if st.button(f"πŸ“ {example}", key=f"example_{i}"):
                # Store the example topic in session state and rerun
                st.session_state.example_topic = example
                st.rerun()
    
    # Handle example topic selection
    if 'example_topic' in st.session_state:
        st.info(f"Example topic selected: {st.session_state.example_topic}")
        if st.button("Use this example topic"):
            # Process the example topic
            results = process_research_query(agent, st.session_state.example_topic)
            if results:
                display_results(results)
            # Clear the session state
            del st.session_state.example_topic

# Footer
st.markdown("---")
st.markdown(
    "Built with ❀️ using [Streamlit](https://streamlit.io) and [LangChain](https://langchain.com) | "
    "Powered by [Groq](https://groq.com)"
)

if __name__ == "__main__":
    main()