midstream 0.2.0

Real-time LLM streaming with inflight analysis
Documentation
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
# MidStream Real-Time Dashboard

**Created by rUv**

Comprehensive real-time dashboard for monitoring and analyzing LLM streaming with advanced temporal pattern detection, attractor analysis, and multi-modal stream introspection.

## ๐ŸŒŸ Features

### Real-Time Monitoring
- **Text Streaming**: Process and analyze text messages in real-time
- **Audio Streaming**: Monitor audio streams with transcription support
- **Video Streaming**: Analyze video streams with object detection
- **Multi-Modal**: Simultaneous handling of text, audio, and video streams

### Advanced Analysis
- **Temporal Pattern Detection**: Identify patterns in conversation flows
- **Attractor Analysis**: Detect fixed points, periodic cycles, and chaotic behavior
- **Lyapunov Exponents**: Measure system stability and chaos
- **Meta-Learning**: Adaptive learning from conversation patterns
- **Behavior Classification**: Classify system behavior as stable, unstable, or chaotic

### Performance Metrics
- **Real-Time FPS**: Frames per second monitoring
- **Latency Tracking**: Message processing latency
- **Stream Metrics**: Bandwidth, bitrate, and chunk statistics
- **Token Counting**: Track LLM token usage
- **Uptime Monitoring**: System uptime and health

### Streaming Support
- **WebSocket**: Real-time bidirectional streaming
- **Server-Sent Events (SSE)**: Unidirectional event streaming
- **WebRTC**: Peer-to-peer audio/video streaming
- **RTMP**: Real-Time Messaging Protocol support
- **HLS**: HTTP Live Streaming support

## ๐Ÿ“ฆ Installation

```bash
cd npm
npm install
npm run build:ts
```

## ๐Ÿš€ Quick Start

### Basic Dashboard

```typescript
import { MidStreamDashboard } from 'midstream-cli';

const dashboard = new MidStreamDashboard();
dashboard.start(100); // Refresh every 100ms

// Process a message
dashboard.processMessage('Hello, world!', 5);

// Process streaming data
const audioData = Buffer.alloc(1024);
dashboard.processStream('audio-1', audioData, 'audio');
```

### Interactive Dashboard

```typescript
import { InteractiveDashboard } from 'midstream-cli';

const dashboard = new InteractiveDashboard();
dashboard.startInteractive();
```

### Run Demo

```bash
# Full demo with all features
npm run demo

# Text-only demo
npm run demo:text

# Audio streaming demo
npm run demo:audio

# Video streaming demo
npm run demo:video

# OpenAI Realtime API demo
npm run demo:openai
```

## ๐Ÿ“Š Dashboard Components

### System Metrics Panel
```
Messages Processed: 150
Total Tokens: 2,340
FPS: 60
Latency: 12ms
Uptime: 0h 5m 23s
```

### Temporal Analysis Panel
```
Attractor Type: PERIODIC
Lyapunov Exp: -0.0234
Stability: STABLE
Chaos: ORDERED
Avg Reward: 0.847
```

### Pattern Detection Panel
```
โ€ข greeting (95%)
โ€ข question (87%)
โ€ข acknowledgment (92%)
โ€ข follow-up (78%)
โ€ข closing (88%)
```

### Streaming Status Panel
```
Audio: โ— ACTIVE
Video: โ— ACTIVE
Streams: 3 active
```

### Stream Metrics Panel
```
audio-stream-1 (audio): 150 chunks, 1.5 MB, 45.2 KB/s
video-stream-1 (video): 1800 frames, 180 MB, 3.2 MB/s
```

## ๐ŸŽฅ Restream Integration

### WebRTC Streaming

```typescript
import { RestreamClient } from 'midstream-cli';

const client = new RestreamClient({
  webrtcSignaling: 'wss://signaling.example.com',
  enableTranscription: true,
  enableObjectDetection: true,
  frameRate: 30,
  resolution: '1920x1080'
});

// Listen for frames
client.on('frame', (frame) => {
  console.log(`Frame ${frame.frameNumber}: ${frame.width}x${frame.height}`);
});

// Listen for audio
client.on('audio', (audio) => {
  console.log(`Audio chunk: ${audio.sampleRate}Hz, ${audio.channels}ch`);
});

// Listen for transcriptions
client.on('transcription', (text) => {
  console.log(`Transcription: ${text}`);
});

// Connect
await client.connectWebRTC();
```

