File size: 2,278 Bytes
f3af494
 
 
 
 
 
 
 
 
 
 
 
fc6b047
 
f3af494
fc6b047
 
 
 
 
 
 
 
 
 
 
 
 
 
f3af494
fc6b047
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3af494
fc6b047
f3af494
 
 
fc6b047
f3af494
 
 
 
 
 
 
 
 
 
 
fc6b047
 
 
 
f3af494
 
 
 
 
 
fc6b047
 
f3af494
fc6b047
f3af494
 
 
 
fc6b047
f3af494
 
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
import streamlit as st
import google.generativeai as genai
import os
from dotenv import load_dotenv

# Load API key from .env file
load_dotenv()
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))

# Initialize chat model
model = genai.GenerativeModel("gemini-1.5-flash")

# Streamlit UI Design
st.set_page_config(page_title="AI Chatbot", page_icon="🤖", layout="centered")

st.markdown(
    """
    <style>
        body {
            background-color: #f5f7fa;
        }
        .stChatMessage {
            border-radius: 12px;
            padding: 12px;
        }
    </style>
    """,
    unsafe_allow_html=True
)

# Title and description
st.title("🤖 AI Chatbot (Gemini 1.5 Flash)")
st.markdown(
    """
    ### Welcome to Your AI Chatbot!
    This chatbot is powered by **Google Gemini 1.5 Flash** and built with **Streamlit**.
    
    🧠 **What can it do?**
    - Answer questions & provide explanations
    - Help with writing & analysis tasks
    - Assist with problem-solving
    
    🔥 Start chatting below!
    """
)

# Initialize chat history
if "messages" not in st.session_state:
    st.session_state.messages = []

# Display chat history
for msg in st.session_state.messages:
    with st.chat_message(msg["role"]):
        st.markdown(msg["content"])

# Get user input
user_input = st.chat_input("Type your message...")

if user_input:
    # Display user message
    st.chat_message("user").markdown(user_input)
    
    # Format chat history for context
    chat_history = [{"role": "user" if m["role"] == "user" else "model", "parts": [m["content"]]} for m in st.session_state.messages]
    
    # Generate AI response
    response = model.generate_content(
        contents=[{"role": "user", "parts": [user_input]}],
        generation_config={"temperature": 0.7},
        safety_settings=[]
    )
    bot_reply = response.text
    
    # Display AI response
    st.chat_message("assistant").markdown(bot_reply)
    
    # Save conversation
    st.session_state.messages.append({"role": "user", "content": user_input})
    st.session_state.messages.append({"role": "assistant", "content": bot_reply})
    
    # Keep chat history concise
    if len(st.session_state.messages) > 6:
        st.session_state.messages = st.session_state.messages[-6:]