shukdevdattaEX commited on
Commit
5e93423
·
verified ·
1 Parent(s): 6262341

Upload Doc.ipynb

Browse files
Files changed (1) hide show
  1. Doc.ipynb +341 -0
Doc.ipynb ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "528b6777",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Complete Chatbot Application Code Explanation\n",
9
+ "\n",
10
+ "## Overview: What This Application Does\n",
11
+ "\n",
12
+ "This code creates a sophisticated web-based chatbot interface using Gradio (a Python library for building user interfaces) that connects to OpenAI's language models. Think of it as building your own ChatGPT-like interface with customizable features.\n",
13
+ "\n",
14
+ "## Import Section: Setting Up the Tools\n",
15
+ "\n",
16
+ "```python\n",
17
+ "import gradio as gr\n",
18
+ "import openai\n",
19
+ "import json\n",
20
+ "import os\n",
21
+ "import time\n",
22
+ "from typing import List, Tuple, Optional\n",
23
+ "import requests\n",
24
+ "from datetime import datetime\n",
25
+ "```\n",
26
+ "\n",
27
+ "Let me explain what each import does:\n",
28
+ "- `gradio as gr`: This is the main library that creates the web interface with buttons, text boxes, and chat windows\n",
29
+ "- `openai`: The official OpenAI library to communicate with their AI models like GPT-3.5 and GPT-4\n",
30
+ "- `json`: Handles saving and loading conversation data in a structured format\n",
31
+ "- `os`: Interacts with the operating system (like creating folders for saved files)\n",
32
+ "- `time`: Could be used for adding delays or timestamps (though not heavily used in this code)\n",
33
+ "- `typing`: Provides type hints to make the code clearer about what kind of data functions expect\n",
34
+ "- `requests`: Makes HTTP requests to web services (imported but not actively used here)\n",
35
+ "- `datetime`: Handles dates and times for timestamping conversations\n",
36
+ "\n",
37
+ "## The ChatbotManager Class: The Brain of the Operation\n",
38
+ "\n",
39
+ "The `ChatbotManager` class is like the control center that manages everything about the chatbot. Let's break it down:\n",
40
+ "\n",
41
+ "### Initialization Method\n",
42
+ "\n",
43
+ "```python\n",
44
+ "def __init__(self):\n",
45
+ " self.conversation_history = []\n",
46
+ " self.current_api_key = None\n",
47
+ " self.current_model = \"gpt-3.5-turbo\"\n",
48
+ " self.system_prompt = \"You are a helpful AI assistant. Respond in a friendly and informative manner.\"\n",
49
+ " self.max_tokens = 150\n",
50
+ " self.temperature = 0.7\n",
51
+ "```\n",
52
+ "\n",
53
+ "When a `ChatbotManager` object is created, it sets up default values:\n",
54
+ "- `conversation_history`: An empty list that will store all the chat messages\n",
55
+ "- `current_api_key`: Starts as None until the user provides their OpenAI API key\n",
56
+ "- `current_model`: Defaults to GPT-3.5-turbo (a fast, cost-effective model)\n",
57
+ "- `system_prompt`: The instructions that tell the AI how to behave\n",
58
+ "- `max_tokens`: Limits response length to 150 tokens (roughly 100-120 words)\n",
59
+ "- `temperature`: Controls creativity (0.7 means moderately creative responses)\n",
60
+ "\n",
61
+ "### API Key Validation Method\n",
62
+ "\n",
63
+ "```python\n",
64
+ "def set_api_key(self, api_key: str) -> str:\n",
65
+ " if not api_key.strip():\n",
66
+ " return \"❌ Please enter a valid API key\"\n",
67
+ " \n",
68
+ " self.current_api_key = api_key.strip()\n",
69
+ " openai.api_key = self.current_api_key\n",
70
+ " \n",
71
+ " try:\n",
72
+ " openai.Model.list()\n",
73
+ " return \"✅ API key validated successfully!\"\n",
74
+ " except Exception as e:\n",
75
+ " return f\"❌ Invalid API key: {str(e)}\"\n",
76
+ "```\n",
77
+ "\n",
78
+ "This method is like a security guard checking if someone has the right credentials:\n",
79
+ "1. First, it checks if the API key isn't empty (using `strip()` to remove spaces)\n",
80
+ "2. If valid, it stores the key and tells the OpenAI library to use it\n",
81
+ "3. It then tests the key by trying to list available models\n",
82
+ "4. If the test succeeds, it returns a success message\n",
83
+ "5. If it fails, it catches the error and returns a failure message\n",
84
+ "\n",
85
+ "### Settings Update Method\n",
86
+ "\n",
87
+ "```python\n",
88
+ "def update_settings(self, model: str, system_prompt: str, max_tokens: int, temperature: float) -> str:\n",
89
+ " self.current_model = model\n",
90
+ " self.system_prompt = system_prompt\n",
91
+ " self.max_tokens = max_tokens\n",
92
+ " self.temperature = temperature\n",
93
+ " return f\"✅ Settings updated: Model={model}, Max Tokens={max_tokens}, Temperature={temperature}\"\n",
94
+ "```\n",
95
+ "\n",
96
+ "This is straightforward - it updates all the chatbot's configuration settings and returns a confirmation message showing what was changed.\n",
97
+ "\n",
98
+ "### Custom Data Integration Method\n",
99
+ "\n",
100
+ "```python\n",
101
+ "def preprocess_data(self, data_text: str) -> str:\n",
102
+ " if not data_text.strip():\n",
103
+ " return \"No custom data provided\"\n",
104
+ " \n",
105
+ " base_prompt = \"You are a helpful AI assistant. Respond in a friendly and informative manner.\"\n",
106
+ " self.system_prompt = base_prompt + f\"\\n\\nAdditional Context:\\n{data_text}\"\n",
107
+ " return f\"✅ Custom data integrated ({len(data_text)} characters)\"\n",
108
+ "```\n",
109
+ "\n",
110
+ "This method allows users to add custom information to the chatbot's knowledge. It takes the default system prompt and appends the custom data, creating a more specialized AI assistant that knows about specific topics or company information.\n",
111
+ "\n",
112
+ "### The Core Response Generation Method\n",
113
+ "\n",
114
+ "```python\n",
115
+ "def generate_response(self, user_input: str, history: List[Tuple[str, str]]) -> Tuple[str, List[Tuple[str, str]]]:\n",
116
+ " if not self.current_api_key:\n",
117
+ " return \"❌ Please set your API key first!\", history\n",
118
+ " \n",
119
+ " if not user_input.strip():\n",
120
+ " return \"Please enter a message.\", history\n",
121
+ " \n",
122
+ " try:\n",
123
+ " messages = [{\"role\": \"system\", \"content\": self.system_prompt}]\n",
124
+ " \n",
125
+ " for user_msg, assistant_msg in history:\n",
126
+ " messages.append({\"role\": \"user\", \"content\": user_msg})\n",
127
+ " messages.append({\"role\": \"assistant\", \"content\": assistant_msg})\n",
128
+ " \n",
129
+ " messages.append({\"role\": \"user\", \"content\": user_input})\n",
130
+ " \n",
131
+ " response = openai.ChatCompletion.create(\n",
132
+ " model=self.current_model,\n",
133
+ " messages=messages,\n",
134
+ " max_tokens=self.max_tokens,\n",
135
+ " temperature=self.temperature,\n",
136
+ " n=1,\n",
137
+ " stop=None,\n",
138
+ " )\n",
139
+ " \n",
140
+ " assistant_response = response.choices[0].message.content.strip()\n",
141
+ " history.append((user_input, assistant_response))\n",
142
+ " \n",
143
+ " return assistant_response, history\n",
144
+ " \n",
145
+ " except Exception as e:\n",
146
+ " error_msg = f\"❌ Error generating response: {str(e)}\"\n",
147
+ " return error_msg, history\n",
148
+ "```\n",
149
+ "\n",
150
+ "This is the heart of the chatbot. Here's what happens step by step:\n",
151
+ "\n",
152
+ "1. **Safety Checks**: First, it verifies that an API key exists and the user actually typed something\n",
153
+ "2. **Message Formatting**: It creates a list of messages in the format OpenAI expects:\n",
154
+ " - Starts with the system prompt (tells the AI how to behave)\n",
155
+ " - Adds all previous conversation history in order\n",
156
+ " - Adds the new user message\n",
157
+ "3. **API Call**: It sends all this information to OpenAI's servers using the specified model and settings\n",
158
+ "4. **Response Processing**: It extracts the AI's response and adds both the user input and AI response to the conversation history\n",
159
+ "5. **Error Handling**: If anything goes wrong, it catches the error and returns a helpful message\n",
160
+ "\n",
161
+ "### Utility Methods\n",
162
+ "\n",
163
+ "```python\n",
164
+ "def clear_conversation(self) -> Tuple[str, List[Tuple[str, str]]]:\n",
165
+ " self.conversation_history = []\n",
166
+ " return \"\", []\n",
167
+ "\n",
168
+ "def export_conversation(self, history: List[Tuple[str, str]]) -> Tuple[str, Optional[str]]:\n",
169
+ " # Creates a JSON file with the conversation data\n",
170
+ "```\n",
171
+ "\n",
172
+ "These methods handle housekeeping tasks like clearing the chat and saving conversations to files.\n",
173
+ "\n",
174
+ "## Model Configuration\n",
175
+ "\n",
176
+ "```python\n",
177
+ "AVAILABLE_MODELS = [\n",
178
+ " \"gpt-3.5-turbo\",\n",
179
+ " \"gpt-3.5-turbo-16k\",\n",
180
+ " \"gpt-4\",\n",
181
+ " \"gpt-4-32k\",\n",
182
+ " \"gpt-4-0613\",\n",
183
+ " \"gpt-4-32k-0613\"\n",
184
+ "]\n",
185
+ "```\n",
186
+ "\n",
187
+ "This list defines which AI models users can choose from. Each has different capabilities:\n",
188
+ "- GPT-3.5 models are faster and cheaper\n",
189
+ "- GPT-4 models are more capable but slower and more expensive\n",
190
+ "- The numbers (16k, 32k) refer to how much text they can process at once\n",
191
+ "\n",
192
+ "## The User Interface Creation\n",
193
+ "\n",
194
+ "The `create_interface()` function builds the entire web interface using Gradio. Think of it as designing a website layout:\n",
195
+ "\n",
196
+ "### Main Structure\n",
197
+ "\n",
198
+ "```python\n",
199
+ "with gr.Blocks(title=\"LLM-Based Chatbot\", theme=gr.themes.Ocean()) as demo:\n",
200
+ "```\n",
201
+ "\n",
202
+ "This creates the main container with a title and applies a blue ocean theme for visual appeal.\n",
203
+ "\n",
204
+ "### Chat Interface Tab\n",
205
+ "\n",
206
+ "The first tab contains the main chat functionality:\n",
207
+ "\n",
208
+ "```python\n",
209
+ "chatbot_interface = gr.Chatbot(\n",
210
+ " label=\"Conversation\",\n",
211
+ " height=400,\n",
212
+ " show_label=True,\n",
213
+ " avatar_images=(\"user.png\", \"assistant.png\"),\n",
214
+ " show_copy_button=True,\n",
215
+ " bubble_full_width=False,\n",
216
+ ")\n",
217
+ "```\n",
218
+ "\n",
219
+ "This creates the chat window where conversations appear, with customizable height, avatars for user and AI, and a copy button for responses.\n",
220
+ "\n",
221
+ "### Input Components\n",
222
+ "\n",
223
+ "```python\n",
224
+ "user_input = gr.Textbox(\n",
225
+ " placeholder=\"Type your message here...\",\n",
226
+ " scale=4,\n",
227
+ " show_label=False,\n",
228
+ " container=False\n",
229
+ ")\n",
230
+ "send_btn = gr.Button(\"📤 Send\", variant=\"primary\", scale=1)\n",
231
+ "```\n",
232
+ "\n",
233
+ "These create the text input box where users type messages and the send button to submit them.\n",
234
+ "\n",
235
+ "### Settings Panel\n",
236
+ "\n",
237
+ "The right side contains controls for configuring the chatbot:\n",
238
+ "- API key input (password type for security)\n",
239
+ "- Model selection dropdown\n",
240
+ "- Token limit slider\n",
241
+ "- Temperature slider for creativity control\n",
242
+ "- Status displays showing current settings\n",
243
+ "\n",
244
+ "### Advanced Settings Tab\n",
245
+ "\n",
246
+ "This tab provides more sophisticated configuration options:\n",
247
+ "- Custom system prompt editing\n",
248
+ "- Custom data integration\n",
249
+ "- Preset prompt buttons for different use cases\n",
250
+ "- Settings management buttons\n",
251
+ "\n",
252
+ "## Event Handling: Making It Interactive\n",
253
+ "\n",
254
+ "The code then connects user actions to functions using event handlers:\n",
255
+ "\n",
256
+ "```python\n",
257
+ "send_btn.click(\n",
258
+ " handle_chat,\n",
259
+ " inputs=[user_input, chatbot_interface],\n",
260
+ " outputs=[chatbot_interface, user_input]\n",
261
+ ")\n",
262
+ "```\n",
263
+ "\n",
264
+ "This tells Gradio: \"When the send button is clicked, run the `handle_chat` function with the current user input and chat history, then update the chat display and clear the input box.\"\n",
265
+ "\n",
266
+ "### Handler Functions\n",
267
+ "\n",
268
+ "The handler functions act as translators between the user interface and the ChatbotManager:\n",
269
+ "\n",
270
+ "```python\n",
271
+ "def handle_chat(user_input, history):\n",
272
+ " if not user_input.strip():\n",
273
+ " return history or [], \"\"\n",
274
+ " \n",
275
+ " response, updated_history = chatbot.generate_response(user_input, history or [])\n",
276
+ " return updated_history, \"\"\n",
277
+ "```\n",
278
+ "\n",
279
+ "This function takes what the user typed, passes it to the chatbot manager, and returns the updated conversation to display in the interface.\n",
280
+ "\n",
281
+ "## Advanced Features\n",
282
+ "\n",
283
+ "### Preset System Prompts\n",
284
+ "\n",
285
+ "The application includes predefined prompts for different use cases:\n",
286
+ "- Customer Support: Professional, solution-focused responses\n",
287
+ "- Educational Tutor: Patient, explanatory teaching style\n",
288
+ "- Creative Assistant: Imaginative, inspiring writing help\n",
289
+ "- Technical Writer: Clear, precise documentation style\n",
290
+ "\n",
291
+ "### Data Integration\n",
292
+ "\n",
293
+ "Users can add custom data to make the chatbot an expert on specific topics, like company FAQs or technical documentation.\n",
294
+ "\n",
295
+ "### Conversation Export\n",
296
+ "\n",
297
+ "The system can save conversations as JSON files with timestamps and metadata for later analysis or record-keeping.\n",
298
+ "\n",
299
+ "## Launch Configuration\n",
300
+ "\n",
301
+ "```python\n",
302
+ "if __name__ == \"__main__\":\n",
303
+ " demo = create_interface()\n",
304
+ " demo.launch(share=True)\n",
305
+ "```\n",
306
+ "\n",
307
+ "This final section starts the application:\n",
308
+ "- Creates the interface\n",
309
+ "- Launches it with `share=True`, which creates a public URL that others can access\n",
310
+ "- The application runs on your computer but can be accessed from anywhere via the generated link\n",
311
+ "\n",
312
+ "## How It All Works Together\n",
313
+ "\n",
314
+ "When you run this code, here's the complete flow:\n",
315
+ "\n",
316
+ "1. **Startup**: The application creates a ChatbotManager instance and builds the web interface\n",
317
+ "2. **User Setup**: User enters their OpenAI API key, which gets validated\n",
318
+ "3. **Configuration**: User can adjust model settings, system prompts, and add custom data\n",
319
+ "4. **Conversation**: User types a message, clicks send\n",
320
+ "5. **Processing**: The system formats the message with conversation history and sends it to OpenAI\n",
321
+ "6. **Response**: OpenAI returns a response, which gets displayed in the chat interface\n",
322
+ "7. **Continuation**: The conversation continues with full context maintained\n",
323
+ "\n",
324
+ "This creates a fully functional, customizable chatbot interface that rivals commercial applications while giving users complete control over the AI's behavior and capabilities."
325
+ ]
326
+ },
327
+ {
328
+ "cell_type": "markdown",
329
+ "id": "07498f29",
330
+ "metadata": {},
331
+ "source": []
332
+ }
333
+ ],
334
+ "metadata": {
335
+ "language_info": {
336
+ "name": "python"
337
+ }
338
+ },
339
+ "nbformat": 4,
340
+ "nbformat_minor": 5
341
+ }