TKM03 commited on
Commit
7517204
·
verified ·
1 Parent(s): 2287c12

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +177 -48
app.py CHANGED
@@ -1,64 +1,193 @@
1
  import gradio as gr
 
 
2
  from huggingface_hub import InferenceClient
 
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
 
 
 
 
 
 
 
9
 
 
10
  def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
  top_p,
 
17
  ):
18
- messages = [{"role": "system", "content": system_message}]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
 
 
25
 
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
 
 
62
 
63
  if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import logging
3
+ import os
4
  from huggingface_hub import InferenceClient
5
+ from datetime import datetime
6
+ import uuid
7
+ import json
8
 
9
+ # Configure logging
10
+ logging.basicConfig(
11
+ level=logging.INFO,
12
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
13
+ handlers=[
14
+ logging.FileHandler("chatbot_logs.log"),
15
+ logging.StreamHandler()
16
+ ]
17
+ )
18
+ logger = logging.getLogger("CompanyChatbot")
19
+
20
+ # Environment variables (for production use)
21
+ HF_MODEL = os.environ.get("HF_MODEL", "HuggingFaceH4/zephyr-7b-beta")
22
+ HF_API_TOKEN = os.environ.get("HF_API_TOKEN", None) # Set your API token as env variable
23
+ COMPANY_NAME = os.environ.get("COMPANY_NAME", "Your Company")
24
+ DEFAULT_SYSTEM_PROMPT = os.environ.get("DEFAULT_SYSTEM_PROMPT",
25
+ f"You are {COMPANY_NAME}'s professional AI assistant. Be helpful, accurate, and concise.")
26
+
27
+ # Initialize the client
28
+ try:
29
+ client = InferenceClient(HF_MODEL, token=HF_API_TOKEN)
30
+ logger.info(f"Successfully initialized InferenceClient with model: {HF_MODEL}")
31
+ except Exception as e:
32
+ logger.error(f"Failed to initialize InferenceClient: {str(e)}")
33
+ raise RuntimeError(f"Failed to initialize the model. Please check your configuration: {str(e)}")
34
 
35
+ # Conversation tracking
36
+ def save_conversation(user_id, conversation):
37
+ filename = f"conversations/{user_id}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
38
+ os.makedirs(os.path.dirname(filename), exist_ok=True)
39
+ with open(filename, 'w') as f:
40
+ json.dump(conversation, f)
41
+ logger.info(f"Saved conversation for user {user_id}")
42
 
43
+ # Main chat function
44
  def respond(
45
+ message,
46
+ history: list[tuple[str, str]],
47
+ system_message,
48
+ max_tokens,
49
+ temperature,
50
  top_p,
51
+ user_id
52
  ):
53
+ if not message.strip():
54
+ return "I'm sorry, I didn't receive any input. How can I help you today?"
55
+
56
+ # Log the incoming request
57
+ logger.info(f"User {user_id} sent message - Length: {len(message)}")
58
+
59
+ try:
60
+ messages = [{"role": "system", "content": system_message}]
61
+
62
+ # Build conversation history
63
+ for user_msg, assistant_msg in history:
64
+ if user_msg:
65
+ messages.append({"role": "user", "content": user_msg})
66
+ if assistant_msg:
67
+ messages.append({"role": "assistant", "content": assistant_msg})
68
+
69
+ messages.append({"role": "user", "content": message})
70
+
71
+ # Generate response
72
+ full_response = ""
73
+ start_time = datetime.now()
74
+
75
+ for message_chunk in client.chat_completion(
76
+ messages,
77
+ max_tokens=max_tokens,
78
+ stream=True,
79
+ temperature=temperature,
80
+ top_p=top_p,
81
+ ):
82
+ token = message_chunk.choices[0].delta.content
83
+ full_response += token if token else ""
84
+ yield full_response
85
+
86
+ # Log completion
87
+ time_taken = (datetime.now() - start_time).total_seconds()
88
+ logger.info(f"Response generated for user {user_id} in {time_taken:.2f}s - Length: {len(full_response)}")
89
+
90
+ # Save conversation for audit/analytics
91
+ conversation_data = {
92
+ "timestamp": datetime.now().isoformat(),
93
+ "user_id": user_id,
94
+ "messages": messages,
95
+ "response": full_response,
96
+ "parameters": {
97
+ "max_tokens": max_tokens,
98
+ "temperature": temperature,
99
+ "top_p": top_p
100
+ },
101
+ "time_taken": time_taken
102
+ }
103
+ save_conversation(user_id, conversation_data)
104
+
105
+ except Exception as e:
106
+ error_msg = f"An error occurred: {str(e)}"
107
+ logger.error(f"Error generating response for user {user_id}: {str(e)}")
108
+ return error_msg
109
 
