rystem.playframework.client 0.1.1 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1617 -47
- package/lib/engine/ClientInteractionRegistry.d.ts +48 -1
- package/lib/engine/ClientInteractionRegistry.d.ts.map +1 -1
- package/lib/engine/ClientInteractionRegistry.js +84 -13
- package/lib/engine/PlayFrameworkClient.d.ts +58 -0
- package/lib/engine/PlayFrameworkClient.d.ts.map +1 -1
- package/lib/engine/PlayFrameworkClient.js +271 -24
- package/lib/index.d.ts +17 -1
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +15 -1
- package/lib/models/AiSceneResponse.d.ts +2 -2
- package/lib/models/AiSceneResponse.d.ts.map +1 -1
- package/lib/models/ClientInteractionRequest.d.ts +15 -0
- package/lib/models/ClientInteractionRequest.d.ts.map +1 -1
- package/lib/models/CommandResult.d.ts +31 -0
- package/lib/models/CommandResult.d.ts.map +1 -0
- package/lib/models/CommandResult.js +18 -0
- package/lib/models/ExecutionState.d.ts +35 -0
- package/lib/models/ExecutionState.d.ts.map +1 -0
- package/lib/models/ExecutionState.js +2 -0
- package/lib/models/PlayFrameworkRequest.d.ts +10 -0
- package/lib/models/PlayFrameworkRequest.d.ts.map +1 -1
- package/lib/models/StoredConversation.d.ts +88 -0
- package/lib/models/StoredConversation.d.ts.map +1 -0
- package/lib/models/StoredConversation.js +17 -0
- package/lib/models/StoredMessage.d.ts +30 -0
- package/lib/models/StoredMessage.d.ts.map +1 -0
- package/lib/models/StoredMessage.js +2 -0
- package/lib/models/VoiceResponse.d.ts +39 -0
- package/lib/models/VoiceResponse.d.ts.map +1 -0
- package/lib/models/VoiceResponse.js +2 -0
- package/lib/utils/BrowserSpeechRecognizer.d.ts +128 -0
- package/lib/utils/BrowserSpeechRecognizer.d.ts.map +1 -0
- package/lib/utils/BrowserSpeechRecognizer.js +150 -0
- package/lib/utils/BrowserSpeechSynthesizer.d.ts +148 -0
- package/lib/utils/BrowserSpeechSynthesizer.d.ts.map +1 -0
- package/lib/utils/BrowserSpeechSynthesizer.js +400 -0
- package/lib/utils/BrowserVoiceClient.d.ts +142 -0
- package/lib/utils/BrowserVoiceClient.d.ts.map +1 -0
- package/lib/utils/BrowserVoiceClient.js +200 -0
- package/lib/utils/ContentUrlConverter.d.ts +62 -0
- package/lib/utils/ContentUrlConverter.d.ts.map +1 -0
- package/lib/utils/ContentUrlConverter.js +151 -0
- package/lib/utils/VoiceRecorder.d.ts +90 -0
- package/lib/utils/VoiceRecorder.d.ts.map +1 -0
- package/lib/utils/VoiceRecorder.js +195 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -15,6 +15,7 @@ Production-ready client with full support for:
|
|
|
15
15
|
- ✅ **Execution modes** - Direct, Planning, DynamicChaining, Scene
|
|
16
16
|
- ✅ **Configurable** - Headers, retry, error handling, timeouts
|
|
17
17
|
- ✅ **Type-safe** - Full TypeScript definitions
|
|
18
|
+
- ✅ **Browser Voice** - Client-side STT/TTS via Web Speech API (zero-latency, no server needed)
|
|
18
19
|
|
|
19
20
|
---
|
|
20
21
|
|
|
@@ -283,12 +284,12 @@ const request: PlayFrameworkRequest = {
|
|
|
283
284
|
contents: [
|
|
284
285
|
{
|
|
285
286
|
type: "image",
|
|
286
|
-
|
|
287
|
+
data: "iVBORw0KGgoAAAANSUhEUgAA...",
|
|
287
288
|
mediaType: "image/png"
|
|
288
289
|
},
|
|
289
290
|
{
|
|
290
291
|
type: "data",
|
|
291
|
-
|
|
292
|
+
data: "JVBERi0xLjQKJeLjz9M...",
|
|
292
293
|
mediaType: "application/pdf"
|
|
293
294
|
},
|
|
294
295
|
{
|
|
@@ -420,49 +421,1379 @@ for await (const step of client.executeStepByStep({
|
|
|
420
421
|
|
|
421
422
|
---
|
|
422
423
|
|
|
423
|
-
##
|
|
424
|
+
## 💾 Conversation Management (Repository Pattern)
|
|
425
|
+
|
|
426
|
+
If the backend has **Repository persistence enabled**, you can manage conversations using REST endpoints.
|
|
427
|
+
|
|
428
|
+
### List Conversations
|
|
429
|
+
|
|
430
|
+
```typescript
|
|
431
|
+
import { ConversationSortOrder } from "@rystem/playframework-client";
|
|
432
|
+
|
|
433
|
+
// Get conversations with filters
|
|
434
|
+
const conversations = await client.listConversations({
|
|
435
|
+
searchText: "weather", // Search in message text
|
|
436
|
+
includePublic: true, // Include public conversations
|
|
437
|
+
includePrivate: true, // Include private conversations
|
|
438
|
+
orderBy: ConversationSortOrder.TimestampDescending, // Sort by newest first
|
|
439
|
+
skip: 0, // Pagination offset
|
|
440
|
+
take: 50 // Page size
|
|
441
|
+
});
|
|
442
|
+
|
|
443
|
+
console.log(conversations);
|
|
444
|
+
// [
|
|
445
|
+
// {
|
|
446
|
+
// conversationKey: "abc-123",
|
|
447
|
+
// userId: "user@example.com",
|
|
448
|
+
// isPublic: false,
|
|
449
|
+
// timestamp: "2025-01-15T10:30:00Z",
|
|
450
|
+
// messages: [...],
|
|
451
|
+
// executionState: {...}
|
|
452
|
+
// }
|
|
453
|
+
// ]
|
|
454
|
+
```
|
|
455
|
+
|
|
456
|
+
### Get Single Conversation
|
|
457
|
+
|
|
458
|
+
```typescript
|
|
459
|
+
const conversation = await client.getConversation("abc-123");
|
|
460
|
+
|
|
461
|
+
if (conversation) {
|
|
462
|
+
console.log(conversation.messages); // Full message history
|
|
463
|
+
console.log(conversation.isPublic); // Public vs private
|
|
464
|
+
} else {
|
|
465
|
+
console.log("Conversation not found or unauthorized");
|
|
466
|
+
}
|
|
467
|
+
```
|
|
468
|
+
|
|
469
|
+
**Authorization**: Private conversations require userId match (set via backend `IAuthorizationLayer`).
|
|
470
|
+
|
|
471
|
+
### Delete Conversation
|
|
472
|
+
|
|
473
|
+
```typescript
|
|
474
|
+
// Owner-only operation
|
|
475
|
+
await client.deleteConversation("abc-123");
|
|
476
|
+
console.log("Conversation deleted");
|
|
477
|
+
```
|
|
478
|
+
|
|
479
|
+
**Response:**
|
|
480
|
+
- ✅ Success - Conversation deleted
|
|
481
|
+
- ❌ `403 Forbidden` - Not the owner
|
|
482
|
+
- ❌ `404 Not Found` - Conversation not found
|
|
483
|
+
|
|
484
|
+
### Update Visibility (Public/Private)
|
|
485
|
+
|
|
486
|
+
```typescript
|
|
487
|
+
// Toggle conversation visibility (owner-only)
|
|
488
|
+
const updated = await client.updateConversationVisibility("abc-123", true);
|
|
489
|
+
console.log(`Conversation is now ${updated.isPublic ? "public" : "private"}`);
|
|
490
|
+
```
|
|
491
|
+
|
|
492
|
+
### React Example: Conversation List UI
|
|
493
|
+
|
|
494
|
+
```tsx
|
|
495
|
+
import { useState, useEffect } from "react";
|
|
496
|
+
import { usePlayFramework, StoredConversation, ConversationSortOrder } from "@rystem/playframework-client";
|
|
497
|
+
|
|
498
|
+
function ConversationList() {
|
|
499
|
+
const client = usePlayFramework("default");
|
|
500
|
+
const [conversations, setConversations] = useState<StoredConversation[]>([]);
|
|
501
|
+
const [searchText, setSearchText] = useState("");
|
|
502
|
+
const [showPublic, setShowPublic] = useState(true);
|
|
503
|
+
const [showPrivate, setShowPrivate] = useState(true);
|
|
504
|
+
const [loading, setLoading] = useState(false);
|
|
505
|
+
|
|
506
|
+
const loadConversations = async () => {
|
|
507
|
+
setLoading(true);
|
|
508
|
+
try {
|
|
509
|
+
const result = await client.listConversations({
|
|
510
|
+
searchText: searchText || undefined,
|
|
511
|
+
includePublic: showPublic,
|
|
512
|
+
includePrivate: showPrivate,
|
|
513
|
+
orderBy: ConversationSortOrder.TimestampDescending,
|
|
514
|
+
take: 100
|
|
515
|
+
});
|
|
516
|
+
setConversations(result);
|
|
517
|
+
} catch (error) {
|
|
518
|
+
console.error("Failed to load conversations:", error);
|
|
519
|
+
} finally {
|
|
520
|
+
setLoading(false);
|
|
521
|
+
}
|
|
522
|
+
};
|
|
523
|
+
|
|
524
|
+
useEffect(() => {
|
|
525
|
+
loadConversations();
|
|
526
|
+
}, [showPublic, showPrivate]);
|
|
527
|
+
|
|
528
|
+
const handleDelete = async (key: string) => {
|
|
529
|
+
if (!window.confirm("Delete this conversation?")) return;
|
|
530
|
+
try {
|
|
531
|
+
await client.deleteConversation(key);
|
|
532
|
+
await loadConversations(); // Reload list
|
|
533
|
+
} catch (error: any) {
|
|
534
|
+
alert(`Failed to delete: ${error.message}`);
|
|
535
|
+
}
|
|
536
|
+
};
|
|
537
|
+
|
|
538
|
+
const handleLoadConversation = async (key: string) => {
|
|
539
|
+
const conv = await client.getConversation(key);
|
|
540
|
+
if (conv) {
|
|
541
|
+
// Load conversation into chat UI
|
|
542
|
+
console.log("Loaded:", conv.messages);
|
|
543
|
+
}
|
|
544
|
+
};
|
|
545
|
+
|
|
546
|
+
return (
|
|
547
|
+
<div>
|
|
548
|
+
<h2>Conversations</h2>
|
|
549
|
+
|
|
550
|
+
{/* Search & Filters */}
|
|
551
|
+
<input
|
|
552
|
+
type="text"
|
|
553
|
+
placeholder="Search messages..."
|
|
554
|
+
value={searchText}
|
|
555
|
+
onChange={e => setSearchText(e.target.value)}
|
|
556
|
+
/>
|
|
557
|
+
<button onClick={loadConversations}>Search</button>
|
|
558
|
+
|
|
559
|
+
<label>
|
|
560
|
+
<input
|
|
561
|
+
type="checkbox"
|
|
562
|
+
checked={showPublic}
|
|
563
|
+
onChange={e => setShowPublic(e.target.checked)}
|
|
564
|
+
/>
|
|
565
|
+
Public
|
|
566
|
+
</label>
|
|
567
|
+
<label>
|
|
568
|
+
<input
|
|
569
|
+
type="checkbox"
|
|
570
|
+
checked={showPrivate}
|
|
571
|
+
onChange={e => setShowPrivate(e.target.checked)}
|
|
572
|
+
/>
|
|
573
|
+
Private
|
|
574
|
+
</label>
|
|
575
|
+
|
|
576
|
+
{/* Conversation List */}
|
|
577
|
+
{loading ? (
|
|
578
|
+
<div>Loading...</div>
|
|
579
|
+
) : (
|
|
580
|
+
<ul>
|
|
581
|
+
{conversations.map(conv => (
|
|
582
|
+
<li key={conv.conversationKey}>
|
|
583
|
+
<div onClick={() => handleLoadConversation(conv.conversationKey)}>
|
|
584
|
+
<strong>{new Date(conv.timestamp).toLocaleString()}</strong>
|
|
585
|
+
<span style={{ color: conv.isPublic ? "green" : "red" }}>
|
|
586
|
+
{conv.isPublic ? "Public" : "Private"}
|
|
587
|
+
</span>
|
|
588
|
+
<p>{conv.messages[0]?.text || "Empty conversation"}</p>
|
|
589
|
+
<small>{conv.messages.length} messages</small>
|
|
590
|
+
</div>
|
|
591
|
+
<button onClick={() => handleDelete(conv.conversationKey)}>Delete</button>
|
|
592
|
+
</li>
|
|
593
|
+
))}
|
|
594
|
+
</ul>
|
|
595
|
+
)}
|
|
596
|
+
</div>
|
|
597
|
+
);
|
|
598
|
+
}
|
|
599
|
+
```
|
|
600
|
+
|
|
601
|
+
### Backend Setup Required
|
|
602
|
+
|
|
603
|
+
For conversation management to work, the backend must:
|
|
604
|
+
|
|
605
|
+
1. **Enable Repository persistence:**
|
|
606
|
+
```csharp
|
|
607
|
+
builder.Services.AddPlayFramework("default", pb => pb
|
|
608
|
+
.UseRepository());
|
|
609
|
+
```
|
|
610
|
+
|
|
611
|
+
2. **Enable conversation endpoints:**
|
|
612
|
+
```csharp
|
|
613
|
+
app.MapPlayFramework("default", settings =>
|
|
614
|
+
{
|
|
615
|
+
settings.EnableConversationEndpoints = true;
|
|
616
|
+
});
|
|
617
|
+
```
|
|
618
|
+
|
|
619
|
+
See [Backend README](../../../README.md) for full setup guide.
|
|
620
|
+
|
|
621
|
+
---
|
|
622
|
+
|
|
623
|
+
## 🔄 Combining Stored Conversations with Live Streaming
|
|
624
|
+
|
|
625
|
+
This section shows how to **load historic messages** from `StoredConversation` and **continue the conversation** with live SSE streaming.
|
|
626
|
+
|
|
627
|
+
### Understanding the Two Models
|
|
628
|
+
|
|
629
|
+
PlayFramework uses **two different models** for different purposes:
|
|
630
|
+
|
|
631
|
+
| Model | Purpose | When | Format | Content |
|
|
632
|
+
|-------|---------|------|--------|---------|
|
|
633
|
+
| **`AiSceneResponse`** | Real-time execution tracking | During `executeStepByStep()` / `executeTokenStreaming()` | SSE (Server-Sent Events) | Status updates, streaming chunks, scene metadata |
|
|
634
|
+
| **`StoredConversation`** | Persistent conversation history | When loading from repository via REST API | JSON | Complete messages, user metadata, execution state |
|
|
635
|
+
|
|
636
|
+
**Why two models?**
|
|
637
|
+
- `AiSceneResponse` contains **temporary execution metadata** (status, sceneName, functionName) needed for real-time UI updates
|
|
638
|
+
- `StoredConversation` contains **only essential data** (messages, userId, timestamp) for efficient storage and querying
|
|
639
|
+
|
|
640
|
+
### Complete Example: Chat with History
|
|
641
|
+
|
|
642
|
+
```tsx
|
|
643
|
+
import React, { useState, useEffect } from 'react';
|
|
644
|
+
import { usePlayFramework, StoredConversation, AiSceneResponse } from '@rystem/playframework-client';
|
|
645
|
+
|
|
646
|
+
interface ChatMessage {
|
|
647
|
+
role: 'user' | 'assistant';
|
|
648
|
+
text: string;
|
|
649
|
+
isStreaming?: boolean; // Distinguishes streaming vs historic messages
|
|
650
|
+
status?: string; // For showing execution status
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
function ChatWithHistory() {
|
|
654
|
+
const client = usePlayFramework('default');
|
|
655
|
+
|
|
656
|
+
// State
|
|
657
|
+
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
|
658
|
+
const [input, setInput] = useState('');
|
|
659
|
+
const [conversationKey, setConversationKey] = useState<string | null>(null);
|
|
660
|
+
const [loading, setLoading] = useState(false);
|
|
661
|
+
|
|
662
|
+
// 📥 LOAD: Load historic conversation from repository
|
|
663
|
+
const loadConversation = async (key: string) => {
|
|
664
|
+
try {
|
|
665
|
+
// Fetch from REST API → StoredConversation
|
|
666
|
+
const stored = await client.getConversation(key);
|
|
667
|
+
|
|
668
|
+
if (!stored) {
|
|
669
|
+
alert('Conversation not found or unauthorized');
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
// Convert StoredMessage[] → ChatMessage[]
|
|
674
|
+
const historicMessages: ChatMessage[] = stored.messages.map(msg => ({
|
|
675
|
+
role: msg.role as 'user' | 'assistant',
|
|
676
|
+
text: msg.text || '',
|
|
677
|
+
isStreaming: false // Historic messages are complete
|
|
678
|
+
}));
|
|
679
|
+
|
|
680
|
+
setMessages(historicMessages);
|
|
681
|
+
setConversationKey(stored.conversationKey);
|
|
682
|
+
|
|
683
|
+
console.log(`✅ Loaded ${stored.messages.length} messages from conversation ${key}`);
|
|
684
|
+
} catch (error) {
|
|
685
|
+
console.error('Failed to load conversation:', error);
|
|
686
|
+
alert(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
687
|
+
}
|
|
688
|
+
};
|
|
689
|
+
|
|
690
|
+
// 📤 SEND: Send message and stream response
|
|
691
|
+
const sendMessage = async () => {
|
|
692
|
+
if (!input.trim() || loading) return;
|
|
693
|
+
|
|
694
|
+
const userMessage = input;
|
|
695
|
+
setInput('');
|
|
696
|
+
setLoading(true);
|
|
697
|
+
|
|
698
|
+
// Add user message to UI
|
|
699
|
+
const userMsg: ChatMessage = { role: 'user', text: userMessage };
|
|
700
|
+
setMessages(prev => [...prev, userMsg]);
|
|
701
|
+
|
|
702
|
+
// Add placeholder for assistant response
|
|
703
|
+
const assistantMsg: ChatMessage = {
|
|
704
|
+
role: 'assistant',
|
|
705
|
+
text: '',
|
|
706
|
+
isStreaming: true, // Flag: currently streaming
|
|
707
|
+
status: 'initializing'
|
|
708
|
+
};
|
|
709
|
+
setMessages(prev => [...prev, assistantMsg]);
|
|
710
|
+
|
|
711
|
+
try {
|
|
712
|
+
// 🔄 Stream from PlayFramework → AiSceneResponse events
|
|
713
|
+
for await (const step of client.executeStepByStep({
|
|
714
|
+
message: userMessage,
|
|
715
|
+
settings: {
|
|
716
|
+
conversationKey: conversationKey || undefined, // Resume existing or start new
|
|
717
|
+
enableStreaming: true
|
|
718
|
+
}
|
|
719
|
+
})) {
|
|
720
|
+
// Update conversationKey from first response
|
|
721
|
+
if (step.conversationKey && !conversationKey) {
|
|
722
|
+
setConversationKey(step.conversationKey);
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
// Update message with streaming chunks
|
|
726
|
+
if (step.streamingChunk) {
|
|
727
|
+
setMessages(prev => {
|
|
728
|
+
const updated = [...prev];
|
|
729
|
+
const last = updated[updated.length - 1];
|
|
730
|
+
last.text += step.streamingChunk;
|
|
731
|
+
last.status = step.status;
|
|
732
|
+
return updated;
|
|
733
|
+
});
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
// Update status (planning, executingScene, etc.)
|
|
737
|
+
else if (step.status) {
|
|
738
|
+
setMessages(prev => {
|
|
739
|
+
const updated = [...prev];
|
|
740
|
+
const last = updated[updated.length - 1];
|
|
741
|
+
last.status = step.status;
|
|
742
|
+
return updated;
|
|
743
|
+
});
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
// Mark streaming as complete
|
|
748
|
+
setMessages(prev => {
|
|
749
|
+
const updated = [...prev];
|
|
750
|
+
const last = updated[updated.length - 1];
|
|
751
|
+
last.isStreaming = false;
|
|
752
|
+
delete last.status;
|
|
753
|
+
return updated;
|
|
754
|
+
});
|
|
755
|
+
|
|
756
|
+
} catch (error) {
|
|
757
|
+
console.error('Streaming error:', error);
|
|
758
|
+
setMessages(prev => {
|
|
759
|
+
const updated = [...prev];
|
|
760
|
+
updated[updated.length - 1] = {
|
|
761
|
+
role: 'assistant',
|
|
762
|
+
text: `Error: ${error instanceof Error ? error.message : 'Unknown error'}`,
|
|
763
|
+
isStreaming: false,
|
|
764
|
+
status: 'error'
|
|
765
|
+
};
|
|
766
|
+
return updated;
|
|
767
|
+
});
|
|
768
|
+
} finally {
|
|
769
|
+
setLoading(false);
|
|
770
|
+
}
|
|
771
|
+
};
|
|
772
|
+
|
|
773
|
+
// 🗑️ CLEAR: Start new conversation
|
|
774
|
+
const clearConversation = () => {
|
|
775
|
+
setMessages([]);
|
|
776
|
+
setConversationKey(null);
|
|
777
|
+
};
|
|
778
|
+
|
|
779
|
+
return (
|
|
780
|
+
<div style={{ maxWidth: '900px', margin: '0 auto', padding: '20px', fontFamily: 'sans-serif' }}>
|
|
781
|
+
<h1>💬 PlayFramework Chat</h1>
|
|
782
|
+
|
|
783
|
+
{/* Conversation Info */}
|
|
784
|
+
<div style={{
|
|
785
|
+
padding: '10px',
|
|
786
|
+
marginBottom: '10px',
|
|
787
|
+
backgroundColor: '#f0f0f0',
|
|
788
|
+
borderRadius: '8px',
|
|
789
|
+
display: 'flex',
|
|
790
|
+
justifyContent: 'space-between',
|
|
791
|
+
alignItems: 'center'
|
|
792
|
+
}}>
|
|
793
|
+
<div>
|
|
794
|
+
{conversationKey ? (
|
|
795
|
+
<>
|
|
796
|
+
<strong>Conversation:</strong> {conversationKey.substring(0, 8)}...
|
|
797
|
+
<span style={{ marginLeft: '10px', color: '#666' }}>
|
|
798
|
+
({messages.length} messages)
|
|
799
|
+
</span>
|
|
800
|
+
</>
|
|
801
|
+
) : (
|
|
802
|
+
<span style={{ color: '#999' }}>New conversation</span>
|
|
803
|
+
)}
|
|
804
|
+
</div>
|
|
805
|
+
<button
|
|
806
|
+
onClick={clearConversation}
|
|
807
|
+
style={{
|
|
808
|
+
padding: '5px 15px',
|
|
809
|
+
borderRadius: '6px',
|
|
810
|
+
border: '1px solid #ccc',
|
|
811
|
+
backgroundColor: '#fff',
|
|
812
|
+
cursor: 'pointer'
|
|
813
|
+
}}
|
|
814
|
+
>
|
|
815
|
+
Clear
|
|
816
|
+
</button>
|
|
817
|
+
</div>
|
|
818
|
+
|
|
819
|
+
{/* Messages */}
|
|
820
|
+
<div style={{
|
|
821
|
+
height: '500px',
|
|
822
|
+
overflowY: 'auto',
|
|
823
|
+
border: '1px solid #ddd',
|
|
824
|
+
borderRadius: '8px',
|
|
825
|
+
padding: '15px',
|
|
826
|
+
marginBottom: '15px',
|
|
827
|
+
backgroundColor: '#fafafa'
|
|
828
|
+
}}>
|
|
829
|
+
{messages.length === 0 ? (
|
|
830
|
+
<div style={{ textAlign: 'center', color: '#999', marginTop: '50px' }}>
|
|
831
|
+
<p>No messages yet. Start a conversation or load an existing one.</p>
|
|
832
|
+
<button
|
|
833
|
+
onClick={() => loadConversation('some-conversation-key')}
|
|
834
|
+
style={{
|
|
835
|
+
padding: '8px 16px',
|
|
836
|
+
borderRadius: '6px',
|
|
837
|
+
border: '1px solid #61dafb',
|
|
838
|
+
backgroundColor: '#61dafb',
|
|
839
|
+
color: '#fff',
|
|
840
|
+
cursor: 'pointer',
|
|
841
|
+
marginTop: '10px'
|
|
842
|
+
}}
|
|
843
|
+
>
|
|
844
|
+
Load Example Conversation
|
|
845
|
+
</button>
|
|
846
|
+
</div>
|
|
847
|
+
) : (
|
|
848
|
+
messages.map((msg, i) => (
|
|
849
|
+
<div
|
|
850
|
+
key={i}
|
|
851
|
+
style={{
|
|
852
|
+
padding: '12px',
|
|
853
|
+
margin: '8px 0',
|
|
854
|
+
borderRadius: '12px',
|
|
855
|
+
backgroundColor: msg.role === 'user' ? '#e3f2fd' : '#fff',
|
|
856
|
+
border: msg.role === 'assistant' ? '1px solid #e0e0e0' : 'none',
|
|
857
|
+
maxWidth: '85%',
|
|
858
|
+
marginLeft: msg.role === 'user' ? 'auto' : '0',
|
|
859
|
+
marginRight: msg.role === 'user' ? '0' : 'auto',
|
|
860
|
+
}}
|
|
861
|
+
>
|
|
862
|
+
<div style={{
|
|
863
|
+
display: 'flex',
|
|
864
|
+
justifyContent: 'space-between',
|
|
865
|
+
marginBottom: '6px',
|
|
866
|
+
fontSize: '12px',
|
|
867
|
+
color: '#666'
|
|
868
|
+
}}>
|
|
869
|
+
<strong style={{ color: msg.role === 'user' ? '#1976d2' : '#388e3c' }}>
|
|
870
|
+
{msg.role === 'user' ? '👤 You' : '🤖 AI'}
|
|
871
|
+
</strong>
|
|
872
|
+
|
|
873
|
+
{/* Show streaming indicator or status */}
|
|
874
|
+
{msg.isStreaming && (
|
|
875
|
+
<span style={{
|
|
876
|
+
color: '#ff6b6b',
|
|
877
|
+
fontStyle: 'italic',
|
|
878
|
+
fontSize: '11px'
|
|
879
|
+
}}>
|
|
880
|
+
{msg.status || 'streaming'} ●
|
|
881
|
+
</span>
|
|
882
|
+
)}
|
|
883
|
+
</div>
|
|
884
|
+
|
|
885
|
+
<div style={{
|
|
886
|
+
whiteSpace: 'pre-wrap',
|
|
887
|
+
wordBreak: 'break-word',
|
|
888
|
+
lineHeight: '1.5'
|
|
889
|
+
}}>
|
|
890
|
+
{msg.text || '...'}
|
|
891
|
+
</div>
|
|
892
|
+
</div>
|
|
893
|
+
))
|
|
894
|
+
)}
|
|
895
|
+
</div>
|
|
896
|
+
|
|
897
|
+
{/* Input */}
|
|
898
|
+
<div style={{ display: 'flex', gap: '10px' }}>
|
|
899
|
+
<input
|
|
900
|
+
type="text"
|
|
901
|
+
value={input}
|
|
902
|
+
onChange={e => setInput(e.target.value)}
|
|
903
|
+
onKeyDown={e => e.key === 'Enter' && !loading && sendMessage()}
|
|
904
|
+
placeholder={loading ? 'AI is responding...' : 'Type your message...'}
|
|
905
|
+
disabled={loading}
|
|
906
|
+
style={{
|
|
907
|
+
flex: 1,
|
|
908
|
+
padding: '12px 16px',
|
|
909
|
+
fontSize: '15px',
|
|
910
|
+
borderRadius: '8px',
|
|
911
|
+
border: '1px solid #ddd',
|
|
912
|
+
outline: 'none'
|
|
913
|
+
}}
|
|
914
|
+
/>
|
|
915
|
+
<button
|
|
916
|
+
onClick={sendMessage}
|
|
917
|
+
disabled={loading || !input.trim()}
|
|
918
|
+
style={{
|
|
919
|
+
padding: '12px 24px',
|
|
920
|
+
fontSize: '15px',
|
|
921
|
+
borderRadius: '8px',
|
|
922
|
+
border: 'none',
|
|
923
|
+
backgroundColor: loading ? '#ccc' : '#61dafb',
|
|
924
|
+
color: loading ? '#666' : '#fff',
|
|
925
|
+
cursor: loading ? 'not-allowed' : 'pointer',
|
|
926
|
+
fontWeight: 600
|
|
927
|
+
}}
|
|
928
|
+
>
|
|
929
|
+
{loading ? 'Sending...' : 'Send'}
|
|
930
|
+
</button>
|
|
931
|
+
</div>
|
|
932
|
+
|
|
933
|
+
{/* Helper Text */}
|
|
934
|
+
<div style={{
|
|
935
|
+
marginTop: '15px',
|
|
936
|
+
fontSize: '13px',
|
|
937
|
+
color: '#666',
|
|
938
|
+
textAlign: 'center'
|
|
939
|
+
}}>
|
|
940
|
+
💡 Messages are automatically saved to the repository when backend persistence is enabled.
|
|
941
|
+
<br />
|
|
942
|
+
Use the conversation list to browse and load previous conversations.
|
|
943
|
+
</div>
|
|
944
|
+
</div>
|
|
945
|
+
);
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
export default ChatWithHistory;
|
|
949
|
+
```
|
|
950
|
+
|
|
951
|
+
### Key Features Demonstrated
|
|
952
|
+
|
|
953
|
+
✅ **Load Historic Messages**: Converts `StoredMessage[]` → `ChatMessage[]`
|
|
954
|
+
✅ **Continue Conversation**: Uses same `conversationKey` to resume context
|
|
955
|
+
✅ **Real-Time Streaming**: Updates UI with `AiSceneResponse` chunks
|
|
956
|
+
✅ **Status Indicators**: Shows execution status during streaming
|
|
957
|
+
✅ **Seamless UX**: Historic + streaming messages in same UI
|
|
958
|
+
|
|
959
|
+
### Flow Diagram
|
|
960
|
+
|
|
961
|
+
```
|
|
962
|
+
1. User clicks "Load Conversation"
|
|
963
|
+
↓
|
|
964
|
+
2. GET /api/ai/default/conversations/{key}
|
|
965
|
+
↓
|
|
966
|
+
3. Receives StoredConversation (REST JSON)
|
|
967
|
+
├─ messages: StoredMessage[]
|
|
968
|
+
├─ conversationKey: "abc-123"
|
|
969
|
+
└─ timestamp, userId, isPublic
|
|
970
|
+
↓
|
|
971
|
+
4. Convert to ChatMessage[] and display
|
|
972
|
+
↓
|
|
973
|
+
5. User types new message
|
|
974
|
+
↓
|
|
975
|
+
6. POST /api/ai/default (SSE streaming)
|
|
976
|
+
settings: { conversationKey: "abc-123" }
|
|
977
|
+
↓
|
|
978
|
+
7. Receives AiSceneResponse events (SSE)
|
|
979
|
+
├─ status: "planning" → "executingScene" → "streaming"
|
|
980
|
+
├─ streamingChunk: "Hello", " world", "!"
|
|
981
|
+
└─ conversationKey: "abc-123" (same as before)
|
|
982
|
+
↓
|
|
983
|
+
8. Backend loads context from cache/repository
|
|
984
|
+
↓
|
|
985
|
+
9. LLM generates response using historic context
|
|
986
|
+
↓
|
|
987
|
+
10. Response streamed to UI in real-time
|
|
988
|
+
↓
|
|
989
|
+
11. Backend saves new messages to repository
|
|
990
|
+
↓
|
|
991
|
+
12. Conversation continues seamlessly
|
|
992
|
+
```
|
|
993
|
+
|
|
994
|
+
### Best Practices
|
|
995
|
+
|
|
996
|
+
1. **Separate concerns**: Use `StoredMessage` for storage, `AiSceneResponse` for streaming
|
|
997
|
+
2. **Flag streaming state**: Add `isStreaming` flag to distinguish live vs historic
|
|
998
|
+
3. **Show status**: Display execution status (`planning`, `executingScene`) during streaming
|
|
999
|
+
4. **Handle errors**: Wrap streaming in try-catch and show error messages
|
|
1000
|
+
5. **Auto-save**: Backend automatically persists conversations when repository is enabled
|
|
1001
|
+
|
|
1002
|
+
---
|
|
1003
|
+
|
|
1004
|
+
## 📸 Multi-Modal Content (Images, Audio, Video, PDFs)
|
|
1005
|
+
|
|
1006
|
+
PlayFramework supports **base64-encoded media content** in messages. The client provides helper utilities to convert Base64 data to Blob URLs for browser display.
|
|
1007
|
+
|
|
1008
|
+
### ContentUrlConverter Helper
|
|
1009
|
+
|
|
1010
|
+
Converts `AIContent` (base64 data) to Blob URLs that can be used in HTML `<img>`, `<audio>`, `<video>`, and `<iframe>` elements.
|
|
1011
|
+
|
|
1012
|
+
```typescript
|
|
1013
|
+
import { ContentUrlConverter, AIContent } from "@rystem/playframework-client";
|
|
1014
|
+
|
|
1015
|
+
const content: AIContent = {
|
|
1016
|
+
type: "data",
|
|
1017
|
+
data: "iVBORw0KGgoAAAANSUhEUgAA...", // Base64 JPEG
|
|
1018
|
+
mediaType: "image/jpeg"
|
|
1019
|
+
};
|
|
1020
|
+
|
|
1021
|
+
// Convert to Blob URL
|
|
1022
|
+
const url = ContentUrlConverter.toBlobUrl(content);
|
|
1023
|
+
|
|
1024
|
+
// Use in <img> tag
|
|
1025
|
+
<img src={url} alt="Image" />
|
|
1026
|
+
|
|
1027
|
+
// IMPORTANT: Cleanup when done (frees memory!)
|
|
1028
|
+
ContentUrlConverter.revokeUrl(url);
|
|
1029
|
+
```
|
|
1030
|
+
|
|
1031
|
+
### API Methods
|
|
1032
|
+
|
|
1033
|
+
#### `toBlob(content: AIContent): Blob | null`
|
|
1034
|
+
Decodes Base64 string to Blob object.
|
|
1035
|
+
|
|
1036
|
+
```typescript
|
|
1037
|
+
const blob = ContentUrlConverter.toBlob(content);
|
|
1038
|
+
```
|
|
1039
|
+
|
|
1040
|
+
#### `toBlobUrl(content: AIContent, cacheKey?: string): string | null`
|
|
1041
|
+
Creates `blob:` URL for browser display. Supports optional caching.
|
|
1042
|
+
|
|
1043
|
+
```typescript
|
|
1044
|
+
const url = ContentUrlConverter.toBlobUrl(content, 'image-123');
|
|
1045
|
+
```
|
|
1046
|
+
|
|
1047
|
+
#### `revokeUrl(url: string, cacheKey?: string): void`
|
|
1048
|
+
Revokes Blob URL to free memory. **Always call this when done!**
|
|
1049
|
+
|
|
1050
|
+
```typescript
|
|
1051
|
+
ContentUrlConverter.revokeUrl(url, 'image-123');
|
|
1052
|
+
```
|
|
1053
|
+
|
|
1054
|
+
#### `clearCache(): void`
|
|
1055
|
+
Revokes all cached URLs at once.
|
|
1056
|
+
|
|
1057
|
+
```typescript
|
|
1058
|
+
ContentUrlConverter.clearCache();
|
|
1059
|
+
```
|
|
1060
|
+
|
|
1061
|
+
#### `downloadAsFile(content: AIContent, filename?: string): void`
|
|
1062
|
+
Triggers browser download.
|
|
1063
|
+
|
|
1064
|
+
```typescript
|
|
1065
|
+
ContentUrlConverter.downloadAsFile(content, 'image.jpg');
|
|
1066
|
+
```
|
|
1067
|
+
|
|
1068
|
+
#### `getFileExtension(mediaType?: string): string`
|
|
1069
|
+
Maps MIME type to file extension.
|
|
1070
|
+
|
|
1071
|
+
```typescript
|
|
1072
|
+
const ext = ContentUrlConverter.getFileExtension('image/jpeg'); // ".jpg"
|
|
1073
|
+
```
|
|
1074
|
+
|
|
1075
|
+
---
|
|
1076
|
+
|
|
1077
|
+
### React Example: Image Viewer
|
|
1078
|
+
|
|
1079
|
+
```tsx
|
|
1080
|
+
import { useState, useEffect } from 'react';
|
|
1081
|
+
import { ContentUrlConverter, AIContent } from "@rystem/playframework-client";
|
|
1082
|
+
|
|
1083
|
+
interface ImageViewerProps {
|
|
1084
|
+
content: AIContent;
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
function ImageViewer({ content }: ImageViewerProps) {
|
|
1088
|
+
const [url, setUrl] = useState<string | null>(null);
|
|
1089
|
+
|
|
1090
|
+
useEffect(() => {
|
|
1091
|
+
// Create Blob URL when component mounts
|
|
1092
|
+
const blobUrl = ContentUrlConverter.toBlobUrl(content, `image-${Date.now()}`);
|
|
1093
|
+
setUrl(blobUrl);
|
|
1094
|
+
|
|
1095
|
+
// Cleanup when component unmounts (important for memory!)
|
|
1096
|
+
return () => {
|
|
1097
|
+
if (blobUrl) {
|
|
1098
|
+
ContentUrlConverter.revokeUrl(blobUrl);
|
|
1099
|
+
}
|
|
1100
|
+
};
|
|
1101
|
+
}, [content]);
|
|
1102
|
+
|
|
1103
|
+
if (!url) return <div>Loading image...</div>;
|
|
1104
|
+
|
|
1105
|
+
return (
|
|
1106
|
+
<div>
|
|
1107
|
+
<img src={url} alt="Image" style={{ maxWidth: '100%' }} />
|
|
1108
|
+
<button onClick={() => ContentUrlConverter.downloadAsFile(content, 'image.jpg')}>
|
|
1109
|
+
Download
|
|
1110
|
+
</button>
|
|
1111
|
+
</div>
|
|
1112
|
+
);
|
|
1113
|
+
}
|
|
1114
|
+
```
|
|
1115
|
+
|
|
1116
|
+
---
|
|
1117
|
+
|
|
1118
|
+
### React Example: Auto-Detection Content Viewer
|
|
1119
|
+
|
|
1120
|
+
```tsx
|
|
1121
|
+
import { ContentUrlConverter, AIContent } from "@rystem/playframework-client";
|
|
1122
|
+
|
|
1123
|
+
function ContentViewer({ content }: { content: AIContent }) {
|
|
1124
|
+
const mediaType = content.mediaType?.toLowerCase() || '';
|
|
1125
|
+
const [url, setUrl] = useState<string | null>(null);
|
|
1126
|
+
|
|
1127
|
+
useEffect(() => {
|
|
1128
|
+
const blobUrl = ContentUrlConverter.toBlobUrl(content);
|
|
1129
|
+
setUrl(blobUrl);
|
|
1130
|
+
|
|
1131
|
+
return () => {
|
|
1132
|
+
if (blobUrl) ContentUrlConverter.revokeUrl(blobUrl);
|
|
1133
|
+
};
|
|
1134
|
+
}, [content]);
|
|
1135
|
+
|
|
1136
|
+
if (!url) return <div>Loading...</div>;
|
|
1137
|
+
|
|
1138
|
+
// Image
|
|
1139
|
+
if (mediaType.startsWith('image/')) {
|
|
1140
|
+
return <img src={url} alt="Image" style={{ maxWidth: '100%' }} />;
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
// Audio
|
|
1144
|
+
if (mediaType.startsWith('audio/')) {
|
|
1145
|
+
return (
|
|
1146
|
+
<audio controls style={{ width: '100%' }}>
|
|
1147
|
+
<source src={url} type={mediaType} />
|
|
1148
|
+
</audio>
|
|
1149
|
+
);
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
// Video
|
|
1153
|
+
if (mediaType.startsWith('video/')) {
|
|
1154
|
+
return (
|
|
1155
|
+
<video controls style={{ maxWidth: '100%' }}>
|
|
1156
|
+
<source src={url} type={mediaType} />
|
|
1157
|
+
</video>
|
|
1158
|
+
);
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
// PDF
|
|
1162
|
+
if (mediaType === 'application/pdf') {
|
|
1163
|
+
return (
|
|
1164
|
+
<iframe
|
|
1165
|
+
src={url}
|
|
1166
|
+
title="PDF Document"
|
|
1167
|
+
style={{ width: '100%', height: '600px', border: '1px solid #ddd' }}
|
|
1168
|
+
/>
|
|
1169
|
+
);
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
// Fallback for unknown types
|
|
1173
|
+
return (
|
|
1174
|
+
<div>
|
|
1175
|
+
<p>📎 Attachment: {content.mediaType || 'unknown type'}</p>
|
|
1176
|
+
<button onClick={() => ContentUrlConverter.downloadAsFile(content)}>
|
|
1177
|
+
Download File
|
|
1178
|
+
</button>
|
|
1179
|
+
</div>
|
|
1180
|
+
);
|
|
1181
|
+
}
|
|
1182
|
+
```
|
|
1183
|
+
|
|
1184
|
+
---
|
|
1185
|
+
|
|
1186
|
+
### includeContents Parameter
|
|
1187
|
+
|
|
1188
|
+
When loading conversations, control whether to fetch base64 content:
|
|
1189
|
+
|
|
1190
|
+
```typescript
|
|
1191
|
+
// ❌ List conversations WITHOUT media (faster, smaller payload)
|
|
1192
|
+
const list = await client.listConversations({
|
|
1193
|
+
includeContents: false, // Default: false
|
|
1194
|
+
take: 50
|
|
1195
|
+
});
|
|
1196
|
+
|
|
1197
|
+
// ✅ Load single conversation WITH media (for display)
|
|
1198
|
+
const conv = await client.getConversation(key, true); // includeContents=true
|
|
1199
|
+
```
|
|
1200
|
+
|
|
1201
|
+
**Why this matters:**
|
|
1202
|
+
|
|
1203
|
+
| Operation | includeContents | Payload Size | Speed |
|
|
1204
|
+
|-----------|----------------|--------------|-------|
|
|
1205
|
+
| List 100 conversations | `false` | ~50 KB | ⚡ Fast (~50ms) |
|
|
1206
|
+
| List 100 conversations | `true` | ~5-50 MB | 🐢 Slow (~500ms) |
|
|
1207
|
+
| Get single conversation | `true` | ~50-500 KB | ✅ Acceptable |
|
|
1208
|
+
|
|
1209
|
+
**Best Practice**: Always use `includeContents=false` for list operations, `true` only when loading a conversation for display.
|
|
1210
|
+
|
|
1211
|
+
---
|
|
1212
|
+
|
|
1213
|
+
### Full Example: Chat with Multi-Modal Support
|
|
1214
|
+
|
|
1215
|
+
```tsx
|
|
1216
|
+
import { useState, useEffect } from 'react';
|
|
1217
|
+
import { usePlayFramework, StoredMessage, AIContent, ContentUrlConverter } from "@rystem/playframework-client";
|
|
1218
|
+
|
|
1219
|
+
function ChatWithMedia() {
|
|
1220
|
+
const client = usePlayFramework('default');
|
|
1221
|
+
const [messages, setMessages] = useState<StoredMessage[]>([]);
|
|
1222
|
+
const [conversationKey, setConversationKey] = useState<string | null>(null);
|
|
1223
|
+
|
|
1224
|
+
const loadConversation = async (key: string) => {
|
|
1225
|
+
// Load conversation WITH contents
|
|
1226
|
+
const conv = await client.getConversation(key, true);
|
|
1227
|
+
|
|
1228
|
+
if (conv) {
|
|
1229
|
+
setMessages(conv.messages);
|
|
1230
|
+
setConversationKey(conv.conversationKey);
|
|
1231
|
+
}
|
|
1232
|
+
};
|
|
1233
|
+
|
|
1234
|
+
return (
|
|
1235
|
+
<div>
|
|
1236
|
+
<h1>Chat with Media Support</h1>
|
|
1237
|
+
|
|
1238
|
+
{messages.map((msg, i) => (
|
|
1239
|
+
<div key={i} style={{
|
|
1240
|
+
backgroundColor: msg.role === 'user' ? '#e3f2fd' : '#fff',
|
|
1241
|
+
padding: '12px',
|
|
1242
|
+
margin: '8px 0',
|
|
1243
|
+
borderRadius: '8px'
|
|
1244
|
+
}}>
|
|
1245
|
+
<strong>{msg.role === 'user' ? '👤 You' : '🤖 AI'}</strong>
|
|
1246
|
+
<p>{msg.text}</p>
|
|
1247
|
+
|
|
1248
|
+
{/* Display attached content (images, PDFs, etc.) */}
|
|
1249
|
+
{msg.contents && msg.contents.length > 0 && (
|
|
1250
|
+
<div style={{ marginTop: '8px' }}>
|
|
1251
|
+
{msg.contents.map((content, idx) => (
|
|
1252
|
+
<ContentViewer key={idx} content={content} />
|
|
1253
|
+
))}
|
|
1254
|
+
</div>
|
|
1255
|
+
)}
|
|
1256
|
+
</div>
|
|
1257
|
+
))}
|
|
1258
|
+
|
|
1259
|
+
<button onClick={() => loadConversation('example-key')}>
|
|
1260
|
+
Load Example Conversation
|
|
1261
|
+
</button>
|
|
1262
|
+
</div>
|
|
1263
|
+
);
|
|
1264
|
+
}
|
|
1265
|
+
```
|
|
1266
|
+
|
|
1267
|
+
---
|
|
1268
|
+
|
|
1269
|
+
### Memory Management Best Practices
|
|
1270
|
+
|
|
1271
|
+
1. **Always cleanup Blob URLs**: Use `useEffect` cleanup function in React
|
|
1272
|
+
2. **Use caching for repeated content**: Pass `cacheKey` parameter
|
|
1273
|
+
3. **Clear cache on unmount**: Call `ContentUrlConverter.clearCache()` when appropriate
|
|
1274
|
+
4. **Lazy load media**: Only convert to Blob URL when needed for display
|
|
1275
|
+
5. **Use includeContents wisely**: Exclude contents from list operations
|
|
1276
|
+
|
|
1277
|
+
**Example cleanup:**
|
|
1278
|
+
```tsx
|
|
1279
|
+
useEffect(() => {
|
|
1280
|
+
const url = ContentUrlConverter.toBlobUrl(content);
|
|
1281
|
+
setImageUrl(url);
|
|
1282
|
+
|
|
1283
|
+
// Cleanup when component unmounts
|
|
1284
|
+
return () => {
|
|
1285
|
+
if (url) ContentUrlConverter.revokeUrl(url);
|
|
1286
|
+
};
|
|
1287
|
+
}, [content]);
|
|
1288
|
+
|
|
1289
|
+
// Clear all on app unmount
|
|
1290
|
+
useEffect(() => {
|
|
1291
|
+
return () => ContentUrlConverter.clearCache();
|
|
1292
|
+
}, []);
|
|
1293
|
+
```
|
|
1294
|
+
|
|
1295
|
+
---
|
|
1296
|
+
|
|
1297
|
+
## 🎙️ Browser Voice (Web Speech API)
|
|
1298
|
+
|
|
1299
|
+
The client includes a fully client-side voice pipeline using the **Web Speech API**. This provides zero-latency speech recognition (STT) and text-to-speech (TTS) directly in the browser — no server-side Whisper or TTS-1 required.
|
|
1300
|
+
|
|
1301
|
+
> **Note:** Browser voice uses the browser's built-in speech engines. For higher quality (OpenAI Whisper + TTS-1), use the [server-side voice pipeline](#server-side-voice-pipeline) instead.
|
|
1302
|
+
|
|
1303
|
+
### Browser Support
|
|
1304
|
+
|
|
1305
|
+
| Feature | Chrome | Edge | Safari | Firefox |
|
|
1306
|
+
|---|---|---|---|---|
|
|
1307
|
+
| SpeechRecognition | ✅ | ✅ | ✅ | ❌ |
|
|
1308
|
+
| SpeechSynthesis | ✅ | ✅ | ✅ | ✅ |
|
|
1309
|
+
|
|
1310
|
+
### Quick Start
|
|
1311
|
+
|
|
1312
|
+
```typescript
|
|
1313
|
+
import {
|
|
1314
|
+
PlayFrameworkServices,
|
|
1315
|
+
BrowserVoiceClient,
|
|
1316
|
+
} from "@rystem/playframework-client";
|
|
1317
|
+
|
|
1318
|
+
// 1. Configure PlayFramework client
|
|
1319
|
+
await PlayFrameworkServices.configure("default", "http://localhost:5158/api/ai");
|
|
1320
|
+
const client = PlayFrameworkServices.resolve("default");
|
|
424
1321
|
|
|
425
|
-
|
|
1322
|
+
// 2. Create browser voice client
|
|
1323
|
+
const voice = new BrowserVoiceClient(
|
|
1324
|
+
client,
|
|
1325
|
+
{ lang: "it-IT" }, // STT options
|
|
1326
|
+
{ lang: "it-IT", rate: 1.0 }, // TTS options
|
|
1327
|
+
);
|
|
1328
|
+
|
|
1329
|
+
// 3. Full voice loop: listen → LLM → speak
|
|
1330
|
+
for await (const event of voice.executeWithBrowserVoice()) {
|
|
1331
|
+
if (event.voiceStatus === "recognized") {
|
|
1332
|
+
console.log("User said:", event.transcript);
|
|
1333
|
+
}
|
|
1334
|
+
if (event.response?.message) {
|
|
1335
|
+
console.log("AI:", event.response.message);
|
|
1336
|
+
}
|
|
1337
|
+
if (event.voiceStatus === "speechComplete") {
|
|
1338
|
+
console.log("Done speaking.");
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
```
|
|
1342
|
+
|
|
1343
|
+
### BrowserSpeechRecognizer
|
|
1344
|
+
|
|
1345
|
+
Wraps `SpeechRecognition` / `webkitSpeechRecognition` for speech-to-text.
|
|
426
1346
|
|
|
427
1347
|
```typescript
|
|
428
|
-
|
|
1348
|
+
import { BrowserSpeechRecognizer } from "@rystem/playframework-client";
|
|
429
1349
|
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
1350
|
+
const recognizer = new BrowserSpeechRecognizer({ lang: "en-US" });
|
|
1351
|
+
|
|
1352
|
+
// One-shot recognition (returns a Promise)
|
|
1353
|
+
const text = await recognizer.listen(10000); // 10s timeout
|
|
1354
|
+
console.log("You said:", text);
|
|
1355
|
+
|
|
1356
|
+
// Continuous recognition with callbacks
|
|
1357
|
+
recognizer.start({
|
|
1358
|
+
onResult: (result) => console.log(result.transcript, result.isFinal),
|
|
1359
|
+
onEnd: () => console.log("Stopped"),
|
|
1360
|
+
onError: (err) => console.error(err),
|
|
1361
|
+
});
|
|
1362
|
+
|
|
1363
|
+
// Change language at runtime
|
|
1364
|
+
recognizer.setLang("it-IT");
|
|
1365
|
+
|
|
1366
|
+
// Stop / abort
|
|
1367
|
+
recognizer.stop(); // graceful
|
|
1368
|
+
recognizer.abort(); // immediate
|
|
1369
|
+
```
|
|
1370
|
+
|
|
1371
|
+
#### Options
|
|
1372
|
+
|
|
1373
|
+
| Property | Type | Default | Description |
|
|
1374
|
+
|---|---|---|---|
|
|
1375
|
+
| `lang` | `string` | Browser default | BCP-47 language code (e.g. `'it-IT'`, `'en-US'`) |
|
|
1376
|
+
| `interimResults` | `boolean` | `true` | Return partial results while speaking |
|
|
1377
|
+
| `continuous` | `boolean` | `false` | Auto-restart recognition on end |
|
|
1378
|
+
| `maxAlternatives` | `number` | `1` | Max recognition alternatives |
|
|
1379
|
+
|
|
1380
|
+
### BrowserSpeechSynthesizer
|
|
1381
|
+
|
|
1382
|
+
Wraps `SpeechSynthesis` for text-to-speech, with built-in **sentence accumulation** for streaming scenarios and **Markdown stripping**.
|
|
1383
|
+
|
|
1384
|
+
```typescript
|
|
1385
|
+
import { BrowserSpeechSynthesizer } from "@rystem/playframework-client";
|
|
1386
|
+
|
|
1387
|
+
const synth = new BrowserSpeechSynthesizer({ lang: "it-IT", rate: 1.1 });
|
|
1388
|
+
|
|
1389
|
+
// Simple: speak a complete text
|
|
1390
|
+
await synth.speak("Ciao, come stai?");
|
|
1391
|
+
|
|
1392
|
+
// Streaming: feed chunks as they arrive from the LLM
|
|
1393
|
+
synth.feedChunk("Ciao, ");
|
|
1394
|
+
synth.feedChunk("come stai? ");
|
|
1395
|
+
synth.feedChunk("Tutto bene.");
|
|
1396
|
+
await synth.flushAndWait(); // speak remaining buffer and wait
|
|
1397
|
+
|
|
1398
|
+
// Cancel ongoing speech
|
|
1399
|
+
synth.cancel();
|
|
1400
|
+
|
|
1401
|
+
// Change language at runtime
|
|
1402
|
+
synth.setLang("en-US");
|
|
1403
|
+
|
|
1404
|
+
// Strip Markdown before speaking
|
|
1405
|
+
const clean = BrowserSpeechSynthesizer.stripMarkdown("**Hello** _world_");
|
|
1406
|
+
// → "Hello world"
|
|
1407
|
+
```
|
|
1408
|
+
|
|
1409
|
+
#### Options
|
|
1410
|
+
|
|
1411
|
+
| Property | Type | Default | Description |
|
|
1412
|
+
|---|---|---|---|
|
|
1413
|
+
| `lang` | `string` | Browser default | BCP-47 language code |
|
|
1414
|
+
| `rate` | `number` | `1` | Speech rate (0.1 – 10) |
|
|
1415
|
+
| `pitch` | `number` | `1` | Pitch (0 – 2) |
|
|
1416
|
+
| `volume` | `number` | `1` | Volume (0 – 1) |
|
|
1417
|
+
| `voiceName` | `string` | Auto | Preferred voice name (e.g. `'Google italiano'`) |
|
|
1418
|
+
| `sentenceDelimiters` | `string[]` | `['.','!','?','\n']` | Characters that trigger sentence flush |
|
|
1419
|
+
| `minCharsBeforeSpeak` | `number` | `20` | Min chars before flushing a sentence |
|
|
1420
|
+
|
|
1421
|
+
#### Streaming Sentence Accumulation
|
|
1422
|
+
|
|
1423
|
+
When using `feedChunk()`, text is buffered until a sentence delimiter is found and the buffer reaches `minCharsBeforeSpeak`. This prevents TTS from speaking tiny fragments:
|
|
1424
|
+
|
|
1425
|
+
```
|
|
1426
|
+
feedChunk("Ciao, ") → buffer: "Ciao, " (no delimiter → wait)
|
|
1427
|
+
feedChunk("come stai? ") → "Ciao, come stai?" → speaks! (delimiter '?' found)
|
|
1428
|
+
feedChunk("Bene. Grazie.") → "Bene." → speaks! then "Grazie." → speaks!
|
|
1429
|
+
```
|
|
1430
|
+
|
|
1431
|
+
### BrowserVoiceClient
|
|
1432
|
+
|
|
1433
|
+
Orchestrates the full voice loop: **STT → PlayFramework → TTS**.
|
|
1434
|
+
|
|
1435
|
+
```typescript
|
|
1436
|
+
import { BrowserVoiceClient } from "@rystem/playframework-client";
|
|
1437
|
+
|
|
1438
|
+
const voice = new BrowserVoiceClient(
|
|
1439
|
+
client, // PlayFrameworkClient
|
|
1440
|
+
{ lang: "it-IT" }, // BrowserSpeechRecognizerOptions
|
|
1441
|
+
{ lang: "it-IT", rate: 1.0 }, // BrowserSpeechSynthesizerOptions
|
|
1442
|
+
);
|
|
1443
|
+
|
|
1444
|
+
// Step-by-step mode (default) — speaks complete step messages
|
|
1445
|
+
for await (const ev of voice.executeWithBrowserVoice({
|
|
1446
|
+
streamingMode: "stepByStep",
|
|
1447
|
+
})) {
|
|
1448
|
+
console.log(ev.voiceStatus, ev.response?.status);
|
|
1449
|
+
}
|
|
1450
|
+
|
|
1451
|
+
// Token streaming mode — speaks tokens as they arrive
|
|
1452
|
+
for await (const ev of voice.executeWithBrowserVoice({
|
|
1453
|
+
streamingMode: "tokenStreaming",
|
|
1454
|
+
})) {
|
|
1455
|
+
if (ev.response?.streamingChunk) {
|
|
1456
|
+
process.stdout.write(ev.response.streamingChunk);
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1460
|
+
// Skip STT — send text directly and speak the response
|
|
1461
|
+
for await (const ev of voice.speakResponse("Tell me a joke", "stepByStep")) {
|
|
1462
|
+
// TTS speaks the AI response
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
// Cancel everything
|
|
1466
|
+
voice.cancelAll();
|
|
1467
|
+
|
|
1468
|
+
// Or cancel just audio (text stream continues)
|
|
1469
|
+
voice.cancelSpeech();
|
|
1470
|
+
|
|
1471
|
+
// Or cancel the HTTP stream + audio
|
|
1472
|
+
voice.cancelStream();
|
|
1473
|
+
|
|
1474
|
+
// Check if a flow is active
|
|
1475
|
+
console.log(voice.isStreaming);
|
|
1476
|
+
```
|
|
1477
|
+
|
|
1478
|
+
#### Options (`BrowserVoiceOptions`)
|
|
1479
|
+
|
|
1480
|
+
| Property | Type | Default | Description |
|
|
1481
|
+
|---|---|---|---|
|
|
1482
|
+
| `text` | `string` | — | Skip STT, use this text directly |
|
|
1483
|
+
| `streamingMode` | `'stepByStep'` \| `'tokenStreaming'` | `'stepByStep'` | How to stream the LLM interaction |
|
|
1484
|
+
| `request` | `Partial<PlayFrameworkRequest>` | — | Base request (settings, conversationKey, etc.) |
|
|
1485
|
+
| `recognitionTimeoutMs` | `number` | `15000` | STT listening timeout |
|
|
1486
|
+
| `signal` | `AbortSignal` | — | Cancel the entire voice flow |
|
|
1487
|
+
| `speakResponse` | `boolean` | `true` | Whether TTS speaks the LLM response |
|
|
1488
|
+
| `useVoiceStyle` | `boolean` | `true` | When `true`, tells the server to inject a voice-style system instruction (conversational tone, no tables/markdown). Set to `false` to keep rich formatting even in voice mode |
|
|
1489
|
+
|
|
1490
|
+
#### Voice Events
|
|
1491
|
+
|
|
1492
|
+
| `voiceStatus` | Description |
|
|
1493
|
+
|---|---|
|
|
1494
|
+
| `'recognizing'` | STT is listening for speech |
|
|
1495
|
+
| `'recognized'` | STT captured the transcript |
|
|
1496
|
+
| `'speaking'` | TTS is speaking |
|
|
1497
|
+
| `'speechComplete'` | TTS finished all queued speech |
|
|
1498
|
+
|
|
1499
|
+
#### Status Filtering
|
|
1500
|
+
|
|
1501
|
+
In `stepByStep` mode, the client automatically skips non-speakable statuses (system messages, tool calls, planning, etc.) and only speaks `running`, `completed`, and `streaming` responses.
|
|
1502
|
+
|
|
1503
|
+
#### Voice-Style Responses
|
|
1504
|
+
|
|
1505
|
+
By default, the `BrowserVoiceClient` sets `isVoiceMode: true` on every request. This tells the server to inject a system instruction that makes the LLM respond in a **conversational, speech-friendly style**:
|
|
1506
|
+
|
|
1507
|
+
- No tables, bullet lists, numbered lists, or markdown formatting
|
|
1508
|
+
- Short, clear sentences with natural discourse markers
|
|
1509
|
+
- Numbers spelled out when small ("three" instead of "3")
|
|
1510
|
+
- Concise responses aimed at ~30 seconds of spoken delivery
|
|
1511
|
+
|
|
1512
|
+
If the user explicitly asks for a table or structured format, the LLM will still provide it.
|
|
1513
|
+
|
|
1514
|
+
**To disable** (keep rich formatting even in voice mode):
|
|
1515
|
+
|
|
1516
|
+
```typescript
|
|
1517
|
+
for await (const ev of voice.executeWithBrowserVoice({
|
|
1518
|
+
useVoiceStyle: false, // voice I/O but formatted responses
|
|
1519
|
+
})) { ... }
|
|
1520
|
+
```
|
|
1521
|
+
|
|
1522
|
+
The voice-style instruction is fully customizable on the server via `VoiceSettings.VoiceStyleInstruction`.
|
|
1523
|
+
|
|
1524
|
+
### React Example: Voice Chat
|
|
1525
|
+
|
|
1526
|
+
```tsx
|
|
1527
|
+
import { usePlayFramework, BrowserVoiceClient } from "@rystem/playframework-client";
|
|
1528
|
+
import { useState, useRef, useEffect } from "react";
|
|
1529
|
+
|
|
1530
|
+
function VoiceChat() {
|
|
1531
|
+
const client = usePlayFramework("default");
|
|
1532
|
+
const [listening, setListening] = useState(false);
|
|
1533
|
+
const [transcript, setTranscript] = useState("");
|
|
1534
|
+
const [response, setResponse] = useState("");
|
|
1535
|
+
const [lang, setLang] = useState(navigator.language || "en-US");
|
|
1536
|
+
const voiceRef = useRef<BrowserVoiceClient | null>(null);
|
|
1537
|
+
|
|
1538
|
+
useEffect(() => {
|
|
1539
|
+
voiceRef.current = new BrowserVoiceClient(
|
|
1540
|
+
client,
|
|
1541
|
+
{ lang },
|
|
1542
|
+
{ lang, rate: 1.0 },
|
|
1543
|
+
);
|
|
1544
|
+
}, [client]);
|
|
1545
|
+
|
|
1546
|
+
// Sync language changes
|
|
1547
|
+
useEffect(() => {
|
|
1548
|
+
if (voiceRef.current) {
|
|
1549
|
+
voiceRef.current.getRecognizer().setLang(lang);
|
|
1550
|
+
voiceRef.current.getSynthesizer().setLang(lang);
|
|
438
1551
|
}
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
|
|
1552
|
+
}, [lang]);
|
|
1553
|
+
|
|
1554
|
+
const handleVoice = async () => {
|
|
1555
|
+
if (!voiceRef.current) return;
|
|
1556
|
+
setListening(true);
|
|
1557
|
+
setTranscript("");
|
|
1558
|
+
setResponse("");
|
|
1559
|
+
|
|
1560
|
+
try {
|
|
1561
|
+
for await (const event of voiceRef.current.executeWithBrowserVoice({
|
|
1562
|
+
streamingMode: "tokenStreaming",
|
|
1563
|
+
})) {
|
|
1564
|
+
if (event.voiceStatus === "recognized") {
|
|
1565
|
+
setTranscript(event.transcript ?? "");
|
|
1566
|
+
}
|
|
1567
|
+
if (event.response?.streamingChunk) {
|
|
1568
|
+
setResponse(prev => prev + event.response!.streamingChunk);
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
} finally {
|
|
1572
|
+
setListening(false);
|
|
442
1573
|
}
|
|
1574
|
+
};
|
|
1575
|
+
|
|
1576
|
+
return (
|
|
1577
|
+
<div>
|
|
1578
|
+
<select value={lang} onChange={e => setLang(e.target.value)}>
|
|
1579
|
+
<option value="en-US">English</option>
|
|
1580
|
+
<option value="it-IT">Italiano</option>
|
|
1581
|
+
<option value="es-ES">Español</option>
|
|
1582
|
+
<option value="fr-FR">Français</option>
|
|
1583
|
+
<option value="de-DE">Deutsch</option>
|
|
1584
|
+
</select>
|
|
1585
|
+
|
|
1586
|
+
<button onClick={handleVoice} disabled={listening}>
|
|
1587
|
+
{listening ? "🎤 Listening..." : "🎤 Speak"}
|
|
1588
|
+
</button>
|
|
1589
|
+
|
|
1590
|
+
{transcript && <p><strong>You:</strong> {transcript}</p>}
|
|
1591
|
+
{response && <p><strong>AI:</strong> {response}</p>}
|
|
1592
|
+
</div>
|
|
1593
|
+
);
|
|
1594
|
+
}
|
|
1595
|
+
```
|
|
1596
|
+
|
|
1597
|
+
### Server-Side Voice Pipeline
|
|
1598
|
+
|
|
1599
|
+
For production scenarios requiring higher-quality STT/TTS (OpenAI Whisper + TTS-1), the server-side voice pipeline handles everything server-side. See the [backend README](https://github.com/KeyserDSoze/Rystem/tree/master/src/AI/Rystem.PlayFramework) for the `WithVoice()` builder and `IVoiceAdapter` setup.
|
|
1600
|
+
|
|
1601
|
+
### Choosing Between Browser and Server Voice
|
|
1602
|
+
|
|
1603
|
+
| Aspect | Browser Voice | Server Voice |
|
|
1604
|
+
|---|---|---|
|
|
1605
|
+
| **Latency** | Zero (local) | Network round-trip |
|
|
1606
|
+
| **Quality** | Browser engine dependent | OpenAI Whisper + TTS-1 (high) |
|
|
1607
|
+
| **Languages** | Depends on browser/OS voices | All Whisper-supported languages |
|
|
1608
|
+
| **Cost** | Free | OpenAI API costs |
|
|
1609
|
+
| **Privacy** | Audio stays on device | Audio sent to server |
|
|
1610
|
+
| **Offline** | Works offline (TTS only) | Requires server |
|
|
1611
|
+
| **Setup** | Zero config | Requires `IVoiceAdapter` + Azure OpenAI |
|
|
1612
|
+
|
|
1613
|
+
---
|
|
1614
|
+
|
|
1615
|
+
## 🚫 Cancellation
|
|
1616
|
+
|
|
1617
|
+
The client provides **three levels of cancellation** that work across all endpoints.
|
|
1618
|
+
When the HTTP stream is aborted the .NET server automatically receives a cancelled `CancellationToken` and stops processing.
|
|
1619
|
+
|
|
1620
|
+
### 1. Cancel via `AbortController` (all endpoints)
|
|
1621
|
+
|
|
1622
|
+
Every method that performs a network call accepts an `AbortSignal`.
|
|
1623
|
+
Create an `AbortController`, pass its signal, and call `controller.abort()` to cancel:
|
|
1624
|
+
|
|
1625
|
+
```typescript
|
|
1626
|
+
const controller = new AbortController();
|
|
1627
|
+
|
|
1628
|
+
// Works with step-by-step, token streaming, voice, and all conversation methods
|
|
1629
|
+
const stream = client.executeStepByStep(
|
|
1630
|
+
{ message: "Long task..." },
|
|
1631
|
+
controller.signal
|
|
1632
|
+
);
|
|
1633
|
+
|
|
1634
|
+
try {
|
|
1635
|
+
for await (const step of stream) {
|
|
1636
|
+
console.log(step.message);
|
|
443
1637
|
}
|
|
444
|
-
}
|
|
1638
|
+
} catch (error) {
|
|
1639
|
+
if (error instanceof DOMException && error.name === "AbortError") {
|
|
1640
|
+
console.log("Request cancelled");
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
445
1643
|
|
|
446
1644
|
// Cancel after 5 seconds
|
|
447
1645
|
setTimeout(() => controller.abort(), 5000);
|
|
448
1646
|
```
|
|
449
1647
|
|
|
1648
|
+
The same pattern applies to every endpoint:
|
|
1649
|
+
|
|
1650
|
+
```typescript
|
|
1651
|
+
// Token streaming
|
|
1652
|
+
client.executeTokenStreaming(request, controller.signal);
|
|
1653
|
+
|
|
1654
|
+
// Server voice pipeline
|
|
1655
|
+
client.executeVoice({ audio: blob, signal: controller.signal });
|
|
1656
|
+
|
|
1657
|
+
// Conversation management
|
|
1658
|
+
client.listConversations(params, controller.signal);
|
|
1659
|
+
client.getConversation(key, false, controller.signal);
|
|
1660
|
+
client.deleteConversation(key, controller.signal);
|
|
1661
|
+
```
|
|
1662
|
+
|
|
1663
|
+
### 2. BrowserVoiceClient — Granular Cancellation
|
|
1664
|
+
|
|
1665
|
+
`BrowserVoiceClient` exposes **four** cancellation methods with different granularity:
|
|
1666
|
+
|
|
1667
|
+
| Method | Audio (TTS) | HTTP Stream | Recognition | Use Case |
|
|
1668
|
+
|---|---|---|---|---|
|
|
1669
|
+
| `cancelSpeech()` | ✅ Stopped | ❌ Continues | ❌ Continues | Mute audio but keep reading text |
|
|
1670
|
+
| `cancelStream()` | ✅ Stopped | ✅ Aborted | ❌ — | Stop text + audio (no more data from server) |
|
|
1671
|
+
| `stopRecognition()` | ❌ — | ❌ — | ✅ Stopped | Stop listening for speech |
|
|
1672
|
+
| `cancelAll()` | ✅ Stopped | ✅ Aborted | ✅ Stopped | Stop everything at once |
|
|
1673
|
+
|
|
1674
|
+
#### Stop audio only (keep text streaming)
|
|
1675
|
+
|
|
1676
|
+
```typescript
|
|
1677
|
+
const voice = new BrowserVoiceClient(client, { lang: 'en-US' });
|
|
1678
|
+
|
|
1679
|
+
// Start voice flow
|
|
1680
|
+
const flowPromise = (async () => {
|
|
1681
|
+
for await (const event of voice.executeWithBrowserVoice({ text: "Tell me a story" })) {
|
|
1682
|
+
// You still receive text events even after cancelSpeech()
|
|
1683
|
+
if (event.response?.message) {
|
|
1684
|
+
appendToUI(event.response.message);
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
1687
|
+
})();
|
|
1688
|
+
|
|
1689
|
+
// Stop audio after 3 seconds, but keep receiving text
|
|
1690
|
+
setTimeout(() => voice.cancelSpeech(), 3000);
|
|
1691
|
+
```
|
|
1692
|
+
|
|
1693
|
+
#### Stop the API call (cancel HTTP stream)
|
|
1694
|
+
|
|
1695
|
+
```typescript
|
|
1696
|
+
// Cancel via the built-in method — aborts the HTTP/SSE connection
|
|
1697
|
+
voice.cancelStream();
|
|
1698
|
+
|
|
1699
|
+
// Or pass an AbortSignal via options for external control
|
|
1700
|
+
const controller = new AbortController();
|
|
1701
|
+
const flow = voice.executeWithBrowserVoice({ signal: controller.signal });
|
|
1702
|
+
// ...
|
|
1703
|
+
controller.abort(); // Same effect as cancelStream()
|
|
1704
|
+
```
|
|
1705
|
+
|
|
1706
|
+
#### Stop everything at once
|
|
1707
|
+
|
|
1708
|
+
```typescript
|
|
1709
|
+
// Stops recognition + aborts HTTP stream + cancels TTS
|
|
1710
|
+
voice.cancelAll();
|
|
1711
|
+
```
|
|
1712
|
+
|
|
1713
|
+
#### Check if a flow is active
|
|
1714
|
+
|
|
1715
|
+
```typescript
|
|
1716
|
+
if (voice.isStreaming) {
|
|
1717
|
+
// A voice flow is in progress
|
|
1718
|
+
voice.cancelAll();
|
|
1719
|
+
}
|
|
1720
|
+
```
|
|
1721
|
+
|
|
1722
|
+
#### React example — Stop buttons
|
|
1723
|
+
|
|
1724
|
+
```tsx
|
|
1725
|
+
function VoiceChat() {
|
|
1726
|
+
const voiceRef = useRef<BrowserVoiceClient>(null);
|
|
1727
|
+
const [messages, setMessages] = useState<string[]>([]);
|
|
1728
|
+
|
|
1729
|
+
const start = async () => {
|
|
1730
|
+
for await (const event of voiceRef.current!.executeWithBrowserVoice()) {
|
|
1731
|
+
if (event.response?.message) {
|
|
1732
|
+
setMessages(prev => [...prev, event.response!.message!]);
|
|
1733
|
+
}
|
|
1734
|
+
}
|
|
1735
|
+
};
|
|
1736
|
+
|
|
1737
|
+
return (
|
|
1738
|
+
<div>
|
|
1739
|
+
<button onClick={start}>🎤 Speak</button>
|
|
1740
|
+
{/* Stop audio only — text still streams */}
|
|
1741
|
+
<button onClick={() => voiceRef.current?.cancelSpeech()}>🔇 Mute</button>
|
|
1742
|
+
{/* Stop the API call + audio */}
|
|
1743
|
+
<button onClick={() => voiceRef.current?.cancelStream()}>⏹ Stop</button>
|
|
1744
|
+
{/* Stop everything including recognition */}
|
|
1745
|
+
<button onClick={() => voiceRef.current?.cancelAll()}>🚫 Cancel All</button>
|
|
1746
|
+
|
|
1747
|
+
{messages.map((m, i) => <p key={i}>{m}</p>)}
|
|
1748
|
+
</div>
|
|
1749
|
+
);
|
|
1750
|
+
}
|
|
1751
|
+
```
|
|
1752
|
+
|
|
1753
|
+
### 3. Timeout-Based Cancellation
|
|
1754
|
+
|
|
1755
|
+
Timeouts are configured globally via `PlayFrameworkSettings.timeout` (in ms).
|
|
1756
|
+
When set, every request is automatically aborted after the timeout expires:
|
|
1757
|
+
|
|
1758
|
+
```typescript
|
|
1759
|
+
const settings: PlayFrameworkSettings = {
|
|
1760
|
+
baseUrl: '/api/play',
|
|
1761
|
+
factoryName: 'assistant',
|
|
1762
|
+
timeout: 30000, // 30-second timeout for ALL requests
|
|
1763
|
+
// ...
|
|
1764
|
+
};
|
|
1765
|
+
```
|
|
1766
|
+
|
|
1767
|
+
When a user-provided `AbortSignal` and a timeout are both present, the client combines them
|
|
1768
|
+
so that whichever fires first cancels the request.
|
|
1769
|
+
|
|
450
1770
|
---
|
|
451
1771
|
|
|
452
1772
|
## 📊 Response Status Types
|
|
453
1773
|
|
|
454
1774
|
```typescript
|
|
455
1775
|
type AiResponseStatus =
|
|
456
|
-
| "initializing"
|
|
457
|
-
| "
|
|
458
|
-
| "
|
|
459
|
-
| "
|
|
460
|
-
| "
|
|
461
|
-
| "
|
|
462
|
-
| "
|
|
463
|
-
| "
|
|
464
|
-
| "
|
|
465
|
-
| "
|
|
1776
|
+
| "initializing" // Starting execution
|
|
1777
|
+
| "loadingCache" // Loading cached conversation context
|
|
1778
|
+
| "executingMainActors" // Running global system prompts
|
|
1779
|
+
| "planning" // Creating execution plan
|
|
1780
|
+
| "executingScene" // Running scene/actor
|
|
1781
|
+
| "functionRequest" // Calling server-side tool
|
|
1782
|
+
| "functionCompleted" // Tool call completed
|
|
1783
|
+
| "toolSkipped" // Tool was skipped
|
|
1784
|
+
| "streaming" // Streaming text chunks
|
|
1785
|
+
| "running" // General execution in progress
|
|
1786
|
+
| "summarizing" // Summarizing conversation
|
|
1787
|
+
| "directorDecision" // Director evaluating results
|
|
1788
|
+
| "generatingFinalResponse" // Generating final response
|
|
1789
|
+
| "savingCache" // Saving to cache
|
|
1790
|
+
| "savingMemory" // Saving conversation memory
|
|
1791
|
+
| "awaitingClient" // Waiting for client-side tool response
|
|
1792
|
+
| "commandClient" // Fire-and-forget command sent to client
|
|
1793
|
+
| "completed" // Success
|
|
1794
|
+
| "budgetExceeded" // Max cost exceeded
|
|
1795
|
+
| "error" // Failure
|
|
1796
|
+
| "unauthorized"; // Authorization failed
|
|
466
1797
|
```
|
|
467
1798
|
|
|
468
1799
|
---
|
|
@@ -494,50 +1825,88 @@ describe("PlayFramework Client", () => {
|
|
|
494
1825
|
|
|
495
1826
|
### `PlayFrameworkServices`
|
|
496
1827
|
|
|
497
|
-
|
|
1828
|
+
Static service locator for managing named `PlayFrameworkClient` instances.
|
|
498
1829
|
|
|
499
|
-
|
|
1830
|
+
| Method | Signature | Description |
|
|
1831
|
+
|--------|-----------|-------------|
|
|
1832
|
+
| `configure` | `(name: string, baseUrl: string, configure?: (settings: PlayFrameworkSettings) => void \| Promise<void>): Promise<PlayFrameworkSettings>` | Register and configure a named client factory |
|
|
1833
|
+
| `resolve` | `(name?: string): PlayFrameworkClient` | Get client by name (defaults to first registered) |
|
|
1834
|
+
| `getClient` | `(name: string): PlayFrameworkClient` | Get client by exact name (throws if not found) |
|
|
1835
|
+
| `getDefaultClient` | `(): PlayFrameworkClient` | Get the first registered client |
|
|
1836
|
+
| `getSettings` | `(name: string): PlayFrameworkSettings` | Get settings by name (throws if not found) |
|
|
1837
|
+
| `isConfigured` | `(name: string): boolean` | Check if a named client exists |
|
|
1838
|
+
| `remove` | `(name: string): void` | Remove a named client and its settings |
|
|
1839
|
+
| `clear` | `(): void` | Remove all clients and settings |
|
|
500
1840
|
|
|
501
1841
|
```typescript
|
|
1842
|
+
// Configure
|
|
502
1843
|
await PlayFrameworkServices.configure("chat", "http://localhost:5158/api/ai");
|
|
503
|
-
```
|
|
504
|
-
|
|
505
|
-
#### `resolve(name: string): PlayFrameworkClient`
|
|
506
1844
|
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
```typescript
|
|
1845
|
+
// Resolve
|
|
510
1846
|
const client = PlayFrameworkServices.resolve("chat");
|
|
1847
|
+
|
|
1848
|
+
// Check & remove
|
|
1849
|
+
if (PlayFrameworkServices.isConfigured("chat")) {
|
|
1850
|
+
PlayFrameworkServices.remove("chat");
|
|
1851
|
+
}
|
|
511
1852
|
```
|
|
512
1853
|
|
|
513
1854
|
---
|
|
514
1855
|
|
|
515
1856
|
### `PlayFrameworkClient`
|
|
516
1857
|
|
|
517
|
-
|
|
1858
|
+
Main client for executing AI requests via SSE streaming.
|
|
518
1859
|
|
|
519
|
-
|
|
1860
|
+
| Method | Signature | Description |
|
|
1861
|
+
|--------|-----------|-------------|
|
|
1862
|
+
| `executeStepByStep` | `(request: PlayFrameworkRequest, signal?: AbortSignal): AsyncIterableIterator<AiSceneResponse>` | Step-by-step streaming (one event per scene completion) |
|
|
1863
|
+
| `executeTokenStreaming` | `(request: PlayFrameworkRequest, signal?: AbortSignal): AsyncIterableIterator<AiSceneResponse>` | Token-level streaming (one event per text chunk) |
|
|
1864
|
+
| `getClientRegistry` | `(): ClientInteractionRegistry` | Get the client-side tool/command registry |
|
|
1865
|
+
| `getConversation` | `(conversationKey: string): Promise<StoredConversation \| null>` | Load a stored conversation by key |
|
|
1866
|
+
| `getConversations` | `(sortOrder?: ConversationSortOrder): Promise<StoredConversation[]>` | List conversations for the authenticated user |
|
|
1867
|
+
| `deleteConversation` | `(conversationKey: string): Promise<boolean>` | Delete a stored conversation |
|
|
520
1868
|
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
Execute with **token-level streaming** (each text chunk as separate event).
|
|
1869
|
+
---
|
|
524
1870
|
|
|
525
|
-
|
|
1871
|
+
### `ClientInteractionRegistry`
|
|
526
1872
|
|
|
527
|
-
|
|
1873
|
+
Registry for client-side tools and commands invoked by the AI during execution.
|
|
528
1874
|
|
|
529
|
-
|
|
1875
|
+
| Method | Signature | Description |
|
|
1876
|
+
|--------|-----------|-------------|
|
|
1877
|
+
| `register` | `<TArgs>(toolName: string, handler: ClientTool<TArgs>): void` | Register a tool (server waits for response) |
|
|
1878
|
+
| `registerCommand` | `<TArgs>(toolName: string, handler: ClientCommand<TArgs>, options?: CommandOptions): void` | Register a fire-and-forget command |
|
|
1879
|
+
| `execute` | `(request: ClientInteractionRequest): Promise<ClientInteractionResult>` | Execute a registered tool/command |
|
|
1880
|
+
| `has` | `(toolName: string): boolean` | Check if a tool/command is registered |
|
|
1881
|
+
| `isCommand` | `(toolName: string): boolean` | Check if the registration is a command |
|
|
1882
|
+
| `getCommandOptions` | `(toolName: string): CommandOptions \| undefined` | Get the command's feedback options |
|
|
1883
|
+
| `getToolNames` | `(): string[]` | List all registered tool/command names |
|
|
1884
|
+
| `unregister` | `(toolName: string): boolean` | Remove a registration |
|
|
1885
|
+
| `clear` | `(): void` | Remove all registrations |
|
|
530
1886
|
|
|
531
|
-
|
|
1887
|
+
**Types:**
|
|
532
1888
|
|
|
533
|
-
|
|
1889
|
+
```typescript
|
|
1890
|
+
type ClientTool<TArgs = any> = (args?: TArgs) => Promise<AIContent[]>;
|
|
1891
|
+
type ClientCommand<TArgs = any> = (args?: TArgs) => Promise<CommandResult>;
|
|
1892
|
+
type CommandFeedbackMode = 'never' | 'onError' | 'always';
|
|
534
1893
|
|
|
535
|
-
|
|
1894
|
+
interface CommandOptions {
|
|
1895
|
+
feedbackMode?: CommandFeedbackMode;
|
|
1896
|
+
}
|
|
1897
|
+
```
|
|
536
1898
|
|
|
537
1899
|
```typescript
|
|
1900
|
+
// Tool — server waits for the result
|
|
538
1901
|
registry.register("myTool", async (args?: { key: string }) => {
|
|
539
1902
|
return [AIContentConverter.fromText(args?.key || "default")];
|
|
540
1903
|
});
|
|
1904
|
+
|
|
1905
|
+
// Command — fire-and-forget, feedback optional
|
|
1906
|
+
registry.registerCommand("showNotification", async (args?: { text: string }) => {
|
|
1907
|
+
showToast(args?.text ?? "");
|
|
1908
|
+
return CommandResult.ok();
|
|
1909
|
+
}, { feedbackMode: 'onError' });
|
|
541
1910
|
```
|
|
542
1911
|
|
|
543
1912
|
---
|
|
@@ -575,7 +1944,208 @@ function MyComponent() {
|
|
|
575
1944
|
|
|
576
1945
|
---
|
|
577
1946
|
|
|
578
|
-
##
|
|
1947
|
+
## � Client Commands (Fire-and-Forget)
|
|
1948
|
+
|
|
1949
|
+
Commands are client-side tools that the server invokes but **does not wait for a response**. Use them for UI side effects (toasts, navigation, animations, etc.).
|
|
1950
|
+
|
|
1951
|
+
### Registering Commands
|
|
1952
|
+
|
|
1953
|
+
```typescript
|
|
1954
|
+
const registry = client.getClientRegistry();
|
|
1955
|
+
|
|
1956
|
+
// Simple command — no feedback to server
|
|
1957
|
+
registry.registerCommand("showToast", async (args?: { text: string }) => {
|
|
1958
|
+
showNotification(args?.text ?? "");
|
|
1959
|
+
return CommandResult.ok();
|
|
1960
|
+
});
|
|
1961
|
+
|
|
1962
|
+
// Command with error feedback — server receives failure info
|
|
1963
|
+
registry.registerCommand("navigateTo", async (args?: { url: string }) => {
|
|
1964
|
+
try {
|
|
1965
|
+
window.location.href = args?.url ?? "/";
|
|
1966
|
+
return CommandResult.ok();
|
|
1967
|
+
} catch (e) {
|
|
1968
|
+
return CommandResult.fail(`Navigation failed: ${e}`);
|
|
1969
|
+
}
|
|
1970
|
+
}, { feedbackMode: 'onError' });
|
|
1971
|
+
|
|
1972
|
+
// Command with always-feedback — server always gets the result
|
|
1973
|
+
registry.registerCommand("playSound", async (args?: { soundId: string }) => {
|
|
1974
|
+
await audioPlayer.play(args?.soundId ?? "notification");
|
|
1975
|
+
return CommandResult.ok("Sound played");
|
|
1976
|
+
}, { feedbackMode: 'always' });
|
|
1977
|
+
```
|
|
1978
|
+
|
|
1979
|
+
### `CommandResult` Helper
|
|
1980
|
+
|
|
1981
|
+
```typescript
|
|
1982
|
+
interface CommandResult {
|
|
1983
|
+
success: boolean;
|
|
1984
|
+
message?: string;
|
|
1985
|
+
}
|
|
1986
|
+
|
|
1987
|
+
// Factory methods
|
|
1988
|
+
CommandResult.ok(); // { success: true }
|
|
1989
|
+
CommandResult.ok("Done"); // { success: true, message: "Done" }
|
|
1990
|
+
CommandResult.fail("Reason"); // { success: false, message: "Reason" }
|
|
1991
|
+
```
|
|
1992
|
+
|
|
1993
|
+
### `CommandFeedbackMode`
|
|
1994
|
+
|
|
1995
|
+
| Mode | Behavior |
|
|
1996
|
+
|------|----------|
|
|
1997
|
+
| `'never'` | Server ignores the command's result (default) |
|
|
1998
|
+
| `'onError'` | Server receives feedback only when `success: false` |
|
|
1999
|
+
| `'always'` | Server always receives the command's result |
|
|
2000
|
+
|
|
2001
|
+
---
|
|
2002
|
+
|
|
2003
|
+
## 📋 `ClientInteractionRequest` Model
|
|
2004
|
+
|
|
2005
|
+
When the server invokes a client-side tool or command, it sends this object:
|
|
2006
|
+
|
|
2007
|
+
```typescript
|
|
2008
|
+
interface ClientInteractionRequest {
|
|
2009
|
+
interactionId: string; // Unique ID for this invocation
|
|
2010
|
+
toolName: string; // Registered tool/command name
|
|
2011
|
+
description?: string; // Human-readable description
|
|
2012
|
+
arguments?: Record<string, any>; // Arguments from AI
|
|
2013
|
+
argumentsSchema?: string; // JSON Schema string
|
|
2014
|
+
timeoutSeconds: number; // Max time to wait (tools only)
|
|
2015
|
+
isCommand?: boolean; // true = fire-and-forget command
|
|
2016
|
+
feedbackMode?: 'never' | 'onError' | 'always'; // Command feedback mode
|
|
2017
|
+
}
|
|
2018
|
+
```
|
|
2019
|
+
|
|
2020
|
+
---
|
|
2021
|
+
|
|
2022
|
+
## 📋 `ClientInteractionResult` Model
|
|
2023
|
+
|
|
2024
|
+
The response your tool handler returns to the server:
|
|
2025
|
+
|
|
2026
|
+
```typescript
|
|
2027
|
+
interface AIContent {
|
|
2028
|
+
type: "text" | "data";
|
|
2029
|
+
text?: string; // For type "text"
|
|
2030
|
+
data?: string; // Base64-encoded (for type "data")
|
|
2031
|
+
mediaType?: string; // e.g., "image/jpeg", "audio/webm"
|
|
2032
|
+
}
|
|
2033
|
+
|
|
2034
|
+
interface ClientInteractionResult {
|
|
2035
|
+
interactionId: string; // Must match the request
|
|
2036
|
+
contents: AIContent[]; // Tool output
|
|
2037
|
+
error?: string; // Error message (if failed)
|
|
2038
|
+
executedAt: string; // ISO 8601 timestamp
|
|
2039
|
+
}
|
|
2040
|
+
```
|
|
2041
|
+
|
|
2042
|
+
---
|
|
2043
|
+
|
|
2044
|
+
## 📋 `ExecutionState` and `ExecutionPhase`
|
|
2045
|
+
|
|
2046
|
+
The `ExecutionState` object tracks the AI orchestration progress during execution:
|
|
2047
|
+
|
|
2048
|
+
```typescript
|
|
2049
|
+
type ExecutionPhase =
|
|
2050
|
+
| "notStarted"
|
|
2051
|
+
| "initialized"
|
|
2052
|
+
| "sceneSelected"
|
|
2053
|
+
| "executingScene"
|
|
2054
|
+
| "awaitingClient"
|
|
2055
|
+
| "sceneCompleted"
|
|
2056
|
+
| "chaining"
|
|
2057
|
+
| "generatingFinalResponse"
|
|
2058
|
+
| "completed"
|
|
2059
|
+
| "completedNoResponse"
|
|
2060
|
+
| "budgetExceeded"
|
|
2061
|
+
| "sceneNotFound"
|
|
2062
|
+
| "tooManyToolRequests"
|
|
2063
|
+
| "break"
|
|
2064
|
+
| "unauthorized";
|
|
2065
|
+
|
|
2066
|
+
interface ExecutionState {
|
|
2067
|
+
phase: ExecutionPhase; // Current execution phase
|
|
2068
|
+
executedSceneOrder: string[]; // Scene names in execution order
|
|
2069
|
+
executedScenes: Record<string, any[]>; // Scene name → results
|
|
2070
|
+
executedTools: string[]; // Tool names invoked
|
|
2071
|
+
accumulatedCost: number; // Total $ cost so far
|
|
2072
|
+
currentSceneName?: string | null; // Currently running scene
|
|
2073
|
+
}
|
|
2074
|
+
```
|
|
2075
|
+
|
|
2076
|
+
---
|
|
2077
|
+
|
|
2078
|
+
## 📋 `AiSceneResponse` Full Model
|
|
2079
|
+
|
|
2080
|
+
Each SSE event yields an `AiSceneResponse`:
|
|
2081
|
+
|
|
2082
|
+
```typescript
|
|
2083
|
+
interface AiSceneResponse {
|
|
2084
|
+
status: AiResponseStatus;
|
|
2085
|
+
sceneName?: string;
|
|
2086
|
+
functionName?: string;
|
|
2087
|
+
functionArguments?: string;
|
|
2088
|
+
message?: string; // Final response text (step-by-step)
|
|
2089
|
+
streamingChunk?: string; // Partial text (token streaming)
|
|
2090
|
+
isStreamingComplete?: boolean;
|
|
2091
|
+
errorMessage?: string;
|
|
2092
|
+
inputTokens?: number;
|
|
2093
|
+
cachedInputTokens?: number;
|
|
2094
|
+
outputTokens?: number;
|
|
2095
|
+
totalTokens?: number;
|
|
2096
|
+
cost?: number; // Cost for this step
|
|
2097
|
+
totalCost?: number; // Accumulated total cost
|
|
2098
|
+
conversationKey?: string;
|
|
2099
|
+
continuationToken?: string; // Token for resuming after client tool
|
|
2100
|
+
clientInteractionRequest?: ClientInteractionRequest;
|
|
2101
|
+
timestamp?: string;
|
|
2102
|
+
metadata?: Record<string, any>;
|
|
2103
|
+
contents?: Array<{
|
|
2104
|
+
type: string;
|
|
2105
|
+
text?: string;
|
|
2106
|
+
data?: string; // Base64 encoded
|
|
2107
|
+
mediaType?: string;
|
|
2108
|
+
}>;
|
|
2109
|
+
}
|
|
2110
|
+
```
|
|
2111
|
+
|
|
2112
|
+
---
|
|
2113
|
+
|
|
2114
|
+
## 📋 `StoredMessage` Full Model
|
|
2115
|
+
|
|
2116
|
+
Each message in a `StoredConversation.messages` array:
|
|
2117
|
+
|
|
2118
|
+
```typescript
|
|
2119
|
+
interface StoredMessage {
|
|
2120
|
+
businessType: number; // Internal type discriminator
|
|
2121
|
+
label?: string | null; // Optional label (e.g., scene name)
|
|
2122
|
+
role: string; // "user" | "assistant" | "system" | "tool"
|
|
2123
|
+
text?: string | null; // Plain text content
|
|
2124
|
+
contents?: any[] | null; // Multi-modal content items
|
|
2125
|
+
additionalProperties?: Record<string, any> | null; // Extra metadata
|
|
2126
|
+
}
|
|
2127
|
+
```
|
|
2128
|
+
|
|
2129
|
+
---
|
|
2130
|
+
|
|
2131
|
+
## 📋 `ContentItem` Full Model
|
|
2132
|
+
|
|
2133
|
+
Used in `PlayFrameworkRequest.contents` for multi-modal input:
|
|
2134
|
+
|
|
2135
|
+
```typescript
|
|
2136
|
+
interface ContentItem {
|
|
2137
|
+
type: "text" | "image" | "audio" | "video" | "file" | "uri";
|
|
2138
|
+
text?: string; // For type "text"
|
|
2139
|
+
data?: string; // Base64-encoded binary data
|
|
2140
|
+
uri?: string; // For type "uri"
|
|
2141
|
+
mediaType?: string; // MIME type (e.g., "image/png", "audio/webm")
|
|
2142
|
+
name?: string; // Optional filename
|
|
2143
|
+
}
|
|
2144
|
+
```
|
|
2145
|
+
|
|
2146
|
+
---
|
|
2147
|
+
|
|
2148
|
+
## �📁 Where to Place This README
|
|
579
2149
|
|
|
580
2150
|
This README should be placed in:
|
|
581
2151
|
```
|