noumanjavaid commited on
Commit
b203e5a
Β·
verified Β·
1 Parent(s): 4b61c01

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +134 -70
app.py CHANGED
@@ -1,119 +1,183 @@
 
1
  import streamlit as st
2
- import openai
3
  from typing import List, Dict
 
 
4
 
5
- # Set up page configuration
6
  st.set_page_config(
7
- page_title="Grok AI Assistant",
8
  page_icon="πŸš€",
9
  layout="wide",
10
  initial_sidebar_state="expanded"
11
  )
12
 
13
- # Custom CSS for enhanced styling
14
- st.markdown("""
 
 
 
 
 
 
 
 
 
 
 
15
  <style>
16
- .main-container {
17
- background-color: #0E1117;
18
- color: #FFFFFF;
19
- font-family: 'Roboto', sans-serif;
20
- }
21
- .stTextInput>div>div>input {
22
- background-color: #262730;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  color: white;
24
- border: 2px solid #4A4A4A;
25
- }
26
- .stButton>button {
27
- background-color: #FF4B4B;
 
 
28
  color: white;
29
  border: none;
30
  padding: 10px 20px;
31
- border-radius: 5px;
32
  transition: all 0.3s ease;
33
- }
34
- .stButton>button:hover {
35
- background-color: #FF6B6B;
36
- transform: scale(1.05);
37
- }
38
- .message-container {
39
- background-color: #262730;
40
- border-radius: 10px;
41
- padding: 15px;
42
- margin-bottom: 10px;
43
- }
44
- .user-message {
45
- background-color: #4A4A4A;
46
- text-align: right;
47
- }
48
- .ai-message {
49
- background-color: #1E1E2E;
50
- }
51
  </style>
52
  """, unsafe_allow_html=True)
53
 
54
- # Initialize OpenAI client
55
- apiKey = st.secrets.get("XAI_API_KEY")
56
- baseURL: "https://api.x.ai/v1"
57
-
58
- class GrokChatApp:
59
  def __init__(self):
60
- self.messages: List[Dict] = []
61
- self.system_prompt = (
62
- "You are Grok, a witty AI assistant inspired by the Hitchhiker's Guide to the Galaxy. "
63
- "Provide creative, humorous, and insightful responses with a touch of cosmic wisdom."
 
 
 
 
 
 
64
  )
 
 
 
 
 
 
 
 
 
 
65
 
66
  def generate_response(self, user_input: str) -> str:
67
  try:
68
- # Prepare messages for API call
 
 
 
 
 
69
  conversation = [
70
- {"role": "system", "content": self.system_prompt}
71
- ] + [
72
- {"role": msg['role'], "content": msg['content']}
73
- for msg in self.messages
74
- ] + [
75
  {"role": "user", "content": user_input}
76
  ]
77
 
78
- # Call Grok AI
79
- response = openai.chat.completions.create(
80
  model="grok-beta",
81
- messages=conversation
 
 
82
  )
83
 
84
  return response.choices[0].message.content
 
85
  except Exception as e:
86
- return f"🚨 Error: {str(e)}"
87
 
88
  def add_message(self, role: str, content: str):
89
  self.messages.append({"role": role, "content": content})
90
 
91
  def main():
92
- st.title("πŸš€ Grok AI: Cosmic Conversations")
93
 
94
- # Initialize chat app
95
  if 'chat_app' not in st.session_state:
96
- st.session_state.chat_app = GrokChatApp()
97
 
98
- # Chat history display
99
- chat_container = st.container()
100
- with chat_container:
101
- for msg in st.session_state.chat_app.messages:
102
- with st.chat_message(msg['role'], avatar='πŸ€–' if msg['role'] == 'assistant' else 'πŸ‘€'):
103
- st.markdown(msg['content'])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
 
105
- # User input
106
- user_input = st.chat_input("Ask Grok anything about life, universe, and everything...")
 
 
107
 
108
- if user_input:
109
- # Display user message
 
110
  st.session_state.chat_app.add_message("user", user_input)
111
  with st.chat_message("user", avatar='πŸ‘€'):
112
  st.markdown(user_input)
113
 
114
- # Generate and display AI response
115
- with st.chat_message("assistant", avatar='πŸ€–'):
116
- with st.spinner("Grok is pondering the mysteries of the universe..."):
117
  response = st.session_state.chat_app.generate_response(user_input)
118
  st.markdown(response)
119
 
 
1
+ import os
2
  import streamlit as st
3
+ from openai import OpenAI
4
  from typing import List, Dict
5
+ import random
6
+ import base64
7
 
8
+ # Advanced Styling and Cosmic Theme
9
  st.set_page_config(
10
+ page_title="Grok Cosmic Companion",
11
  page_icon="πŸš€",
12
  layout="wide",
13
  initial_sidebar_state="expanded"
14
  )
15
 