### RTMP Streaming

```typescript
const client = new RestreamClient({
  rtmpUrl: 'rtmp://live.example.com/live',
  streamKey: 'your-stream-key',
  enableTranscription: true
});

await client.connectRTMP();
```

### HLS Streaming

```typescript
const client = new RestreamClient({
  enableTranscription: true
});

await client.connectHLS('https://example.com/stream.m3u8');
```

### Stream Analysis

```typescript
// Get real-time analysis
const analysis = client.getAnalysis();

console.log(`
  Frames: ${analysis.frameCount}
  Audio Chunks: ${analysis.audioChunks}
  FPS: ${analysis.fps}
  Bitrate: ${analysis.bitrate} Kbps
  Patterns: ${analysis.patterns.length}
`);
```

## ๐Ÿค– OpenAI Realtime Integration

```typescript
import { MidStreamDashboard } from 'midstream-cli';
import { OpenAIRealtimeClient } from 'midstream-cli';

const dashboard = new MidStreamDashboard();
dashboard.start();

const client = new OpenAIRealtimeClient({
  apiKey: process.env.OPENAI_API_KEY,
  model: 'gpt-4o-realtime-preview-2024-10-01',
  voice: 'alloy'
});

// Connect dashboard to OpenAI events
client.on('response.text.delta', (delta) => {
  dashboard.processMessage(delta, delta.length);
});

client.on('response.audio.delta', (delta) => {
  const audio = Buffer.from(delta, 'base64');
  dashboard.processStream('openai-audio', audio, 'audio');
});

await client.connect();
client.sendText('Analyze this conversation...');
```

## ๐Ÿงช Testing with Stream Simulator

```typescript
import { StreamSimulator } from 'midstream-cli';

const simulator = new StreamSimulator(30); // 30 FPS

simulator.start(
  (frame) => {
    // Process video frame
    dashboard.processStream('video', frame.data, 'video');
  },
  (audio) => {
    // Process audio chunk
    dashboard.processStream('audio', audio.data, 'audio');
  }
);

// Run for 60 seconds
setTimeout(() => simulator.stop(), 60000);
```

## ๐Ÿ”ง Configuration

### Dashboard Options

```typescript
const dashboard = new MidStreamDashboard();

// Custom agent configuration
const agent = dashboard.getAgent();
// Agent is pre-configured with:
// - maxHistory: 1000
// - embeddingDim: 3
// - schedulingPolicy: 'EDF'
```

### Refresh Rate

```typescript
// Fast refresh (100ms) - smooth but CPU intensive
dashboard.start(100);

// Medium refresh (500ms) - balanced
dashboard.start(500);

// Slow refresh (1000ms) - low CPU usage
dashboard.start(1000);
```

## ๐Ÿ“ˆ Advanced Usage

### Custom Pattern Analysis

```typescript
const agent = dashboard.getAgent();

// Detect custom pattern
const pattern = ['greeting', 'question', 'answer'];
const positions = agent.detectPattern(conversation, pattern);

console.log(`Pattern found at positions: ${positions}`);
```

### Sequence Comparison

```typescript
// Compare two conversation sequences
const similarity = agent.compareSequences(
  sequence1,
  sequence2,
  'dtw' // Dynamic Time Warping
);

console.log(`Similarity: ${(similarity * 100).toFixed(1)}%`);
```

### Behavior Analysis

```typescript
// Analyze system behavior
const rewards = [0.8, 0.85, 0.83, 0.87, 0.84];
const analysis = agent.analyzeBehavior(rewards);

console.log(`
  Attractor: ${analysis.attractorType}
  Lyapunov: ${analysis.lyapunovExponent}
  Stable: ${analysis.isStable}
  Chaotic: ${analysis.isChaotic}
`);
```

## ๐ŸŽจ Customization

### Color Themes

The dashboard uses chalk for colorful console output:
- **Cyan**: Headers and titles
- **Green**: Success states and positive metrics
- **Yellow**: Warnings and neutral metrics
- **Red**: Errors and negative states
- **Magenta**: Patterns and detections
- **Gray**: Secondary information

### Custom Metrics

