Reality123b commited on
Commit
e319620
·
verified ·
1 Parent(s): 95cfa66

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -40
app.py CHANGED
@@ -2,7 +2,7 @@ import os
2
  import base64
3
  import requests
4
  import gradio as gr
5
- from huggingface_hub import InferenceClient
6
 
7
  class XylariaChat:
8
  def __init__(self):
@@ -11,9 +11,9 @@ class XylariaChat:
11
  if not self.hf_token:
12
  raise ValueError("HuggingFace token not found in environment variables")
13
 
14
- # Initialize the inference client
15
  self.client = InferenceClient(
16
- model=os.getenv("MODEL_NAME"),
17
  api_key=self.hf_token
18
  )
19
 
@@ -26,16 +26,16 @@ class XylariaChat:
26
  self.persistent_memory = {}
27
 
28
  # System prompt with more detailed instructions
29
- self.system_prompt = """You are a helpful and harmless assistant. You are Xylaria developed by Sk Md Saad Amin(india, 12 year old). You should think step-by-step.
30
- """
31
 
32
  def store_information(self, key, value):
33
  """Store important information in persistent memory"""
34
  self.persistent_memory[key] = value
 
35
 
36
  def retrieve_information(self, key):
37
  """Retrieve information from persistent memory"""
38
- return self.persistent_memory.get(key)
39
 
40
  def reset_conversation(self):
41
  """
@@ -46,9 +46,8 @@ class XylariaChat:
46
  self.conversation_history = []
47
  self.persistent_memory.clear()
48
 
49
- # Clear API-side memory by resetting the conversation
50
  try:
51
- # Attempt to clear any API-side session or context
52
  self.client = InferenceClient(
53
  model="Qwen/QwQ-32B-Preview",
54
  api_key=self.hf_token
@@ -101,32 +100,57 @@ class XylariaChat:
101
  return f"Error processing image: {str(e)}"
102
 
103
  def get_response(self, user_input, image=None):
104
- # Prepare messages with conversation context and persistent memory
105
- messages = [
106
- {"role": "system", "content": self.system_prompt},
107
- ]
108
-
109
- # Add persistent memory context if available
110
- if self.persistent_memory:
111
- memory_context = "Remembered Information:\n" + "\n".join(
112
- [f"{k}: {v}" for k, v in self.persistent_memory.items()]
113
- )
114
- messages.append({"role": "system", "content": memory_context})
115
-
116
- # Add conversation history
117
- messages.extend(self.conversation_history)
118
-
119
- # Process image if uploaded
120
- if image:
121
- image_caption = self.caption_image(image)
122
- user_input = f"Image description: {image_caption}\n\nUser's message: {user_input}"
123
 
124
- # Add user input
125
- messages.append({"role": "user", "content": user_input})
 
126
 
127
- # Generate response with streaming
 
 
128
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  stream = self.client.chat.completions.create(
 
130
  messages=messages,
131
  temperature=0.5,
132
  max_tokens=10240,
@@ -137,6 +161,7 @@ class XylariaChat:
137
  return stream
138
 
139
  except Exception as e:
 
140
  return f"Error generating response: {str(e)}"
141
 
142
  def create_interface(self):
@@ -153,14 +178,18 @@ class XylariaChat:
153
  updated_history = chat_history + [[message, ""]]
154
 
155
  # Streaming output
156
- for chunk in response_stream:
157
- if chunk.choices[0].delta.content:
158
- chunk_content = chunk.choices[0].delta.content
159
- full_response += chunk_content
160
-
161
- # Update the last message in chat history with partial response
162
- updated_history[-1][1] = full_response
163
- yield "", updated_history, None
 
 
 
 
164
 
165
  # Update conversation history
166
  self.conversation_history.append(
@@ -197,10 +226,10 @@ class XylariaChat:
197
  # Chat interface with improved styling
198
  with gr.Column():
199
  chatbot = gr.Chatbot(
200
- label="Xylaria 1.4 Senoa",
201
  height=500,
202
  show_copy_button=True,
203
- type="messages" # Updated to use messages type
204
  )
205
 
206
  # Input row with improved layout and image upload
 
2
  import base64
3
  import requests
4
  import gradio as gr
5
+ from huggingface_hub import InferenceClient, ChatMessage
6
 
7
  class XylariaChat:
8
  def __init__(self):
 
11
  if not self.hf_token:
12
  raise ValueError("HuggingFace token not found in environment variables")
13
 
14
+ # Initialize the inference client with the Qwen model
15
  self.client = InferenceClient(
16
+ model="Qwen/QwQ-32B-Preview",
17
  api_key=self.hf_token
18
  )
19
 
 
26
  self.persistent_memory = {}
27
 
28
  # System prompt with more detailed instructions
29
+ self.system_prompt = """You are a helpful and harmless assistant. You are Xylaria developed by Sk Md Saad Amin(india, 12 year old). You should think step-by-step."""
 
30
 
31
  def store_information(self, key, value):
32
  """Store important information in persistent memory"""
33
  self.persistent_memory[key] = value
34
+ return f"Stored: {key} = {value}"
35
 
36
  def retrieve_information(self, key):
37
  """Retrieve information from persistent memory"""
38
+ return self.persistent_memory.get(key, "No information found for this key.")
39
 
40
  def reset_conversation(self):
41
  """
 