110
+ # Authentication function (replace with your actual auth system)
111
+ def authenticate(username, password):
112
+ # In production, this should check against your company's auth system
113
+ valid_credentials = {"admin": "admin123", "user": "user123"} # Example only
114
+
115
+ if username in valid_credentials and valid_credentials[username] == password:
116
+ return True, str(uuid.uuid4()) # Generate user session ID
117
+ return False, None
118
 
119
+ # Login interface
120
+ def login(username, password):
121
+ success, user_id = authenticate(username, password)
122
+ if success:
123
+ return gr.update(visible=False), gr.update(visible=True), user_id
124
+ else:
125
+ return gr.update(visible=True), gr.update(visible=False), None
 
 
 
 
 
 
 
 
126
 
127
+ # Main application
128
+ with gr.Blocks(css="styles.css", title=f"{COMPANY_NAME} AI Assistant") as demo:
129
+ user_id = gr.State(None)
130
+
131
+ with gr.Row():
132
+ gr.Markdown(f"# {COMPANY_NAME} AI Assistant")
133
+
134
+ with gr.Group(visible=True) as login_group:
135
+ gr.Markdown("### Please log in to continue")
136
+ username = gr.Textbox(label="Username")
137
+ password = gr.Textbox(label="Password", type="password")
138
+ login_button = gr.Button("Login")
139
+
140
+ with gr.Group(visible=False) as chat_group:
141
+ chatbot = gr.ChatInterface(
142
+ respond,
143
+ additional_inputs=[
144
+ gr.Textbox(value=DEFAULT_SYSTEM_PROMPT, label="System Instructions"),
145
+ gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max Response Length"),
146
+ gr.Slider(minimum=0.1, maximum=1.0, value=0.7, step=0.1, label="Temperature (Creativity)"),
147
+ gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (Variation)"),
148
+ user_id
149
+ ],
150
+ analytics_enabled=True,
151
+ title=None,
152
+ )
153
+
154
+ login_button.click(
155
+ login,
156
+ inputs=[username, password],
157
+ outputs=[login_group, chat_group, user_id]
158
+ )
159
 
160
+ # For CSS styling
161
+ css = """
162
+ body {
163
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
164
+ background-color: #f9f9f9;
165
+ }
166
+ .gradio-container {
167
+ max-width: 1200px !important;
168
+ margin: auto;
169
+ }
170
+ .footer {
171
+ text-align: center;
172
+ margin-top: 20px;
173
+ color: #666;
174
+ font-size: 0.8em;
175
+ }
176
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177
 
178
+ with open("styles.css", "w") as f:
179
+ f.write(css)
180
 
181
  if __name__ == "__main__":
182
+ # Check if we're running in production
183
+ if os.environ.get("PRODUCTION", "false").lower() == "true":
184
+ demo.launch(
185
+ server_name="0.0.0.0",
186
+ server_port=int(os.environ.get("PORT", 7860)),
187
+ share=False,
188
+ show_error=False,
189
+ auth=None, # We handle auth in the app
190
+ )
191
+ else:
192
+ # Development mode
193
+ demo.launch(share=True)