-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo.py
More file actions
265 lines (220 loc) · 10.1 KB
/
demo.py
File metadata and controls
265 lines (220 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#!/usr/bin/env python3
"""
Voice Agent Demo Script
This script demonstrates the basic functionality of the voice agent:
1. Voice input/output capabilities
2. Session memory and conversation context
3. LLM-powered responses
Requirements:
- OpenAI API key set as environment variable OPENAI_API_KEY
- Microphone and speakers/headphones
- All dependencies installed (see requirements.txt)
"""
import os
import sys
from voice_agent import VoiceAgent
def check_prerequisites():
"""Check if all prerequisites are met"""
print("Checking prerequisites...")
# Check OpenAI API key
if not os.getenv("OPENAI_API_KEY"):
print("❌ OPENAI_API_KEY environment variable not found")
print("Please set your OpenAI API key:")
print("export OPENAI_API_KEY='your-api-key-here'")
return False
else:
print("✅ OpenAI API key found")
# Check dependencies
try:
import speech_recognition
print("✅ speech_recognition installed")
except ImportError:
print("❌ speech_recognition not installed")
return False
try:
import pyttsx3
print("✅ pyttsx3 installed")
except ImportError:
print("❌ pyttsx3 not installed")
return False
try:
import openai
print("✅ openai installed")
except ImportError:
print("❌ openai not installed")
return False
return True
def demo_text_only():
"""Demo mode with text input/output only (no audio)"""
print("\n" + "="*50)
print("DEMO MODE: Text-only conversation with Long-term Memory")
print("(No audio required - useful for testing memory features)")
print("="*50 + "\n")
# Get user ID for personalized experience
user_id = input("Enter your user ID (or press Enter for 'demo_user'): ").strip()
if not user_id:
user_id = "demo_user"
# Initialize voice agent with long-term memory
from voice_agent import VoiceAgent
import logging
# Set up logging to see memory operations
logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
try:
agent = VoiceAgent(user_id=user_id)
print(f"✅ Initialized voice agent with long-term memory for user '{user_id}'")
print(f"💭 {agent.get_memory_summary()}")
except Exception as e:
print(f"❌ Failed to initialize voice agent: {e}")
return
print("\nDemo Voice Agent (Text Mode with Full Personalization)")
print("💡 Try mentioning your preferences, interests, or personal details!")
print("🔄 Start a new session later with the same user ID to see if it remembers!")
print("🤖 The agent may proactively ask follow-up questions or suggest topics!")
print("⚙️ Say 'set proactivity off/low/normal/high' to control interaction level")
print("👤 Say 'show profile' or 'my profile' to see what I know about you")
print("Type 'exit' to quit\n")
while True:
try:
user_input = input("You: ").strip()
if user_input.lower() in ['exit', 'quit', 'goodbye', 'stop']:
agent_response = "Goodbye! I'll remember our conversation for next time."
print(f"Agent: {agent_response}")
break
if not user_input:
continue
# Handle proactivity control commands
if user_input.lower().startswith('set proactivity'):
level = user_input.lower().replace('set proactivity', '').strip()
response = agent.set_proactivity_level(level)
print(f"Agent: {response}")
continue
# Handle profile commands
if user_input.lower() in ['show profile', 'my profile']:
if agent.profile_enabled:
profile_info = agent._get_profile_summary()
print(f"Agent: {profile_info}")
else:
print("Agent: Profile system is not available.")
continue
# Generate response using the full agent (includes memory extraction)
agent_response = agent.generate_response(user_input)
print(f"Agent: {agent_response}")
# Store in session memory and extract long-term memories
turn_id = agent.memory.add_turn(user_input, agent_response)
if agent.ltm_enabled:
agent._store_long_term_memories(user_input, agent_response, turn_id)
# Simulate brief pause and check for proactive follow-up
import time
time.sleep(0.5) # Brief pause
if agent.proactive_enabled:
proactive_message = agent.check_for_proactive_opportunity(pause_duration=3.0)
if proactive_message:
print(f"🤖 Agent (proactive): {proactive_message}")
# Store the proactive interaction
agent.memory.add_turn("[proactive follow-up]", proactive_message)
except KeyboardInterrupt:
print("\nDemo ended")
break
except Exception as e:
print(f"Error: {e}")
# Show comprehensive stats
session_stats = agent.memory.get_session_stats()
print(f"\n📊 Session Summary:")
print(f"- Conversation turns: {session_stats['total_turns']}")
print(f"- {agent.get_memory_summary()}")
if agent.ltm_enabled:
try:
ltm_stats = agent.long_term_memory.get_memory_stats()
print(f"\n🧠 Long-term Memory Details:")
print(f"- Total memories stored: {ltm_stats.get('total_memories', 0)}")
if ltm_stats.get('by_type'):
print(f"- Memory types: {ltm_stats['by_type']}")
if ltm_stats.get('by_domain'):
print(f"- Memory domains: {ltm_stats['by_domain']}")
except Exception as e:
print(f"⚠️ Could not retrieve memory stats: {e}")
if agent.proactive_enabled:
try:
proactive_stats = agent.proactive_agent.get_proactivity_stats()
print(f"\n🤖 Proactivity Details:")
print(f"- Level: {proactive_stats['proactivity_level']}")
print(f"- Conversation time: {proactive_stats['conversation_minutes']} minutes")
if proactive_stats['last_proactive']:
print(f"- Last proactive: {proactive_stats['last_proactive']}")
print(f"- Declined topics: {proactive_stats['declined_topics_count']}")
except Exception as e:
print(f"⚠️ Could not retrieve proactivity stats: {e}")
if agent.profile_enabled:
try:
profile_stats = agent.profile_manager.get_profile_stats(agent.user_id)
print(f"\n👤 User Profile Details:")
print(f"- User: {profile_stats['name']}")
print(f"- Interests tracked: {profile_stats['interests_count']}")
print(f"- Allowed domains: {profile_stats['allowed_domains']}")
print(f"- Proactivity preference: {profile_stats['proactivity_level']}")
print(f"- Profile updates: {profile_stats['total_changes']}")
except Exception as e:
print(f"⚠️ Could not retrieve profile stats: {e}")
def main():
"""Main demo function"""
print("Voice Agent Demo")
print("================\n")
if not check_prerequisites():
print("\nPlease install missing dependencies and try again:")
print("pip install -r requirements.txt")
return
print("\nChoose demo mode:")
print("1. Full voice mode (microphone + speakers required)")
print("2. Enhanced voice mode with natural AI voice 🎤✨")
print("3. Text-only mode (no audio required)")
print("4. Exit")
while True:
choice = input("\nEnter your choice (1-4): ").strip()
if choice == "1":
print("\nStarting full voice mode...")
print("Make sure your microphone and speakers are working!")
# Get user ID for personalized experience
user_id = input("Enter your user ID (or press Enter for 'demo_user'): ").strip()
if not user_id:
user_id = "demo_user"
input("Press Enter when ready...")
try:
from voice_agent import VoiceAgent
agent = VoiceAgent(user_id=user_id)
agent.run_conversation()
except Exception as e:
print(f"Error running voice agent: {e}")
print("You might want to try text-only mode instead.")
break
elif choice == "2":
print("\nStarting enhanced voice mode with natural AI voice...")
print("🎤 This uses the natural voice you liked from test_ai_voice.py!")
print("Make sure you have pygame installed: pip install pygame")
print("Make sure your microphone and speakers are working!")
# Get user ID for personalized experience
user_id = input("Enter your user ID (or press Enter for 'demo_user'): ").strip()
if not user_id:
user_id = "demo_user"
input("Press Enter when ready...")
try:
from proactive_agent import EnhancedVoiceAgent
enhanced_agent = EnhancedVoiceAgent(user_id=user_id)
if enhanced_agent.initialized:
enhanced_agent.start_conversation()
else:
print("❌ Failed to initialize enhanced voice agent")
print("Fallback: Try option 1 for basic voice mode")
except Exception as e:
print(f"Error running enhanced voice agent: {e}")
print("Fallback: Try option 1 for basic voice mode")
break
elif choice == "3":
demo_text_only()
break
elif choice == "4":
print("Goodbye!")
break
else:
print("Invalid choice. Please enter 1, 2, 3, or 4.")
if __name__ == "__main__":
main()