46
  self.conversation_history = []
47
  self.persistent_memory.clear()
48
 
49
+ # Reinitialize the client
50
  try:
 
51
  self.client = InferenceClient(
52
  model="Qwen/QwQ-32B-Preview",
53
  api_key=self.hf_token
 
100
  return f"Error processing image: {str(e)}"
101
 
102
  def get_response(self, user_input, image=None):
103
+ """
104
+ Generate a response using chat completions with improved error handling
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
 
106
+ Args:
107
+ user_input (str): User's message
108
+ image (optional): Uploaded image
109
 
110
+ Returns:
111
+ Stream of chat completions or error message
112
+ """
113
  try:
114
+ # Prepare messages with conversation context and persistent memory
115
+ messages = []
116
+
117
+ # Add system prompt as first message
118
+ messages.append(ChatMessage(
119
+ role="system",
120
+ content=self.system_prompt
121
+ ))
122
+
123
+ # Add persistent memory context if available
124
+ if self.persistent_memory:
125
+ memory_context = "Remembered Information:\n" + "\n".join(
126
+ [f"{k}: {v}" for k, v in self.persistent_memory.items()]
127
+ )
128
+ messages.append(ChatMessage(
129
+ role="system",
130
+ content=memory_context
131
+ ))
132
+
133
+ # Convert existing conversation history to ChatMessage objects
134
+ for msg in self.conversation_history:
135
+ messages.append(ChatMessage(
136
+ role=msg['role'],
137
+ content=msg['content']
138
+ ))
139
+
140
+ # Process image if uploaded
141
+ if image:
142
+ image_caption = self.caption_image(image)
143
+ user_input = f"Image description: {image_caption}\n\nUser's message: {user_input}"
144
+
145
+ # Add user input
146
+ messages.append(ChatMessage(
147
+ role="user",
148
+ content=user_input
149
+ ))
150
+
151
+ # Generate response with streaming
152
  stream = self.client.chat.completions.create(
153
+ model="Qwen/QwQ-32B-Preview",
154
  messages=messages,
155
  temperature=0.5,
156
  max_tokens=10240,
 
161
  return stream
162
 
163
  except Exception as e:
164
+ print(f"Detailed error in get_response: {e}")
165
  return f"Error generating response: {str(e)}"
166
 
167
  def create_interface(self):
 
178
  updated_history = chat_history + [[message, ""]]
179
 
180
  # Streaming output
181
+ try:
182
+ for chunk in response_stream:
183
+ if chunk.choices and chunk.choices[0].delta and chunk.choices[0].delta.content:
184
+ chunk_content = chunk.choices[0].delta.content
185
+ full_response += chunk_content
186
+
187
+ # Update the last message in chat history with partial response
188
+ updated_history[-1][1] = full_response
189
+ yield "", updated_history, None
190
+ except Exception as e:
191
+ print(f"Streaming error: {e}")
192
+ yield "", updated_history + [["", f"Error during response: {e}"]], None
193
 
194
  # Update conversation history
195
  self.conversation_history.append(
 
226
  # Chat interface with improved styling
227
  with gr.Column():
228
  chatbot = gr.Chatbot(
229
+ label="Xylaria 1.4 Senoa (Qwen Model)",
230
  height=500,
231
  show_copy_button=True,
232
+ type="messages"
233
  )
234
 
235
  # Input row with improved layout and image upload