shukdevdattaEX commited on
Commit
ecfe44f
Β·
verified Β·
1 Parent(s): 1550fe3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +204 -0
app.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import openai
3
+ import json
4
+ import os
5
+ from typing import List, Tuple, Optional
6
+ from datetime import datetime
7
+
8
+ class ChatbotManager:
9
+ def __init__(self):
10
+ self.conversation_history = []
11
+ self.current_api_key = None
12
+ self.current_model = "gpt-3.5-turbo"
13
+ self.system_prompt = "You are a helpful AI assistant. Respond in a friendly and informative manner." #default
14
+ self.max_tokens = 150
15
+ self.temperature = 0.7
16
+
17
+ def set_api_key(self, api_key: str) -> str:
18
+ if not api_key.strip():
19
+ return "❌ Please enter a valid API key"
20
+
21
+ self.current_api_key = api_key.strip()
22
+ openai.api_key = self.current_api_key
23
+
24
+ try:
25
+ openai.Model.list()
26
+ return "βœ… API key validated successfully!"
27
+ except Exception as e:
28
+ return f"❌ Invalid API key: {str(e)}"
29
+
30
+ def update_settings(self, model: str, system_prompt: str, max_tokens: int, temperature: float) -> str:
31
+ self.current_model = model
32
+ self.system_prompt = system_prompt
33
+ self.max_tokens = max_tokens
34
+ self.temperature = temperature
35
+ return f"βœ… Settings updated: Model={model}, Max Tokens={max_tokens}, Temperature={temperature}"
36
+
37
+ def preprocess_data(self, data_text: str) -> str: ### we are integrating the custom data to the existing KB of model
38
+ if not data_text.strip():
39
+ return "No custom data provided"
40
+
41
+ base_prompt = "You are a helpful AI assistant. Respond in a friendly and informative manner."
42
+ self.system_prompt = base_prompt + f"\n\nAdditional Context:\n{data_text}"
43
+ return f"βœ… Custom data integrated ({len(data_text)} characters)"
44
+
45
+ def generate_response(self,user_input:str, history: List[Tuple[str, str]])-> Tuple[str, List[Tuple[str, str]]]:
46
+ if not self.current_api_key:
47
+ return "❌ Please set your API key first!", history
48
+
49
+ if not user_input.strip():
50
+ return "Please enter a message.", history
51
+
52
+ try:
53
+ messages=[{"role": "system", "content": self.system_prompt}]
54
+
55
+ for user_msg, assistant_msg in history:
56
+ messages.append({"role": "user", "content": user_msg})
57
+ messages.append({"role": "assistant", "content": assistant_msg})
58
+
59
+ messages.append({"role": "user", "content": user_input})
60
+
61
+ response=openai.ChatCompletion.create(
62
+ model=self.current_model,
63
+ messages=messages,
64
+ max_tokens=self.max_tokens,
65
+ temperature=self.temperature,
66
+ n=1,
67
+ stop=None,
68
+ )
69
+
70
+ assistant_response = response.choices[0].message.content.strip()
71
+ history.append((user_input, assistant_response))
72
+
73
+ return assistant_response, history
74
+
75
+ except Exception as e:
76
+ error_msg = f"❌ Error generating response: {str(e)}"
77
+ return error_msg, history
78
+
79
+ def clear_conversation(self) -> Tuple[str, List[Tuple[str, str]]]:
80
+ self.conversation_history = []
81
+ return "", []
82
+
83
+ chatbot=ChatbotManager()
84
+
85
+ AVAILABLE_MODELS = [ #dropdown for models openai==0.28
86
+ "gpt-3.5-turbo",
87
+ "gpt-3.5-turbo-16k",
88
+ "gpt-4",
89
+ "gpt-4-32k",
90
+ "gpt-4-0613",
91
+ "gpt-4-32k-0613"
92
+ ]
93
+
94
+ def create_interface():
95
+ with gr.Blocks(title="LLM-Based Chatbot", theme=gr.themes.Ocean()) as demo:
96
+ gr.Markdown("""
97
+ # πŸ€– LLM-Based Conversational AI Chatbot
98
+ This chatbot leverages powerful Language Models to provide intelligent conversations.
99
+ Enter your OpenAI API key to get started!
100
+ """)
101
+ with gr.Tab("Chat Interface"):
102
+ with gr.Row():
103
+ with gr.Column(scale=3):
104
+ chatbot_interface = gr.Chatbot(
105
+ label="Conversation",
106
+ height=400,
107
+ show_label=True,
108
+ avatar_images=("user.png", "assistant.png"),
109
+ show_copy_button=True,
110
+ bubble_full_width=False,
111
+ )
112
+ with gr.Row():
113
+ user_input = gr.Textbox(
114
+ placeholder="Type your message here...",
115
+ scale=4,
116
+ show_label=False,
117
+ container=False
118
+ )
119
+ send_btn = gr.Button("πŸ“€ Send", variant="primary", scale=1)
120
+
121
+ with gr.Row():
122
+ clear_btn = gr.Button("πŸ—‘οΈ Clear Chat")
123
+ regenerate_btn = gr.Button("πŸ”„ Regenerate")
124
+
125
+ with gr.Column(scale=1):
126
+ gr.Markdown("### πŸ”§ Quick Settings")
127
+
128
+ api_key_input = gr.Textbox(
129
+ label="πŸ”‘ OpenAI API Key",
130
+ placeholder="sk-...",
131
+ type="password"
132
+ )
133
+ api_status = gr.Textbox(
134
+ label="API Status",
135
+ interactive=False,
136
+ value="❌ No API key provided"
137
+ )
138
+
139
+ model_dropdown = gr.Dropdown(
140
+ choices=AVAILABLE_MODELS,
141
+ value="gpt-3.5-turbo",
142
+ label="πŸ€– Model"
143
+ )
144
+
145
+ max_tokens_slider = gr.Slider(
146
+ minimum=50,
147
+ maximum=4096,
148
+ value=150,
149
+ step=10,
150
+ label="πŸ“ Max Tokens"
151
+ )
152
+
153
+ temperature_slider = gr.Slider(
154
+ minimum=0.0,
155
+ maximum=1.0,
156
+ value=0.7,
157
+ step=0.1,
158
+ label="🌑️ Temperature"
159
+ )
160
+
161
+ gr.Markdown("### πŸ“Š Current Settings")
162
+ current_settings = gr.Textbox(
163
+ value="Model: gpt-3.5-turbo\nTokens: 150\nTemp: 0.7",
164
+ label="Active Configuration",
165
+ interactive=False,
166
+ lines=3
167
+ )
168
+ with gr.Tab("βš™οΈ Advanced Settings"):
169
+ gr.Markdown("### 🎯 System Prompt Configuration")
170
+ system_prompt_input = gr.Textbox(
171
+ label="System Prompt",
172
+ value="You are a helpful AI assistant. Respond in a friendly and informative manner.",
173
+ lines=5,
174
+ placeholder="Enter custom system prompt..."
175
+ )
176
+
177
+ gr.Markdown("### πŸ“š Custom Data Integration")
178
+ custom_data_input = gr.Textbox(
179
+ label="Custom Training Data",
180
+ lines=10,
181
+ placeholder="Enter custom data, FAQs, or domain-specific information..."
182
+ )
183
+
184
+ with gr.Row():
185
+ update_settings_btn = gr.Button("βœ… Update Settings")
186
+ integrate_data_btn = gr.Button("πŸ“Š Integrate Custom Data")
187
+ reset_prompt_btn = gr.Button("πŸ”„ Reset to Default")
188
+
189
+ settings_status = gr.Textbox(
190
+ label="Settings Status",
191
+ interactive=False
192
+ )
193
+
194
+ gr.Markdown("### 🎭 Preset System Prompts")
195
+ with gr.Row():
196
+ preset_customer_support = gr.Button("πŸ‘₯ Customer Support")
197
+ preset_tutor = gr.Button("πŸŽ“ Educational Tutor")
198
+ preset_creative = gr.Button("✨ Creative Assistant")
199
+ preset_technical = gr.Button("πŸ”§ Technical Writer")
200
+
201
+
202
+
203
+
204
+