```typescript
// Get current state
const state = dashboard.getState();

// Modify or extend as needed
console.log(`
  Messages: ${state.messageCount}
  Patterns: ${state.patternsDetected.length}
  Attractor: ${state.attractorType}
`);
```

## ๐Ÿ” Security Considerations

### API Keys
Always use environment variables for API keys:

```bash
# .env file
OPENAI_API_KEY=sk-...
AGENTIC_FLOW_API_KEY=...
```

### Stream Authentication
When using WebRTC or RTMP, ensure proper authentication:

```typescript
const client = new RestreamClient({
  rtmpUrl: 'rtmps://secure.example.com/live', // Use RTMPS
  streamKey: process.env.STREAM_KEY,
  apiKey: process.env.API_KEY
});
```

### Rate Limiting
Implement rate limiting for API calls:

```typescript
// Limit message processing rate
let lastProcess = 0;
const minInterval = 100; // ms

function processWithRateLimit(message: string) {
  const now = Date.now();
  if (now - lastProcess >= minInterval) {
    dashboard.processMessage(message, message.length);
    lastProcess = now;
  }
}
```

## ๐Ÿ“Š Performance Optimization

### Buffer Management
The dashboard automatically manages buffers:
- Recent messages: Last 5 messages
- Frame buffer: Last 100 frames
- Audio buffer: Last 100 chunks

### Memory Usage
Monitor and optimize memory usage:

```typescript
// Periodic cleanup
setInterval(() => {
  if (global.gc) {
    global.gc();
  }
}, 60000);
```

### CPU Optimization
Adjust refresh rate based on CPU usage:

```typescript
// Start with fast refresh
dashboard.start(100);

// Reduce if CPU is high
if (cpuUsage > 80) {
  dashboard.stop();
  dashboard.start(500);
}
```

## ๐Ÿ› Troubleshooting

### Dashboard Not Updating
- Check refresh rate is appropriate
- Verify messages are being processed
- Check console for errors

### Stream Not Connecting
- Verify URL and credentials
- Check network connectivity
- Review firewall settings

### High CPU Usage
- Increase refresh interval
- Reduce stream resolution
- Disable unnecessary features

### Memory Leaks
- Check buffer sizes
- Verify event listeners are cleaned up
- Monitor with `process.memoryUsage()`

## ๐Ÿ“š API Reference

### MidStreamDashboard

#### Constructor
```typescript
new MidStreamDashboard()
```

#### Methods
- `start(refreshRate: number): void` - Start dashboard
- `stop(): void` - Stop dashboard
- `processMessage(message: string, tokens?: number): void` - Process text message
- `processStream(streamId: string, data: Buffer, type: 'audio' | 'video' | 'text'): void` - Process stream data
- `getAgent(): MidStreamAgent` - Get underlying agent
- `getState(): DashboardState` - Get current state

### RestreamClient

#### Constructor
```typescript
new RestreamClient(config: RestreamConfig)
```

#### Methods
- `connectRTMP(): Promise<void>` - Connect to RTMP stream
- `connectWebRTC(): Promise<void>` - Connect to WebRTC stream
- `connectHLS(url: string): Promise<void>` - Connect to HLS stream
- `disconnect(): void` - Disconnect from stream
- `getAnalysis(): StreamAnalysis` - Get stream analysis
- `getStats()` - Get stream statistics

#### Events
- `connected` - Stream connected
- `disconnected` - Stream disconnected
- `frame` - Video frame received
- `audio` - Audio chunk received
- `transcription` - Audio transcribed
- `objects_detected` - Objects detected in frame
- `error` - Error occurred

### StreamSimulator

#### Constructor
```typescript
new StreamSimulator(frameRate: number)
```

#### Methods
- `start(onFrame, onAudio?): void` - Start simulation
- `stop(): void` - Stop simulation
- `getFrameNumber(): number` - Get current frame number

## ๐Ÿค Contributing

Contributions are welcome! Please:
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request

## ๐Ÿ“„ License

MIT License - see LICENSE file for details

## ๐Ÿ‘จโ€๐Ÿ’ป Author

**Created by rUv**

For questions or support, please open an issue on GitHub.

## ๐Ÿ™ Acknowledgments

- OpenAI for Realtime API
- WebRTC community
- Node.js community
- All contributors

---

**MidStream Dashboard** - Real-time introspection for the AI age