uumerrr684 commited on
Commit
b95cfcd
·
verified ·
1 Parent(s): f6357df

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +256 -127
app.py CHANGED
@@ -1,127 +1,256 @@
1
- import gradio as gr
2
- import requests
3
- import os
4
-
5
- # Define the model to use for the chatbot
6
- CHATBOT_MODEL = "openai/gpt-3.5-turbo"
7
-
8
- # --- OPENROUTER API LOGIC ---
9
- # The OpenRouter API key will be read from an environment variable.
10
- # On Hugging Face Spaces, you can set this in the "Secrets" section.
11
- def get_openrouter_api_key():
12
- """Retrieves the OpenRouter API key from environment variables."""
13
- api_key = os.environ.get("OPENROUTER_API_KEY")
14
- if not api_key:
15
- return None
16
- return api_key
17
-
18
- def generate_response(message, history):
19
- """
20
- Sends a message and the chat history to the OpenRouter API to generate a response.
21
-
22
- Args:
23
- message (str): The user's new message.
24
- history (list): A list of tuples containing previous user/bot messages.
25
-
26
- Returns:
27
- str: The AI's generated response or an error message.
28
- """
29
- api_key = get_openrouter_api_key()
30
- if not api_key:
31
- return "Error: OPENROUTER_API_KEY is not set. Please configure it in the environment secrets."
32
-
33
- url = "https://openrouter.ai/api/v1/chat/completions"
34
- headers = {
35
- "Authorization": f"Bearer {api_key}",
36
- "Content-Type": "application/json"
37
- }
38
-
39
- # Construct the messages list for the API call, including the system prompt
40
- # and all previous messages from the history.
41
- messages = [{"role": "system", "content": "You are a helpful AI assistant."}]
42
- for user_msg, bot_msg in history:
43
- messages.append({"role": "user", "content": user_msg})
44
- messages.append({"role": "assistant", "content": bot_msg})
45
- messages.append({"role": "user", "content": message})
46
-
47
- data = {
48
- "model": CHATBOT_MODEL,
49
- "messages": messages,
50
- }
51
-
52
- try:
53
- response = requests.post(url, headers=headers, json=data)
54
- response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
55
- result = response.json()
56
-
57
- # Extract and return the chatbot's response
58
- return result['choices'][0]['message']['content']
59
-
60
- except requests.exceptions.RequestException as e:
61
- return f"An error occurred: {e}"
62
-
63
- # --- GRADIO UI & THEME ---
64
- # Create a custom theme to replicate the '2025 green glowing' aesthetic.
65
- custom_theme = gr.themes.Soft(
66
- # Set the primary and secondary hues to create the green glow effect
67
- primary_hue="emerald", # Use a vibrant green hue
68
- secondary_hue="gray",
69
- font=[gr.themes.GoogleFont("DM Sans"), "sans-serif"],
70
- ).set(
71
- # Set the background to a deep black
72
- body_background_fill="#030712",
73
- # Style the text box and submit button to match the theme
74
- block_background_fill="#1F2937",
75
- block_border_color="#34D399", # Glowing green border
76
- block_border_width="2px",
77
- block_border_radius="25px",
78
- button_background_fill="#34D399",
79
- button_background_fill_hover="#10B981",
80
- button_text_color="#1F2937",
81
- button_border_radius="25px",
82
-
83
- # Set text colors
84
- text_color="#34D399",
85
- background_fill_primary="#030712", # Main background color
86
- background_fill_secondary="#1F2937",
87
- )
88
-
89
- # Custom CSS to style the chatbot messages and container, fixing the TypeError.
90
- custom_css = """
91
- .gradio-container {
92
- background-color: #030712;
93
- color: #34D399;
94
- }
95
- .gradio-chatbot {
96
- background-color: #1F2937;
97
- border: none;
98
- border-radius: 8px;
99
- }
100
- .gradio-chatbot .message.bot {
101
- background-color: #111827;
102
- border-radius: 10px;
103
- }
104
- .gradio-chatbot .message.user {
105
- background-color: #374151;
106
- border-radius: 10px;
107
- }
108
- """
109
-
110
- # Use the custom theme with the ChatInterface
111
- demo = gr.ChatInterface(
112
- generate_response,
113
- theme=custom_theme,
114
- title="My Cyber Chatbot",
115
- textbox=gr.Textbox(
116
- placeholder="Ask anything",
117
- container=False,
118
- show_copy_button=True
119
- ),
120
- retry_btn=None,
121
- undo_btn=None,
122
- clear_btn="Clear Chat",
123
- css=custom_css,
124
- )
125
-
126
- # Launch the app
127
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>My Chatbot</title>
7
+ <style>
8
+ body {
9
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif;
10
+ margin: 0;
11
+ padding: 0;
12
+ background-color: #f7f7f7;
13
+ display: flex;
14
+ justify-content: center;
15
+ align-items: center;
16
+ height: 100vh;
17
+ }
18
+
19
+ .chatbot-container {
20
+ width: 90%;
21
+ max-width: 900px;
22
+ height: 90vh;
23
+ display: flex;
24
+ flex-direction: column;
25
+ background-color: #fff;
26
+ border-radius: 12px;
27
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
28
+ overflow: hidden;
29
+ }
30
+
31
+ .chatbot-header {
32
+ display: flex;
33
+ justify-content: space-between;
34
+ align-items: center;
35
+ padding: 16px 24px;
36
+ border-bottom: 1px solid #e5e5e5;
37
+ }
38
+
39
+ .chatbot-logo {
40
+ font-weight: 600;
41
+ font-size: 1.25rem;
42
+ color: #333;
43
+ }
44
+
45
+ .chatbot-info .status {
46
+ color: #666;
47
+ font-size: 0.8rem;
48
+ margin-right: 10px;
49
+ }
50
+
51
+ .plus-button {
52
+ background-color: #1a73e8;
53
+ color: #fff;
54
+ border: none;
55
+ padding: 8px 16px;
56
+ border-radius: 20px;
57
+ font-size: 0.8rem;
58
+ cursor: pointer;
59
+ }
60
+
61
+ .chatbot-main {
62
+ flex-grow: 1;
63
+ display: flex;
64
+ flex-direction: column;
65
+ justify-content: center;
66
+ align-items: center;
67
+ text-align: center;
68
+ padding: 20px;
69
+ overflow-y: auto;
70
+ }
71
+
72
+ .intro-message {
73
+ max-width: 500px;
74
+ margin-bottom: 20px;
75
+ color: #444;
76
+ }
77
+
78
+ .intro-message h2 {
79
+ font-size: 2rem;
80
+ font-weight: 600;
81
+ margin-bottom: 10px;
82
+ }
83
+
84
+ .chat-area {
85
+ width: 100%;
86
+ max-width: 700px;
87
+ display: flex;
88
+ flex-direction: column;
89
+ gap: 15px;
90
+ overflow-y: auto;
91
+ padding: 20px 0;
92
+ }
93
+
94
+ .message {
95
+ padding: 10px 15px;
96
+ border-radius: 18px;
97
+ max-width: 70%;
98
+ word-wrap: break-word;
99
+ }
100
+
101
+ .user-message {
102
+ background-color: #f0f0f0;
103
+ align-self: flex-end;
104
+ }
105
+
106
+ .bot-message {
107
+ background-color: #e6f7ff;
108
+ align-self: flex-start;
109
+ }
110
+
111
+ .chatbot-input-form {
112
+ padding: 16px 24px;
113
+ border-top: 1px solid #e5e5e5;
114
+ }
115
+
116
+ .input-container {
117
+ display: flex;
118
+ border: 1px solid #e5e5e5;
119
+ border-radius: 24px;
120
+ padding: 8px;
121
+ background-color: #f7f7f7;
122
+ }
123
+
124
+ #chat-input {
125
+ flex-grow: 1;
126
+ border: none;
127
+ background: transparent;
128
+ font-size: 1rem;
129
+ padding: 0 10px;
130
+ }
131
+
132
+ #chat-input:focus {
133
+ outline: none;
134
+ }
135
+
136
+ .send-button {
137
+ background-color: #1a73e8;
138
+ border: none;
139
+ border-radius: 50%;
140
+ width: 36px;
141
+ height: 36px;
142
+ display: flex;
143
+ justify-content: center;
144
+ align-items: center;
145
+ cursor: pointer;
146
+ }
147
+
148
+ .send-button svg {
149
+ fill: #fff;
150
+ transform: rotate(45deg);
151
+ }
152
+ </style>
153
+ </head>
154
+ <body>
155
+ <div class="chatbot-container">
156
+ <header class="chatbot-header">
157
+ <div class="chatbot-logo">ChatGPT</div>
158
+ <div class="chatbot-info">
159
+ <span class="status">Saved memory full</span>
160
+ <button class="plus-button">+ Get Plus</button>
161
+ </div>
162
+ </header>
163
+
164
+ <main class="chatbot-main">
165
+ <div class="intro-message">
166
+ <h2>Introducing GPT-5</h2>
167
+ <p>ChatGPT now has our smartest, fastest, most useful model yet, with thinking built in — so you get the best answer, every time.</p>
168
+ </div>
169
+ <div class="chat-area">
170
+ </div>
171
+ </main>
172
+
173
+ <form class="chatbot-input-form" id="chat-form">
174
+ <div class="input-container">
175
+ <input type="text" id="chat-input" placeholder="Ask anything" autocomplete="off">
176
+ <button type="submit" class="send-button">
177
+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" class="text-white dark:text-black">
178
+ <path d="M12 4L3 9L12 14L21 9L12 4ZM12 16V22L21 9L12 16Z" fill="currentColor"></path>
179
+ </svg>
180
+ </button>
181
+ </div>
182
+ </form>
183
+ </div>
184
+
185
+ <script>
186
+ document.addEventListener('DOMContentLoaded', () => {
187
+ const chatForm = document.getElementById('chat-form');
188
+ const chatInput = document.getElementById('chat-input');
189
+ const chatArea = document.querySelector('.chat-area');
190
+ const introMessage = document.querySelector('.intro-message');
191
+
192
+ // Replace with your OpenRouter API key
193
+ const OPENROUTER_API_KEY = 'YOUR_OPENROUTER_API_KEY';
194
+
195
+ const MODEL_NAME = 'gpt-3.5-turbo';
196
+
197
+ const appendMessage = (message, sender) => {
198
+ const messageDiv = document.createElement('div');
199
+ messageDiv.classList.add('message');
200
+ messageDiv.classList.add(`${sender}-message`);
201
+ messageDiv.textContent = message;
202
+ chatArea.appendChild(messageDiv);
203
+ chatArea.scrollTop = chatArea.scrollHeight;
204
+ };
205
+
206
+ const sendMessage = async (userMessage) => {
207
+ // Hide the intro message when the first message is sent
208
+ if (introMessage) {
209
+ introMessage.style.display = 'none';
210
+ }
211
+
212
+ appendMessage(userMessage, 'user');
213
+ chatInput.value = '';
214
+
215
+ try {
216
+ const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
217
+ method: 'POST',
218
+ headers: {
219
+ 'Authorization': `Bearer ${OPENROUTER_API_KEY}`,
220
+ 'Content-Type': 'application/json',
221
+ },
222
+ body: JSON.stringify({
223
+ model: MODEL_NAME,
224
+ messages: [
225
+ { role: 'system', content: 'You are a helpful assistant.' },
226
+ { role: 'user', content: userMessage }
227
+ ],
228
+ }),
229
+ });
230
+
231
+ if (!response.ok) {
232
+ const errorData = await response.json();
233
+ throw new Error(errorData.error.message || `API error: ${response.statusText}`);
234
+ }
235
+
236
+ const data = await response.json();
237
+ const botMessage = data.choices[0].message.content;
238
+ appendMessage(botMessage, 'bot');
239
+
240
+ } catch (error) {
241
+ console.error('Error:', error);
242
+ appendMessage('Sorry, I am unable to connect right now. Please try again later.', 'bot');
243
+ }
244
+ };
245
+
246
+ chatForm.addEventListener('submit', (e) => {
247
+ e.preventDefault();
248
+ const userMessage = chatInput.value.trim();
249
+ if (userMessage) {
250
+ sendMessage(userMessage);
251
+ }
252
+ });
253
+ });
254
+ </script>
255
+ </body>
256
+ </html>