Spaces:
Runtime error
Runtime error
File size: 9,177 Bytes
b203e5a 2c836ab b203e5a a9c4879 b203e5a 5f02f49 f7a4da1 2c836ab b203e5a 2c836ab b203e5a 2c836ab f7a4da1 b203e5a 2c836ab ff19abc 79fa50b 0235176 f7a4da1 0235176 f7a4da1 0235176 f7a4da1 0235176 f7a4da1 0235176 79fa50b f7a4da1 0235176 f7a4da1 0235176 f7a4da1 0235176 f7a4da1 0235176 79fa50b f7a4da1 0235176 f7a4da1 0235176 f7a4da1 0235176 79fa50b f7a4da1 79fa50b f7a4da1 0235176 f7a4da1 0235176 f7a4da1 ff19abc 79fa50b ff19abc 0235176 ff19abc 79fa50b ff19abc 0235176 ff19abc 0235176 ff19abc 0235176 79fa50b 0235176 79fa50b 0235176 79fa50b 0235176 2c836ab b203e5a 2c836ab ff19abc b203e5a f7a4da1 b203e5a f7a4da1 b203e5a ff19abc b203e5a f7a4da1 2c836ab f7a4da1 2c836ab b203e5a 2c836ab b203e5a 2c836ab b203e5a ca60cc8 b203e5a 9e6746e 2c836ab b203e5a 2c836ab f7a4da1 2c836ab f7a4da1 2c836ab ff19abc f7a4da1 2c836ab b203e5a 2c836ab f7a4da1 ff19abc f7a4da1 b203e5a ff19abc b203e5a ff19abc b203e5a f7a4da1 ff19abc f7a4da1 ff19abc f7a4da1 2c836ab b203e5a ff19abc 2c836ab b203e5a ff19abc b203e5a 2c836ab b203e5a ff19abc 2c836ab |
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 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
import os
import streamlit as st
from openai import OpenAI
from typing import List, Dict, Optional
import random
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Advanced Styling and Cosmic Theme
st.set_page_config(
page_title="Grok Cosmic Companion",
page_icon="π",
layout="wide",
initial_sidebar_state="expanded"
)
def get_cosmic_background() -> str:
"""Generate a random cosmic gradient background."""
colors = [
"linear-gradient(135deg, #1e2ad2, #8e2de2)",
"linear-gradient(135deg, #ff6a00, #ee0979)",
"linear-gradient(135deg, #000428, #004e92)",
"linear-gradient(135deg, #2c3e50, #3498db)"
]
return random.choice(colors)
# Advanced CSS with Cosmic Design
st.markdown(f"""
<style>
@import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;500;600;700&display=swap');
* {{
font-family: 'Orbitron', sans-serif !important;
}}
.stApp {{
background: {get_cosmic_background()};
background-attachment: fixed;
background-size: cover;
color: white;
}}
section[data-testid="stSidebar"] {{
background-color: rgba(0, 0, 0, 0.3);
backdrop-filter: blur(10px);
}}
.main .block-container {{
background: rgba(0, 0, 0, 0.3);
border-radius: 15px;
padding: 20px;
backdrop-filter: blur(10px);
}}
/* Chat message styling */
.chat-message {{
background: rgba(255, 255, 255, 0.1);
border-radius: 10px;
padding: 15px;
margin-bottom: 10px;
transition: all 0.3s ease;
}}
.chat-message:hover {{
transform: scale(1.02);
box-shadow: 0 0 20px rgba(255, 255, 255, 0.2);
}}
/* Input field styling */
.stTextInput > div > div > input {{
background: rgba(255, 255, 255, 0.1);
color: white;
border: 2px solid rgba(255, 255, 255, 0.2);
border-radius: 10px;
}}
/* Button styling */
.stButton > button {{
background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
color: white;
border: none;
padding: 10px 20px;
border-radius: 20px;
transition: all 0.3s ease;
text-transform: uppercase;
letter-spacing: 1px;
}}
.stButton > button:hover {{
transform: scale(1.1);
box-shadow: 0 0 20px rgba(255, 255, 255, 0.3);
}}
/* Title styling */
.cosmic-title {{
text-align: center;
font-size: 2.5rem;
margin-bottom: 2rem;
color: white;
text-shadow: 0 0 10px rgba(255, 255, 255, 0.5);
animation: glow 2s ease-in-out infinite alternate;
font-weight: 700;
}}
/* Header styling */
[data-testid="stHeader"] {{
background: rgba(0, 0, 0, 0.3);
backdrop-filter: blur(10px);
}}
/* Select box styling */
.stSelectbox label,
.stSelectbox div[data-baseweb="select"] span {{
color: white !important;
}}
/* Markdown text styling */
div[data-testid="stMarkdownContainer"] {{
color: white;
}}
/* Sidebar text */
.sidebar .sidebar-content {{
font-weight: 500;
}}
/* Chat input styling */
.stChatInputContainer {{
padding-bottom: 20px;
}}
/* Chat message text */
.stChatMessage {{
font-weight: 400;
letter-spacing: 0.5px;
}}
/* Spinner text */
.stSpinner {{
font-weight: 500;
letter-spacing: 1px;
}}
@keyframes glow {{
from {{
text-shadow: 0 0 10px rgba(255, 255, 255, 0.5);
}}
to {{
text-shadow: 0 0 20px rgba(255, 255, 255, 0.8),
0 0 30px rgba(255, 255, 255, 0.6);
}}
}}
/* Additional elements */
button, input, optgroup, select, textarea {{
font-family: 'Orbitron', sans-serif !important;
}}
.streamlit-expanderHeader {{
font-family: 'Orbitron', sans-serif !important;
letter-spacing: 1px;
}}
.stAlert {{
font-family: 'Orbitron', sans-serif !important;
letter-spacing: 0.5px;
}}
</style>
""", unsafe_allow_html=True)
class AdvancedGrokChatApp:
def __init__(self):
"""Initialize the chat application with API configuration and personality modes."""
self.XAI_API_KEY: str = "xai-1HSpHLqxC3LnInrYpwAobgEVsjchUG0PP0adniSXWGQXwq6YfvcPto9MhsS6ouQtC4a4Dh2qqXmERgQQ"
try:
self.client = OpenAI(
api_key=self.XAI_API_KEY,
base_url="https://api.x.ai/v1"
)
except Exception as e:
st.error(f"πΈ Failed to initialize OpenAI client: {str(e)}")
st.stop()
self.personality_modes: Dict[str, str] = {
"Cosmic Philosopher": "You are a wise AI that speaks like a blend of Douglas Adams and Carl Sagan.",
"Intergalactic Comedian": "You are a witty AI that makes jokes about the universe's absurdities.",
"Scientific Oracle": "You provide deep scientific insights with poetic eloquence.",
"Space Explorer": "You are an adventurous AI exploring the mysteries of the cosmos."
}
self.current_mode: str = "Cosmic Philosopher"
self.messages: List[Dict[str, str]] = []
def generate_response(self, user_input: str) -> str:
"""Generate AI response based on user input and conversation history."""
try:
system_prompt = (
f"{self.personality_modes[self.current_mode]} "
"Respond creatively, with depth and a touch of cosmic wonder."
)
conversation = [
{"role": "system", "content": system_prompt}
] + self.messages + [
{"role": "user", "content": user_input}
]
response = self.client.chat.completions.create(
model="grok-beta",
messages=conversation,
temperature=0,
max_tokens=4096
)
return response.choices[0].message.content
except Exception as e:
st.error(f"π Cosmic Disruption: {str(e)}")
return "I apologize, but I'm experiencing a cosmic disturbance. Please try again."
def add_message(self, role: str, content: str) -> None:
"""Add a message to the conversation history."""
self.messages.append({"role": role, "content": content})
def save_conversation(self) -> str:
"""Save the conversation history to a string format."""
return "\n".join([f"{msg['role']}: {msg['content']}" for msg in self.messages])
def initialize_session_state() -> None:
"""Initialize or reset the session state."""
if 'chat_app' not in st.session_state:
st.session_state.chat_app = AdvancedGrokChatApp()
def main() -> None:
"""Main application function."""
st.markdown('<h1 class="cosmic-title">π Grok: Cosmic Companion</h1>', unsafe_allow_html=True)
initialize_session_state()
# Sidebar with Advanced Controls
with st.sidebar:
st.header("π Cosmic Controls")
# Personality Mode Selector
mode = st.selectbox(
"Choose Grok's Personality",
list(st.session_state.chat_app.personality_modes.keys())
)
st.session_state.chat_app.current_mode = mode
# Conversation Management
col1, col2 = st.columns(2)
with col1:
if st.button("π Reset Chat"):
st.session_state.chat_app.messages = []
st.success("β¨ Conversation reset to cosmic zero!")
with col2:
if st.button("πΎ Save Chat"):
conversation_text = st.session_state.chat_app.save_conversation()
st.download_button(
label="π₯ Download",
data=conversation_text,
file_name="cosmic_conversation.txt",
mime="text/plain"
)
# Chat Interface
chat_container = st.container()
with chat_container:
for msg in st.session_state.chat_app.messages:
with st.chat_message(msg['role'], avatar='π€' if msg['role'] == 'assistant' else 'π€'):
st.markdown(msg['content'])
# User Input
if user_input := st.chat_input("π Whisper your cosmic query..."):
# User Message
st.session_state.chat_app.add_message("user", user_input)
with st.chat_message("user", avatar='π€'):
st.markdown(user_input)
# AI Response
with st.chat_message("assistant", avatar='π'):
with st.spinner("π Traversing cosmic data streams..."):
response = st.session_state.chat_app.generate_response(user_input)
st.markdown(response)
st.session_state.chat_app.add_message("assistant", response)
if __name__ == "__main__":
main() |