artecnosomatic commited on
Commit
42a68b0
·
1 Parent(s): 8c83fc8

Improve conversation quality: better model, enhanced parameters, improved memory context, and natural prompts

Browse files
Files changed (2) hide show
  1. app.py +27 -15
  2. chat_interface.py +28 -6
app.py CHANGED
@@ -75,23 +75,30 @@ class MemoryChatApp:
75
  if any(word in user_input.lower() for word in ["remember", "note", "save"]):
76
  return user_input
77
 
78
- # Extract personal information
79
  personal_info = []
80
  if "my name is" in user_input.lower():
81
- personal_info.append("User shared their name")
 
 
82
  if "i live in" in user_input.lower():
83
- personal_info.append("User shared their location")
 
84
  if "i work at" in user_input.lower():
85
- personal_info.append("User shared their workplace")
 
86
  if "i study" in user_input.lower():
87
- personal_info.append("User shared their studies")
 
88
  if "my birthday" in user_input.lower():
89
- personal_info.append("User shared their birthday")
 
90
  if "my favorite" in user_input.lower():
91
- personal_info.append("User shared a favorite thing")
 
92
 
93
  if personal_info:
94
- return f"User mentioned: {', '.join(personal_info)}. Details: {user_input}"
95
 
96
  # Default to user input if no specific patterns found
97
  return user_input
@@ -114,17 +121,17 @@ class MemoryChatApp:
114
  self.conversation_history.append({"role": "user", "content": user_input})
115
 
116
  # Retrieve relevant memories to provide context
117
- relevant_memories = self.memory_manager.retrieve_memories(user_input, k=3)
118
 
119
- # Build context from memories
120
  context = ""
121
  if relevant_memories:
122
- context = "Relevant memories:\n"
123
- for memory in relevant_memories[:2]: # Limit to 2 most relevant
124
- context += f"- {memory['content']}\n"
125
  context += "\n"
126
 
127
- # Build the prompt with context and conversation history
128
  prompt = self.build_prompt(user_input, context)
129
 
130
  # Generate AI response
@@ -157,7 +164,12 @@ class MemoryChatApp:
157
  Returns:
158
  The prompt to send to the AI model
159
  """
160
- prompt = f"{context}Human: {user_input}\nAI: "
 
 
 
 
 
161
  return prompt
162
 
163
  def get_current_time(self) -> str:
 
75
  if any(word in user_input.lower() for word in ["remember", "note", "save"]):
76
  return user_input
77
 
78
+ # Extract personal information with more detail
79
  personal_info = []
80
  if "my name is" in user_input.lower():
81
+ # Extract the actual name
82
+ name_part = user_input.lower().split("my name is")[-1].strip()
83
+ personal_info.append(f"User's name is {name_part}")
84
  if "i live in" in user_input.lower():
85
+ location_part = user_input.lower().split("i live in")[-1].strip()
86
+ personal_info.append(f"User lives in {location_part}")
87
  if "i work at" in user_input.lower():
88
+ work_part = user_input.lower().split("i work at")[-1].strip()
89
+ personal_info.append(f"User works at {work_part}")
90
  if "i study" in user_input.lower():
91
+ study_part = user_input.lower().split("i study")[-1].strip()
92
+ personal_info.append(f"User studies {study_part}")
93
  if "my birthday" in user_input.lower():
94
+ birthday_part = user_input.lower().split("my birthday")[-1].strip()
95
+ personal_info.append(f"User's birthday is {birthday_part}")
96
  if "my favorite" in user_input.lower():
97
+ favorite_part = user_input.lower().split("my favorite")[-1].strip()
98
+ personal_info.append(f"User's favorite {favorite_part}")
99
 
100
  if personal_info:
101
+ return f"Personal info: {', '.join(personal_info)}"
102
 
103
  # Default to user input if no specific patterns found
104
  return user_input
 
121
  self.conversation_history.append({"role": "user", "content": user_input})
122
 
123
  # Retrieve relevant memories to provide context
124
+ relevant_memories = self.memory_manager.retrieve_memories(user_input, k=5) # Get more memories
125
 
126
+ # Build context from memories with better formatting
127
  context = ""
128
  if relevant_memories:
129
+ context = "Here's what I remember about you:\n"
130
+ for i, memory in enumerate(relevant_memories[:3], 1): # Show top 3 memories
131
+ context += f"{i}. {memory['content']}\n"
132
  context += "\n"
133
 
134
+ # Build the prompt with enhanced context and conversation history
135
  prompt = self.build_prompt(user_input, context)
136
 
137
  # Generate AI response
 
164
  Returns:
165
  The prompt to send to the AI model
166
  """
