-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo_streaming.py
More file actions
205 lines (166 loc) · 6.91 KB
/
demo_streaming.py
File metadata and controls
205 lines (166 loc) · 6.91 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
#!/usr/bin/env python3
"""
Demo script to showcase Autumn's streaming capabilities vs non-streaming.
Shows the difference in user experience and potential issues.
"""
import asyncio
import time
import logging
from datetime import datetime
from pathlib import Path
import sys
# Add the project root to the Python path
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
from core.brain import AutumnBrain
from core.memory import AutumnMemory
from config.personality import AutumnPersonality
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class StreamingDemo:
def __init__(self):
self.memory = AutumnMemory()
self.personality = AutumnPersonality()
self.brain = None
async def initialize(self):
"""Initialize Autumn's brain."""
logger.info("Initializing Autumn's brain...")
self.brain = AutumnBrain(self.memory, self.personality)
await self.brain.initialize()
logger.info("Brain initialized successfully!")
async def streaming_callback(self, data):
"""Callback function to handle streaming data."""
if data["type"] == "token":
# Print tokens as they arrive (like typing effect)
print(data["content"], end="", flush=True)
elif data["type"] == "sentence":
# Complete sentence ready for TTS
print(f"\n[SENTENCE COMPLETE] {data['content']}")
elif data["type"] == "complete":
# Final response complete
print(f"\n[STREAMING COMPLETE] Total chars: {len(data['content'])}")
async def demo_non_streaming(self, query: str):
"""Demo regular non-streaming response."""
print(f"\n{'='*60}")
print(f"NON-STREAMING DEMO")
print(f"{'='*60}")
print(f"Query: {query}")
print(f"Waiting for complete response...")
start_time = time.time()
response = await self.brain.process(query)
end_time = time.time()
print(f"\nResponse received in {end_time - start_time:.2f} seconds:")
print(f"Response: {response}")
async def demo_streaming(self, query: str):
"""Demo streaming response."""
print(f"\n{'='*60}")
print(f"STREAMING DEMO")
print(f"{'='*60}")
print(f"Query: {query}")
print(f"Streaming response (real-time):")
print("-" * 40)
start_time = time.time()
# Start streaming
response = await self.brain.process_streaming(query, self.streaming_callback)
end_time = time.time()
print(f"\n-" * 40)
print(f"Complete response received in {end_time - start_time:.2f} seconds")
async def demo_comparison(self):
"""Run comparison between streaming and non-streaming."""
test_queries = [
"Tell me about the history of artificial intelligence",
"Explain quantum computing in simple terms",
"What are the benefits of renewable energy?",
"How does machine learning work?"
]
for query in test_queries:
print(f"\n{'#'*80}")
print(f"COMPARISON TEST: {query}")
print(f"{'#'*80}")
# Non-streaming first
await self.demo_non_streaming(query)
# Small delay
await asyncio.sleep(1)
# Streaming second
await self.demo_streaming(query)
# Pause between queries
input("\nPress Enter to continue to next query...")
async def demo_error_scenarios(self):
"""Demo various error scenarios with streaming."""
print(f"\n{'='*60}")
print(f"ERROR SCENARIO TESTING")
print(f"{'='*60}")
error_scenarios = [
"This is a very long query that might cause timeout issues " * 20,
"", # Empty query
"Tell me about 🤖 AI and 🧠 machine learning with emojis", # Unicode
]
for i, query in enumerate(error_scenarios, 1):
print(f"\nError Scenario {i}: {query[:50]}...")
try:
await self.demo_streaming(query)
except Exception as e:
print(f"Error caught: {e}")
async def interactive_demo(self):
"""Interactive demo where user can type queries."""
print(f"\n{'='*60}")
print(f"INTERACTIVE STREAMING DEMO")
print(f"{'='*60}")
print("Type your queries and see streaming in action!")
print("Type 'quit' to exit, 'switch' to toggle streaming mode")
streaming_mode = True
while True:
try:
user_input = input(f"\n[{'STREAMING' if streaming_mode else 'NORMAL'}] You: ").strip()
if user_input.lower() == 'quit':
break
elif user_input.lower() == 'switch':
streaming_mode = not streaming_mode
print(f"Switched to {'STREAMING' if streaming_mode else 'NORMAL'} mode")
continue
elif not user_input:
continue
print(f"Autumn: ", end="", flush=True)
if streaming_mode:
response = await self.brain.process_streaming(user_input, self.streaming_callback)
else:
response = await self.brain.process(user_input)
print(response)
except KeyboardInterrupt:
print("\nExiting...")
break
except Exception as e:
print(f"\nError: {e}")
async def run_demo(self):
"""Run the complete demo."""
await self.initialize()
print("Welcome to Autumn AI Streaming Demo!")
print("=" * 50)
while True:
print("\nDemo Options:")
print("1. Comparison Demo (Streaming vs Non-streaming)")
print("2. Error Scenario Testing")
print("3. Interactive Demo")
print("4. Exit")
choice = input("\nSelect option (1-4): ").strip()
if choice == "1":
await self.demo_comparison()
elif choice == "2":
await self.demo_error_scenarios()
elif choice == "3":
await self.interactive_demo()
elif choice == "4":
print("Goodbye!")
break
else:
print("Invalid option. Please try again.")
async def main():
"""Main entry point."""
demo = StreamingDemo()
await demo.run_demo()
if __name__ == "__main__":
asyncio.run(main())