16
+ # Cosmic Background Generator
17
+ def get_cosmic_background():
18
+ # Create a dynamic, gradient cosmic background
19
+ colors = [
20
+ "linear-gradient(135deg, #1e2ad2, #8e2de2)",
21
+ "linear-gradient(135deg, #ff6a00, #ee0979)",
22
+ "linear-gradient(135deg, #000428, #004e92)",
23
+ "linear-gradient(135deg, #2c3e50, #3498db)"
24
+ ]
25
+ return random.choice(colors)
26
+
27
+ # Advanced CSS with Cosmic Design
28
+ st.markdown(f"""
29
  <style>
30
+ body {{
31
+ background: {get_cosmic_background()};
32
+ color: #ffffff;
33
+ font-family: 'Orbitron', sans-serif;
34
+ }}
35
+
36
+ .stApp {{
37
+ background: transparent;
38
+ }}
39
+
40
+ .main-container {{
41
+ background: rgba(0,0,0,0.7);
42
+ border-radius: 15px;
43
+ padding: 20px;
44
+ backdrop-filter: blur(10px);
45
+ }}
46
+
47
+ .chat-message {{
48
+ background: rgba(255,255,255,0.1);
49
+ border-radius: 10px;
50
+ padding: 15px;
51
+ margin-bottom: 10px;
52
+ transition: all 0.3s ease;
53
+ }}
54
+
55
+ .chat-message:hover {{
56
+ transform: scale(1.02);
57
+ box-shadow: 0 0 20px rgba(255,255,255,0.2);
58
+ }}
59
+
60
+ .stTextInput > div > div > input {{
61
+ background: rgba(255,255,255,0.1);
62
  color: white;
63
+ border: 2px solid rgba(255,255,255,0.2);
64
+ border-radius: 10px;
65
+ }}
66
+
67
+ .stButton > button {{
68
+ background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
69
  color: white;
70
  border: none;
71
  padding: 10px 20px;
72
+ border-radius: 20px;
73
  transition: all 0.3s ease;
74
+ }}
75
+
76
+ .stButton > button:hover {{
77
+ transform: scale(1.1);
78
+ box-shadow: 0 0 20px rgba(255,255,255,0.3);
79
+ }}
 
 
 
 
 
 
 
 
 
 
 
 
80
  </style>
81
  """, unsafe_allow_html=True)
82
 
83
+ class AdvancedGrokChatApp:
 
 
 
 
84
  def __init__(self):
85
+ # Cosmic AI Configuration
86
+ self.XAI_API_KEY = os.getenv("XAI_API_KEY")
87
+
88
+ if not self.XAI_API_KEY:
89
+ st.error("πŸ›Έ Cosmic Connection Lost: API Key Missing!")
90
+ st.stop()
91
+
92
+ self.client = OpenAI(
93
+ api_key=self.XAI_API_KEY,
94
+ base_url="https://api.x.ai/v1"
95
  )
96
+
97
+ # Advanced Personality Prompts
98
+ self.personality_modes = {
99
+ "Cosmic Philosopher": "You are a wise AI that speaks like a blend of Douglas Adams and Carl Sagan.",
100
+ "Intergalactic Comedian": "You are a witty AI that makes jokes about the universe's absurdities.",
101
+ "Scientific Oracle": "You provide deep scientific insights with poetic eloquence."
102
+ }
103
+
104
+ self.current_mode = "Cosmic Philosopher"
105
+ self.messages: List[Dict] = []
106
 
107
  def generate_response(self, user_input: str) -> str:
108
  try:
109
+ # Enhanced Conversation Context
110
+ system_prompt = (
111
+ f"{self.personality_modes[self.current_mode]} "
112
+ "Respond creatively, with depth and a touch of cosmic wonder."
113
+ )
114
+
115
  conversation = [
116
+ {"role": "system", "content": system_prompt}
117
+ ] + self.messages + [
 
 
 
118
  {"role": "user", "content": user_input}
119
  ]
120
 
121
+ response = self.client.chat.completions.create(
 
122
  model="grok-beta",
123
+ messages=conversation,
124
+ temperature=0.7, # More creative responses
125
+ max_tokens=300
126
  )
127
 
128
  return response.choices[0].message.content
129
+
130
  except Exception as e:
131
+ return f"πŸŒ‹ Cosmic Disruption: {str(e)}"
132
 
133
  def add_message(self, role: str, content: str):
134
  self.messages.append({"role": role, "content": content})
135
 
136
  def main():
137
+ st.title("πŸš€ Grok: Cosmic Companion")
138
 
139
+ # Initialize chat app with session state
140
  if 'chat_app' not in st.session_state:
141
+ st.session_state.chat_app = AdvancedGrokChatApp()
142
 
143
+ # Sidebar with Advanced Controls
144
+ with st.sidebar:
145
+ st.header("🌌 Cosmic Controls")
146
+
147
+ # Personality Mode Selector
148
+ mode = st.selectbox(
149
+ "Choose Grok's Personality",
150
+ list(st.session_state.chat_app.personality_modes.keys())
151
+ )
152
+ st.session_state.chat_app.current_mode = mode
153
+
154
+ # Conversation Management
155
+ col1, col2 = st.columns(2)
156
+ with col1:
157
+ if st.button("πŸ”„ Reset"):
158
+ st.session_state.chat_app.messages = []
159
+ st.success("Conversation reset to cosmic zero!")
160
+
161
+ with col2:
162
+ if st.button("πŸ’Ύ Save Conversation"):
163
+ # Placeholder for conversation saving logic
164
+ st.info("Conversation saved to cosmic archives!")
165
 
166
+ # Chat Interface
167
+ for msg in st.session_state.chat_app.messages:
168
+ with st.chat_message(msg['role'], avatar='πŸ€–' if msg['role'] == 'assistant' else 'πŸ‘€'):
169
+ st.markdown(msg['content'])
170
 
171
+ # User Input
172
+ if user_input := st.chat_input("Whisper your cosmic query..."):
173
+ # User Message
174
  st.session_state.chat_app.add_message("user", user_input)
175
  with st.chat_message("user", avatar='πŸ‘€'):
176
  st.markdown(user_input)
177
 
178
+ # AI Response
179
+ with st.chat_message("assistant", avatar='πŸš€'):
180
+ with st.spinner("Traversing cosmic data streams..."):
181
  response = st.session_state.chat_app.generate_response(user_input)
182
  st.markdown(response)
183