167
+ # Build a more natural conversation prompt
168
+ prompt = f"""{context}The user says: "{user_input}"
169
+
170
+ As an AI assistant, respond naturally and helpfully. Consider any relevant memories above when crafting your response. Be conversational, engaging, and provide helpful information.
171
+
172
+ Your response: """
173
  return prompt
174
 
175
  def get_current_time(self) -> str:
chat_interface.py CHANGED
@@ -9,7 +9,7 @@ console = Console()
9
  class HuggingFaceChat:
10
  """Interface for chatting with Hugging Face models."""
11
 
12
- def __init__(self, model_name: str = "microsoft/DialoGPT-small"):
13
  """
14
  Initialize the chat interface.
15
 
@@ -66,15 +66,18 @@ class HuggingFaceChat:
66
  return "I'm sorry, but I couldn't load the model. Please check your internet connection and model availability."
67
 
68
  try:
69
- # Generate response
70
  response = self.chatbot(
71
  prompt,
72
  max_length=max_length,
73
  do_sample=True,
74
- temperature=0.7,
75
- top_p=0.9,
76
- repetition_penalty=1.2,
77
- pad_token_id=self.tokenizer.eos_token_id
 
 
 
78
  )
79
 
80
  # Extract the generated text
@@ -84,12 +87,31 @@ class HuggingFaceChat:
84
  if generated_text.startswith(prompt):
85
  generated_text = generated_text[len(prompt):].strip()
86
 
 
 
 
 
87
  return generated_text
88
 
89
  except Exception as e:
90
  console.print(f"[red]Error generating response: {e}[/red]")
91
  return "I'm sorry, but I encountered an error while generating a response."
92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  def check_model_availability(self) -> bool:
94
  """Check if the model is available."""
95
  return self.chatbot is not None
 
9
  class HuggingFaceChat:
10
  """Interface for chatting with Hugging Face models."""
11
 
12
+ def __init__(self, model_name: str = "microsoft/DialoGPT-medium"):
13
  """
14
  Initialize the chat interface.
15
 
 
66
  return "I'm sorry, but I couldn't load the model. Please check your internet connection and model availability."
67
 
68
  try:
69
+ # Generate response with improved parameters for better quality
70
  response = self.chatbot(
71
  prompt,
72
  max_length=max_length,
73
  do_sample=True,
74
+ temperature=0.8, # Higher for more creativity
75
+ top_p=0.95, # Higher for more diverse responses
76
+ top_k=50, # Limit to top 50 tokens
77
+ repetition_penalty=1.1, # Lower penalty for more natural flow
78
+ no_repeat_ngram_size=3, # Avoid repeating 3-word phrases
79
+ pad_token_id=self.tokenizer.eos_token_id,
80
+ truncation=True # Enable truncation to prevent errors
81
  )
82
 
83
  # Extract the generated text
 
87
  if generated_text.startswith(prompt):
88
  generated_text = generated_text[len(prompt):].strip()
89
 
90
+ # Clean up the response
91
+ # Remove any incomplete sentences or hanging punctuation
92
+ generated_text = self._clean_response(generated_text)
93
+
94
  return generated_text
95
 
96
  except Exception as e:
97
  console.print(f"[red]Error generating response: {e}[/red]")
98
  return "I'm sorry, but I encountered an error while generating a response."
99
 
100
+ def _clean_response(self, text: str) -> str:
101
+ """Clean up the generated response."""
102
+ # Remove any trailing incomplete sentences
103
+ if text.endswith(('.', '!', '?')):
104
+ return text
105
+
106
+ # Find the last complete sentence
107
+ import re
108
+ sentences = re.split(r'(?<=[.!?])\s+', text)
109
+ if len(sentences) > 1:
110
+ # Remove the last incomplete sentence
111
+ text = ' '.join(sentences[:-1])
112
+
113
+ return text.strip()
114
+
115
  def check_model_availability(self) -> bool:
116
  """Check if the model is available."""
117
  return self.chatbot is not None