rystem.playframework.client 0.1.3 → 0.1.4
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 +375 -2108
- package/lib/engine/PlayFrameworkClient.js +7 -7
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,2311 +1,578 @@
|
|
|
1
|
-
#
|
|
1
|
+
# rystem.playframework.client
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
[](https://www.typescriptlang.org/)
|
|
5
|
-
[](LICENSE)
|
|
3
|
+
`rystem.playframework.client` is the published TypeScript client for the PlayFramework HTTP API.
|
|
6
4
|
|
|
7
|
-
|
|
5
|
+
It wraps PlayFramework SSE endpoints, auto-runs client-side tools, supports conversation CRUD and the server voice endpoint, and also ships browser-native helpers such as `AIContentConverter`, `ContentUrlConverter`, `VoiceRecorder`, and `BrowserVoiceClient`.
|
|
8
6
|
|
|
9
|
-
|
|
10
|
-
- ✅ **Step-by-step streaming** (SSE) - Each scene/actor as separate event
|
|
11
|
-
- ✅ **Token-level streaming** (SSE) - Real-time text chunks
|
|
12
|
-
- ✅ **Client-side tools** - Camera, geolocation, file picker, microphone
|
|
13
|
-
- ✅ **Multi-modal content** - Images, audio, video, PDFs, URIs
|
|
14
|
-
- ✅ **React hooks** - `usePlayFramework()` for easy integration
|
|
15
|
-
- ✅ **Execution modes** - Direct, Planning, DynamicChaining, Scene
|
|
16
|
-
- ✅ **Configurable** - Headers, retry, error handling, timeouts
|
|
17
|
-
- ✅ **Type-safe** - Full TypeScript definitions
|
|
18
|
-
- ✅ **Browser Voice** - Client-side STT/TTS via Web Speech API (zero-latency, no server needed)
|
|
19
|
-
|
|
20
|
-
---
|
|
21
|
-
|
|
22
|
-
## 📦 Installation
|
|
7
|
+
## Installation
|
|
23
8
|
|
|
24
9
|
```bash
|
|
25
|
-
npm install
|
|
10
|
+
npm install rystem.playframework.client
|
|
26
11
|
```
|
|
27
12
|
|
|
28
|
-
|
|
29
|
-
```bash
|
|
30
|
-
yarn add @rystem/playframework-client
|
|
31
|
-
```
|
|
13
|
+
The current package name in `package.json` is `rystem.playframework.client`.
|
|
32
14
|
|
|
33
|
-
|
|
15
|
+
## What this package expects from the server
|
|
34
16
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
### 1. Configure Client
|
|
38
|
-
|
|
39
|
-
```typescript
|
|
40
|
-
import { PlayFrameworkServices } from "@rystem/playframework-client";
|
|
17
|
+
This client assumes a backend that maps PlayFramework under a base path such as:
|
|
41
18
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
settings.
|
|
46
|
-
settings.
|
|
19
|
+
```csharp
|
|
20
|
+
app.MapPlayFramework("default", settings =>
|
|
21
|
+
{
|
|
22
|
+
settings.BasePath = "/api/ai";
|
|
23
|
+
settings.EnableConversationEndpoints = true;
|
|
24
|
+
settings.EnableVoiceEndpoints = true;
|
|
47
25
|
});
|
|
48
26
|
```
|
|
49
27
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
```typescript
|
|
53
|
-
const client = PlayFrameworkServices.resolve("default");
|
|
54
|
-
|
|
55
|
-
// Step-by-step streaming
|
|
56
|
-
for await (const step of client.executeStepByStep({
|
|
57
|
-
message: "Tell me a joke"
|
|
58
|
-
})) {
|
|
59
|
-
console.log(`[${step.status}] ${step.message}`);
|
|
60
|
-
}
|
|
61
|
-
// Output:
|
|
62
|
-
// [planning] Analyzing request...
|
|
63
|
-
// [executingScene] Generating joke...
|
|
64
|
-
// [completed] Why did the chicken cross the road? To get to the other side!
|
|
65
|
-
|
|
66
|
-
// Token-level streaming (real-time chunks)
|
|
67
|
-
for await (const chunk of client.executeTokenStreaming({
|
|
68
|
-
message: "Write a short story"
|
|
69
|
-
})) {
|
|
70
|
-
process.stdout.write(chunk.streamingChunk || "");
|
|
71
|
-
}
|
|
72
|
-
// Output: "Once" → " upon" → " a" → " time" → "..."
|
|
73
|
-
```
|
|
74
|
-
|
|
75
|
-
### 3. Use with React
|
|
76
|
-
|
|
77
|
-
```tsx
|
|
78
|
-
import { usePlayFramework } from "@rystem/playframework-client";
|
|
79
|
-
import { useState } from "react";
|
|
80
|
-
|
|
81
|
-
function ChatComponent() {
|
|
82
|
-
const client = usePlayFramework("default");
|
|
83
|
-
const [messages, setMessages] = useState<string[]>([]);
|
|
84
|
-
const [loading, setLoading] = useState(false);
|
|
85
|
-
|
|
86
|
-
const handleSend = async (input: string) => {
|
|
87
|
-
setLoading(true);
|
|
88
|
-
const newMessages: string[] = [];
|
|
89
|
-
|
|
90
|
-
try {
|
|
91
|
-
for await (const step of client.executeStepByStep({
|
|
92
|
-
message: input
|
|
93
|
-
})) {
|
|
94
|
-
if (step.streamingChunk) {
|
|
95
|
-
// Real-time token streaming
|
|
96
|
-
newMessages.push(step.streamingChunk);
|
|
97
|
-
} else if (step.message) {
|
|
98
|
-
// Step-by-step message
|
|
99
|
-
newMessages.push(`[${step.status}] ${step.message}`);
|
|
100
|
-
}
|
|
101
|
-
setMessages([...newMessages]);
|
|
102
|
-
}
|
|
103
|
-
} finally {
|
|
104
|
-
setLoading(false);
|
|
105
|
-
}
|
|
106
|
-
};
|
|
28
|
+
When you configure the TypeScript client with:
|
|
107
29
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
<input onKeyDown={e => e.key === 'Enter' && handleSend(e.currentTarget.value)} />
|
|
111
|
-
<div>
|
|
112
|
-
{messages.map((msg, i) => <div key={i}>{msg}</div>)}
|
|
113
|
-
</div>
|
|
114
|
-
</div>
|
|
115
|
-
);
|
|
116
|
-
}
|
|
30
|
+
```text
|
|
31
|
+
http://localhost:5158/api/ai
|
|
117
32
|
```
|
|
118
33
|
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
## 🎯 Core Features
|
|
34
|
+
the library appends `/{factoryName}` itself.
|
|
122
35
|
|
|
123
|
-
|
|
36
|
+
So for the `default` factory it calls:
|
|
124
37
|
|
|
125
|
-
|
|
126
|
-
-
|
|
127
|
-
-
|
|
128
|
-
-
|
|
129
|
-
|
|
130
|
-
**Token Streaming** (`executeTokenStreaming`):
|
|
131
|
-
- Returns **individual text chunks** as they're generated
|
|
132
|
-
- Best for: Real-time chat UIs, typewriter effects
|
|
133
|
-
- Example: "Hello" → " world" → "!" → "..."
|
|
134
|
-
|
|
135
|
-
```typescript
|
|
136
|
-
// Step-by-step - structured workflow
|
|
137
|
-
for await (const step of client.executeStepByStep({ message: "..." })) {
|
|
138
|
-
console.log(step.status); // "planning", "executingScene", "completed"
|
|
139
|
-
console.log(step.sceneName); // "ChatScene"
|
|
140
|
-
console.log(step.message); // Full response
|
|
141
|
-
}
|
|
38
|
+
- `POST http://localhost:5158/api/ai/default`
|
|
39
|
+
- `POST http://localhost:5158/api/ai/default/streaming`
|
|
40
|
+
- `GET http://localhost:5158/api/ai/default/conversations`
|
|
41
|
+
- `POST http://localhost:5158/api/ai/default/voice`
|
|
142
42
|
|
|
143
|
-
|
|
144
|
-
for await (const chunk of client.executeTokenStreaming({ message: "..." })) {
|
|
145
|
-
console.log(chunk.streamingChunk); // "Hello", " world", "!"
|
|
146
|
-
}
|
|
147
|
-
```
|
|
43
|
+
## Architecture
|
|
148
44
|
|
|
149
|
-
|
|
45
|
+
The package is built around:
|
|
150
46
|
|
|
151
|
-
|
|
47
|
+
- `PlayFrameworkServices`
|
|
48
|
+
- `PlayFrameworkClient`
|
|
49
|
+
- `ClientInteractionRegistry`
|
|
50
|
+
- `AIContentConverter`
|
|
51
|
+
- `ContentUrlConverter`
|
|
52
|
+
- `VoiceRecorder`
|
|
53
|
+
- `BrowserVoiceClient`
|
|
54
|
+
- `usePlayFramework`
|
|
152
55
|
|
|
153
|
-
|
|
56
|
+
The usual lifecycle is:
|
|
154
57
|
|
|
155
|
-
|
|
58
|
+
1. configure one or more client factories with `PlayFrameworkServices.configure(...)`
|
|
59
|
+
2. resolve a `PlayFrameworkClient`
|
|
60
|
+
3. call `executeStepByStep(...)` or `executeTokenStreaming(...)`
|
|
61
|
+
4. optionally register browser-side tools through `getClientRegistry()`
|
|
62
|
+
5. optionally use conversation or voice helpers
|
|
156
63
|
|
|
157
|
-
|
|
158
|
-
services.AddPlayFramework(builder =>
|
|
159
|
-
{
|
|
160
|
-
builder.AddScene("vision", "Analyze user photos", scene =>
|
|
161
|
-
{
|
|
162
|
-
scene.OnClient(client =>
|
|
163
|
-
{
|
|
164
|
-
client.AddTool("capturePhoto", "Take photo from camera");
|
|
165
|
-
client.AddTool("getCurrentLocation", "Get GPS coordinates");
|
|
166
|
-
client.AddTool("selectFiles", "Open file picker");
|
|
167
|
-
});
|
|
168
|
-
});
|
|
169
|
-
});
|
|
170
|
-
```
|
|
64
|
+
## Example: bootstrap one client
|
|
171
65
|
|
|
172
|
-
|
|
66
|
+
`PlayFrameworkServices.configure(...)` is async and should usually run during application startup.
|
|
173
67
|
|
|
174
68
|
```typescript
|
|
175
|
-
import { PlayFrameworkServices
|
|
69
|
+
import { PlayFrameworkServices } from "rystem.playframework.client";
|
|
176
70
|
|
|
177
|
-
|
|
178
|
-
|
|
71
|
+
await PlayFrameworkServices.configure("default", "http://localhost:5158/api/ai", async settings => {
|
|
72
|
+
settings.timeout = 120_000;
|
|
73
|
+
settings.maxReconnectAttempts = 3;
|
|
74
|
+
settings.reconnectBaseDelay = 1000;
|
|
179
75
|
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
return [content];
|
|
187
|
-
});
|
|
188
|
-
|
|
189
|
-
// Register geolocation tool
|
|
190
|
-
registry.register("getCurrentLocation", async () => {
|
|
191
|
-
const content = await AIContentConverter.fromGeolocation({ timeout: 10_000 });
|
|
192
|
-
return [content];
|
|
193
|
-
});
|
|
76
|
+
settings.addHeadersEnricher(async (_url, _method, headers) => {
|
|
77
|
+
return {
|
|
78
|
+
...Object.fromEntries(new Headers(headers).entries()),
|
|
79
|
+
Authorization: `Bearer ${localStorage.getItem("token") ?? ""}`
|
|
80
|
+
};
|
|
81
|
+
});
|
|
194
82
|
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
input.onchange = async () => {
|
|
202
|
-
const contents = await AIContentConverter.fromMultipleFiles(input.files!);
|
|
203
|
-
resolve(contents);
|
|
204
|
-
};
|
|
205
|
-
input.click();
|
|
206
|
-
});
|
|
83
|
+
settings.addErrorHandler(async (_url, _method, _headers, _body, error) => {
|
|
84
|
+
if (error instanceof Error && error.message.includes("401")) {
|
|
85
|
+
localStorage.removeItem("token");
|
|
86
|
+
}
|
|
87
|
+
return false;
|
|
88
|
+
});
|
|
207
89
|
});
|
|
208
|
-
```
|
|
209
|
-
|
|
210
|
-
**Client automatically resumes execution after tool completion!**
|
|
211
90
|
|
|
212
|
-
|
|
213
|
-
for await (const step of client.executeStepByStep({ message: "Take a photo and describe it" })) {
|
|
214
|
-
console.log(step.status);
|
|
215
|
-
// 1. "executingScene" - LLM requests camera
|
|
216
|
-
// 2. "awaitingClient" - Client executes tool
|
|
217
|
-
// 3. "executingScene" - LLM analyzes photo
|
|
218
|
-
// 4. "completed" - Final response
|
|
219
|
-
}
|
|
91
|
+
const client = PlayFrameworkServices.resolve("default");
|
|
220
92
|
```
|
|
221
93
|
|
|
222
|
-
|
|
94
|
+
If you only configure one factory, `resolve()` with no name returns the first configured client:
|
|
223
95
|
|
|
224
96
|
```typescript
|
|
225
|
-
|
|
226
|
-
const photo = await AIContentConverter.fromCamera();
|
|
227
|
-
|
|
228
|
-
// Geolocation (returns JSON with lat/lng)
|
|
229
|
-
const location = await AIContentConverter.fromGeolocation();
|
|
230
|
-
|
|
231
|
-
// File upload (returns Base64 data)
|
|
232
|
-
const file = await AIContentConverter.fromFile(fileInput.files[0]);
|
|
233
|
-
|
|
234
|
-
// Multiple files
|
|
235
|
-
const files = await AIContentConverter.fromMultipleFiles(fileInput.files);
|
|
236
|
-
|
|
237
|
-
// Microphone (returns Base64 audio)
|
|
238
|
-
const audio = await AIContentConverter.fromMicrophone(5000); // 5 seconds
|
|
239
|
-
|
|
240
|
-
// Plain text
|
|
241
|
-
const text = AIContentConverter.fromText("Hello world");
|
|
97
|
+
const defaultClient = PlayFrameworkServices.resolve();
|
|
242
98
|
```
|
|
243
99
|
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
## 🎛️ Execution Modes
|
|
100
|
+
## Example: configure multiple factories
|
|
247
101
|
|
|
248
|
-
|
|
102
|
+
The sample workspace in `src/AI/Rystem.PlayFramework.Client/src/App.tsx` configures both `default` and `foundry` against the same base path.
|
|
249
103
|
|
|
250
104
|
```typescript
|
|
251
|
-
|
|
105
|
+
await Promise.all([
|
|
106
|
+
PlayFrameworkServices.configure("default", "http://localhost:5158/api/ai", settings => {
|
|
107
|
+
settings.timeout = 120_000;
|
|
108
|
+
}),
|
|
109
|
+
PlayFrameworkServices.configure("foundry", "http://localhost:5158/api/ai", settings => {
|
|
110
|
+
settings.timeout = 120_000;
|
|
111
|
+
})
|
|
112
|
+
]);
|
|
252
113
|
|
|
253
|
-
const
|
|
254
|
-
|
|
255
|
-
settings: {
|
|
256
|
-
executionMode: "Planning", // Direct | Planning | DynamicChaining | Scene
|
|
257
|
-
maxRecursionDepth: 5,
|
|
258
|
-
enableSummarization: true,
|
|
259
|
-
enableDirector: false
|
|
260
|
-
}
|
|
261
|
-
};
|
|
114
|
+
const cloudClient = PlayFrameworkServices.resolve("default");
|
|
115
|
+
const localClient = PlayFrameworkServices.resolve("foundry");
|
|
262
116
|
```
|
|
263
117
|
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
| Mode | Description | Use Case |
|
|
267
|
-
|------|-------------|----------|
|
|
268
|
-
| `Direct` | Single scene, no planning | Simple queries, fast responses |
|
|
269
|
-
| `Planning` | Upfront multi-step plan | Known workflows (booking, checkout) |
|
|
270
|
-
| `DynamicChaining` | LLM decides next step live | Exploratory tasks (research, debugging) |
|
|
271
|
-
| `Scene` | Execute specific scene by name | Resuming after client interaction |
|
|
118
|
+
This is useful when the backend exposes multiple PlayFramework factories with different scenes or model providers.
|
|
272
119
|
|
|
273
|
-
|
|
120
|
+
## Example: step-by-step streaming
|
|
274
121
|
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
Send **images, audio, video, PDFs, URIs** with your request:
|
|
122
|
+
`executeStepByStep(...)` yields full `AiSceneResponse` events as the backend progresses through planning, scene execution, tool calls, and final output.
|
|
278
123
|
|
|
279
124
|
```typescript
|
|
280
|
-
import { PlayFrameworkRequest
|
|
125
|
+
import type { PlayFrameworkRequest } from "rystem.playframework.client";
|
|
281
126
|
|
|
282
127
|
const request: PlayFrameworkRequest = {
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
data: "JVBERi0xLjQKJeLjz9M...",
|
|
293
|
-
mediaType: "application/pdf"
|
|
294
|
-
},
|
|
295
|
-
{
|
|
296
|
-
type: "uri",
|
|
297
|
-
uri: "https://example.com/document.pdf",
|
|
298
|
-
mediaType: "application/pdf"
|
|
299
|
-
},
|
|
300
|
-
{
|
|
301
|
-
type: "text",
|
|
302
|
-
text: "Additional context"
|
|
303
|
-
}
|
|
304
|
-
]
|
|
128
|
+
message: "Calculate 12 * 7",
|
|
129
|
+
metadata: {
|
|
130
|
+
userId: "user-42",
|
|
131
|
+
tenantId: "tenant-a"
|
|
132
|
+
},
|
|
133
|
+
settings: {
|
|
134
|
+
executionMode: "Scene",
|
|
135
|
+
sceneName: "Calculator"
|
|
136
|
+
}
|
|
305
137
|
};
|
|
306
138
|
|
|
307
139
|
for await (const step of client.executeStepByStep(request)) {
|
|
308
|
-
|
|
309
|
-
}
|
|
310
|
-
```
|
|
311
|
-
|
|
312
|
-
---
|
|
313
|
-
|
|
314
|
-
## ⚙️ Configuration & Settings
|
|
315
|
-
|
|
316
|
-
### Global Configuration
|
|
317
|
-
|
|
318
|
-
```typescript
|
|
319
|
-
import { PlayFrameworkServices } from "@rystem/playframework-client";
|
|
320
|
-
|
|
321
|
-
await PlayFrameworkServices.configure("premium", "https://api.example.com/api/ai", settings => {
|
|
322
|
-
// Timeout (ms)
|
|
323
|
-
settings.timeout = 120_000; // 2 minutes
|
|
324
|
-
|
|
325
|
-
// Reconnection on SSE failures
|
|
326
|
-
settings.maxReconnectAttempts = 3;
|
|
327
|
-
settings.reconnectBaseDelay = 1000; // 1 second
|
|
328
|
-
|
|
329
|
-
// Default headers
|
|
330
|
-
settings.defaultHeaders = {
|
|
331
|
-
"Content-Type": "application/json",
|
|
332
|
-
"X-App-Version": "1.0.0"
|
|
333
|
-
};
|
|
334
|
-
|
|
335
|
-
// Dynamic headers (auth token)
|
|
336
|
-
settings.addHeadersEnricher(async (url, method, headers, body) => {
|
|
337
|
-
const token = await getAuthToken();
|
|
338
|
-
return {
|
|
339
|
-
...headers,
|
|
340
|
-
"Authorization": `Bearer ${token}`
|
|
341
|
-
};
|
|
342
|
-
});
|
|
343
|
-
|
|
344
|
-
// Error handling with retry
|
|
345
|
-
settings.addErrorHandler(async (url, method, headers, body, error) => {
|
|
346
|
-
if (error.message.includes("401")) {
|
|
347
|
-
await refreshAuthToken();
|
|
348
|
-
return true; // Retry
|
|
349
|
-
}
|
|
350
|
-
return false; // Don't retry
|
|
351
|
-
});
|
|
352
|
-
});
|
|
353
|
-
```
|
|
354
|
-
|
|
355
|
-
### Per-Request Settings
|
|
356
|
-
|
|
357
|
-
```typescript
|
|
358
|
-
const request: PlayFrameworkRequest = {
|
|
359
|
-
message: "Your query",
|
|
360
|
-
settings: {
|
|
361
|
-
// Execution mode
|
|
362
|
-
executionMode: "Planning", // Direct | Planning | DynamicChaining | Scene
|
|
363
|
-
|
|
364
|
-
// Planning settings
|
|
365
|
-
maxRecursionDepth: 5, // Max planning depth
|
|
366
|
-
maxDynamicScenes: 10, // Max scenes in DynamicChaining
|
|
367
|
-
|
|
368
|
-
// Features
|
|
369
|
-
enableSummarization: true, // Auto-summarize long contexts
|
|
370
|
-
enableDirector: false, // Multi-scene orchestration
|
|
371
|
-
enableStreaming: true, // Token-level streaming
|
|
372
|
-
|
|
373
|
-
// Model overrides
|
|
374
|
-
modelId: "gpt-4o", // Override default model
|
|
375
|
-
temperature: 0.7, // 0.0 - 2.0
|
|
376
|
-
maxTokens: 4096, // Max response tokens
|
|
377
|
-
|
|
378
|
-
// Caching
|
|
379
|
-
cacheBehavior: "Default", // Default | Avoidable | Forever
|
|
380
|
-
conversationKey: "user-123-session-1", // Unique conversation ID
|
|
381
|
-
|
|
382
|
-
// Budget
|
|
383
|
-
maxBudget: 0.50, // Max cost in USD (null = unlimited)
|
|
384
|
-
|
|
385
|
-
// Scene selection (Scene mode only)
|
|
386
|
-
sceneName: "SpecificScene" // Execute specific scene
|
|
387
|
-
},
|
|
388
|
-
metadata: {
|
|
389
|
-
userId: "user-123",
|
|
390
|
-
sessionId: "session-abc",
|
|
391
|
-
customKey: "customValue"
|
|
392
|
-
}
|
|
393
|
-
};
|
|
394
|
-
```
|
|
395
|
-
|
|
396
|
-
---
|
|
140
|
+
console.log(step.status, step.sceneName, step.message);
|
|
397
141
|
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
```typescript
|
|
403
|
-
const conversationKey = crypto.randomUUID();
|
|
404
|
-
|
|
405
|
-
// First request
|
|
406
|
-
for await (const step of client.executeStepByStep({
|
|
407
|
-
message: "What's the weather in Paris?",
|
|
408
|
-
settings: { conversationKey }
|
|
409
|
-
})) {
|
|
410
|
-
console.log(step.message);
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
// Follow-up request (uses cached context)
|
|
414
|
-
for await (const step of client.executeStepByStep({
|
|
415
|
-
message: "And in London?",
|
|
416
|
-
settings: { conversationKey }
|
|
417
|
-
})) {
|
|
418
|
-
console.log(step.message); // LLM remembers Paris context
|
|
142
|
+
if (step.totalTokens != null || step.totalCost != null) {
|
|
143
|
+
console.log("usage", step.totalTokens, step.totalCost);
|
|
144
|
+
}
|
|
419
145
|
}
|
|
420
146
|
```
|
|
421
147
|
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
## 💾 Conversation Management (Repository Pattern)
|
|
148
|
+
This calls:
|
|
425
149
|
|
|
426
|
-
|
|
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
|
-
// ]
|
|
150
|
+
```text
|
|
151
|
+
POST {baseUrl}/{factoryName}
|
|
454
152
|
```
|
|
455
153
|
|
|
456
|
-
|
|
154
|
+
Common yielded statuses include:
|
|
457
155
|
|
|
458
|
-
|
|
459
|
-
|
|
156
|
+
- `initializing`
|
|
157
|
+
- `planning`
|
|
158
|
+
- `executingScene`
|
|
159
|
+
- `functionRequest`
|
|
160
|
+
- `functionCompleted`
|
|
161
|
+
- `running`
|
|
162
|
+
- `awaitingClient`
|
|
163
|
+
- `commandClient`
|
|
460
164
|
|
|
461
|
-
|
|
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
|
-
```
|
|
165
|
+
Completion and error markers are handled internally by the client runtime rather than surfaced as normal yielded events.
|
|
468
166
|
|
|
469
|
-
|
|
167
|
+
## Example: token streaming
|
|
470
168
|
|
|
471
|
-
|
|
169
|
+
`executeTokenStreaming(...)` still yields `AiSceneResponse` objects, but the text arrives through `streamingChunk`.
|
|
472
170
|
|
|
473
171
|
```typescript
|
|
474
|
-
|
|
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
|
-
```
|
|
172
|
+
let finalText = "";
|
|
491
173
|
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
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
|
-
);
|
|
174
|
+
for await (const chunk of client.executeTokenStreaming({
|
|
175
|
+
message: "Write a short summary of PlayFramework",
|
|
176
|
+
settings: {
|
|
177
|
+
executionMode: "Direct"
|
|
178
|
+
}
|
|
179
|
+
})) {
|
|
180
|
+
if (chunk.streamingChunk) {
|
|
181
|
+
finalText += chunk.streamingChunk;
|
|
182
|
+
console.log(chunk.streamingChunk);
|
|
183
|
+
}
|
|
946
184
|
}
|
|
947
185
|
|
|
948
|
-
|
|
186
|
+
console.log("final", finalText);
|
|
949
187
|
```
|
|
950
188
|
|
|
951
|
-
|
|
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
|
|
189
|
+
This calls:
|
|
960
190
|
|
|
191
|
+
```text
|
|
192
|
+
POST {baseUrl}/{factoryName}/streaming
|
|
961
193
|
```
|
|
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
194
|
|
|
1004
|
-
##
|
|
195
|
+
## Request model
|
|
1005
196
|
|
|
1006
|
-
|
|
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.
|
|
197
|
+
The main request type is `PlayFrameworkRequest`.
|
|
1011
198
|
|
|
1012
199
|
```typescript
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
200
|
+
const request = {
|
|
201
|
+
message: "Book a flight to Paris",
|
|
202
|
+
metadata: {
|
|
203
|
+
userId: "123",
|
|
204
|
+
tenantId: "tenant-a"
|
|
205
|
+
},
|
|
206
|
+
settings: {
|
|
207
|
+
executionMode: "Planning",
|
|
208
|
+
maxRecursionDepth: 5,
|
|
209
|
+
sceneName: "Travel"
|
|
210
|
+
},
|
|
211
|
+
conversationKey: "conversation-123"
|
|
1019
212
|
};
|
|
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
213
|
```
|
|
1053
214
|
|
|
1054
|
-
|
|
1055
|
-
Revokes all cached URLs at once.
|
|
215
|
+
The `settings` object mirrors the server-side `SceneRequestSettings`, including:
|
|
1056
216
|
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
217
|
+
- `executionMode`
|
|
218
|
+
- `sceneName`
|
|
219
|
+
- `conversationKey`
|
|
220
|
+
- `clientInteractionResults`
|
|
221
|
+
- `enableStreaming`
|
|
222
|
+
- `enableSummarization`
|
|
223
|
+
- `enableDirector`
|
|
224
|
+
- `maxRecursionDepth`
|
|
1060
225
|
|
|
1061
|
-
|
|
1062
|
-
Triggers browser download.
|
|
226
|
+
The request can also include `contents` for multi-modal inputs.
|
|
1063
227
|
|
|
1064
|
-
|
|
1065
|
-
ContentUrlConverter.downloadAsFile(content, 'image.jpg');
|
|
1066
|
-
```
|
|
228
|
+
## Example: send files and multi-modal contents
|
|
1067
229
|
|
|
1068
|
-
|
|
1069
|
-
Maps MIME type to file extension.
|
|
230
|
+
The request model accepts `ContentItem[]`, while `AIContentConverter` helps you build the base64 payloads in the browser.
|
|
1070
231
|
|
|
1071
232
|
```typescript
|
|
1072
|
-
|
|
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
|
-
}
|
|
233
|
+
import {
|
|
234
|
+
AIContentConverter,
|
|
235
|
+
type ContentItem,
|
|
236
|
+
type PlayFrameworkRequest
|
|
237
|
+
} from "rystem.playframework.client";
|
|
1142
238
|
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
return (
|
|
1146
|
-
<audio controls style={{ width: '100%' }}>
|
|
1147
|
-
<source src={url} type={mediaType} />
|
|
1148
|
-
</audio>
|
|
1149
|
-
);
|
|
1150
|
-
}
|
|
239
|
+
async function buildRequest(file: File): Promise<PlayFrameworkRequest> {
|
|
240
|
+
const converted = await AIContentConverter.fromFile(file);
|
|
1151
241
|
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
);
|
|
242
|
+
const contents: ContentItem[] = [
|
|
243
|
+
{
|
|
244
|
+
type: "file",
|
|
245
|
+
data: converted.data,
|
|
246
|
+
mediaType: converted.mediaType,
|
|
247
|
+
name: file.name
|
|
1159
248
|
}
|
|
249
|
+
];
|
|
1160
250
|
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
title="PDF Document"
|
|
1167
|
-
style={{ width: '100%', height: '600px', border: '1px solid #ddd' }}
|
|
1168
|
-
/>
|
|
1169
|
-
);
|
|
251
|
+
return {
|
|
252
|
+
message: "Summarize the attached document and extract the risks.",
|
|
253
|
+
contents,
|
|
254
|
+
settings: {
|
|
255
|
+
executionMode: "Planning"
|
|
1170
256
|
}
|
|
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
|
-
);
|
|
257
|
+
};
|
|
1181
258
|
}
|
|
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
259
|
|
|
1277
|
-
|
|
1278
|
-
```tsx
|
|
1279
|
-
useEffect(() => {
|
|
1280
|
-
const url = ContentUrlConverter.toBlobUrl(content);
|
|
1281
|
-
setImageUrl(url);
|
|
260
|
+
const request = await buildRequest(selectedFile);
|
|
1282
261
|
|
|
1283
|
-
|
|
1284
|
-
|
|
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");
|
|
1321
|
-
|
|
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
|
-
}
|
|
262
|
+
for await (const step of client.executeStepByStep(request)) {
|
|
263
|
+
console.log(step.status, step.message);
|
|
1340
264
|
}
|
|
1341
265
|
```
|
|
1342
266
|
|
|
1343
|
-
|
|
267
|
+
Browser helpers available in this package include:
|
|
1344
268
|
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
269
|
+
- `AIContentConverter.fromFile(...)`
|
|
270
|
+
- `AIContentConverter.fromMultipleFiles(...)`
|
|
271
|
+
- `AIContentConverter.fromCamera(...)`
|
|
272
|
+
- `AIContentConverter.fromGeolocation(...)`
|
|
273
|
+
- `AIContentConverter.fromMicrophone(...)`
|
|
274
|
+
- `AIContentConverter.fromText(...)`
|
|
1349
275
|
|
|
1350
|
-
|
|
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
|
-
});
|
|
276
|
+
## Example: render or download returned contents
|
|
1362
277
|
|
|
1363
|
-
|
|
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**.
|
|
278
|
+
`AiSceneResponse.contents` can include generated images, audio, or files. `ContentUrlConverter` is the browser-side helper for previewing or downloading them.
|
|
1383
279
|
|
|
1384
280
|
```typescript
|
|
1385
|
-
import {
|
|
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
|
-
}
|
|
281
|
+
import { ContentUrlConverter } from "rystem.playframework.client";
|
|
1450
282
|
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
streamingMode: "tokenStreaming",
|
|
283
|
+
for await (const step of client.executeStepByStep({
|
|
284
|
+
message: "Generate an image of a blue robot"
|
|
1454
285
|
})) {
|
|
1455
|
-
|
|
1456
|
-
|
|
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 |
|
|
286
|
+
const media = step.contents?.[0];
|
|
287
|
+
if (!media) continue;
|
|
1489
288
|
|
|
1490
|
-
|
|
289
|
+
const url = ContentUrlConverter.toBlobUrl(media, `response-${Date.now()}`);
|
|
290
|
+
if (url) {
|
|
291
|
+
console.log("preview", url);
|
|
292
|
+
}
|
|
1491
293
|
|
|
1492
|
-
|
|
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);
|
|
1551
|
-
}
|
|
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);
|
|
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
|
-
);
|
|
294
|
+
ContentUrlConverter.downloadAsFile(media, "playframework-output");
|
|
1594
295
|
}
|
|
1595
296
|
```
|
|
1596
297
|
|
|
1597
|
-
|
|
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:
|
|
298
|
+
Remember to revoke blob URLs you keep around:
|
|
1624
299
|
|
|
1625
300
|
```typescript
|
|
1626
|
-
|
|
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);
|
|
1637
|
-
}
|
|
1638
|
-
} catch (error) {
|
|
1639
|
-
if (error instanceof DOMException && error.name === "AbortError") {
|
|
1640
|
-
console.log("Request cancelled");
|
|
1641
|
-
}
|
|
1642
|
-
}
|
|
1643
|
-
|
|
1644
|
-
// Cancel after 5 seconds
|
|
1645
|
-
setTimeout(() => controller.abort(), 5000);
|
|
1646
|
-
```
|
|
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);
|
|
301
|
+
ContentUrlConverter.revokeUrl(url, cacheKey);
|
|
1691
302
|
```
|
|
1692
303
|
|
|
1693
|
-
|
|
304
|
+
## Example: client-side tools and commands
|
|
1694
305
|
|
|
1695
|
-
|
|
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
|
-
```
|
|
306
|
+
When the server emits `awaitingClient` or `commandClient`, the library can execute browser-side tools locally and resume automatically.
|
|
1705
307
|
|
|
1706
|
-
|
|
308
|
+
This is the same pattern used by the sample app in `src/AI/Rystem.PlayFramework.Client/src/App.tsx`.
|
|
1707
309
|
|
|
1708
310
|
```typescript
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
311
|
+
import {
|
|
312
|
+
AIContentConverter,
|
|
313
|
+
CommandResultHelper,
|
|
314
|
+
PlayFrameworkServices
|
|
315
|
+
} from "rystem.playframework.client";
|
|
1714
316
|
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
// A voice flow is in progress
|
|
1718
|
-
voice.cancelAll();
|
|
1719
|
-
}
|
|
1720
|
-
```
|
|
317
|
+
const client = PlayFrameworkServices.resolve("default");
|
|
318
|
+
const registry = client.getClientRegistry();
|
|
1721
319
|
|
|
1722
|
-
|
|
320
|
+
registry.register("getCurrentLocation", async () => {
|
|
321
|
+
const content = await AIContentConverter.fromGeolocation({ timeout: 10_000 });
|
|
322
|
+
return [content];
|
|
323
|
+
});
|
|
1723
324
|
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
325
|
+
registry.register<{ question?: string }>("getUserConfirmation", async (args) => {
|
|
326
|
+
const confirmed = window.confirm(args?.question ?? "Do you confirm?");
|
|
327
|
+
return [AIContentConverter.fromText(confirmed ? "confirmed" : "denied")];
|
|
328
|
+
});
|
|
1728
329
|
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
}
|
|
1734
|
-
}
|
|
1735
|
-
};
|
|
330
|
+
registry.registerCommand("logUserAction", async (args?: { action?: string }) => {
|
|
331
|
+
console.log("action", args?.action);
|
|
332
|
+
return CommandResultHelper.ok();
|
|
333
|
+
}, { feedbackMode: "never" });
|
|
1736
334
|
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
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
|
-
}
|
|
335
|
+
registry.registerCommand("saveToLocalStorage", async (args?: { key: string; value: string }) => {
|
|
336
|
+
if (!args) {
|
|
337
|
+
return CommandResultHelper.fail("Missing args");
|
|
338
|
+
}
|
|
339
|
+
localStorage.setItem(args.key, args.value);
|
|
340
|
+
return CommandResultHelper.ok(`Saved ${args.key}`);
|
|
341
|
+
}, { feedbackMode: "always" });
|
|
1751
342
|
```
|
|
1752
343
|
|
|
1753
|
-
|
|
344
|
+
Supported command feedback modes are:
|
|
1754
345
|
|
|
1755
|
-
|
|
1756
|
-
|
|
346
|
+
- `never`
|
|
347
|
+
- `onError`
|
|
348
|
+
- `always`
|
|
1757
349
|
|
|
1758
|
-
|
|
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.
|
|
350
|
+
Important behavior:
|
|
1769
351
|
|
|
1770
|
-
|
|
352
|
+
- `PlayFrameworkClient` executes registered tools automatically when the server asks for them
|
|
353
|
+
- tool names must match what the server emits after its own normalization
|
|
354
|
+
- auto-resume uses the returned `conversationKey` and `clientInteractionResults` behind the scenes
|
|
355
|
+
- if a tool is missing, the library sends back an error result instead of silently succeeding
|
|
1771
356
|
|
|
1772
|
-
##
|
|
357
|
+
## Example: conversation management
|
|
1773
358
|
|
|
1774
|
-
|
|
1775
|
-
type AiResponseStatus =
|
|
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
|
|
1797
|
-
```
|
|
359
|
+
`PlayFrameworkClient` exposes:
|
|
1798
360
|
|
|
1799
|
-
|
|
361
|
+
- `listConversations(...)`
|
|
362
|
+
- `getConversation(...)`
|
|
363
|
+
- `deleteConversation(...)`
|
|
364
|
+
- `updateConversationVisibility(...)`
|
|
1800
365
|
|
|
1801
|
-
|
|
366
|
+
Example:
|
|
1802
367
|
|
|
1803
368
|
```typescript
|
|
1804
|
-
import {
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
const settings = new PlayFrameworkSettings("default", "http://localhost:5158/api/ai");
|
|
1809
|
-
const client = new PlayFrameworkClient(settings);
|
|
1810
|
-
|
|
1811
|
-
const responses: string[] = [];
|
|
369
|
+
import {
|
|
370
|
+
ConversationSortOrder,
|
|
371
|
+
PlayFrameworkServices
|
|
372
|
+
} from "rystem.playframework.client";
|
|
1812
373
|
|
|
1813
|
-
|
|
1814
|
-
if (step.message) responses.push(step.message);
|
|
1815
|
-
}
|
|
374
|
+
const client = PlayFrameworkServices.resolve("default");
|
|
1816
375
|
|
|
1817
|
-
|
|
1818
|
-
|
|
376
|
+
const conversations = await client.listConversations({
|
|
377
|
+
searchText: "weather",
|
|
378
|
+
orderBy: ConversationSortOrder.TimestampDescending,
|
|
379
|
+
includePublic: true,
|
|
380
|
+
includePrivate: true,
|
|
381
|
+
skip: 0,
|
|
382
|
+
take: 20
|
|
1819
383
|
});
|
|
1820
|
-
```
|
|
1821
384
|
|
|
1822
|
-
|
|
385
|
+
const selected = conversations[0];
|
|
1823
386
|
|
|
1824
|
-
|
|
387
|
+
if (selected) {
|
|
388
|
+
const fullConversation = await client.getConversation(selected.conversationKey, true);
|
|
389
|
+
console.log(fullConversation?.messages.length);
|
|
1825
390
|
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
Static service locator for managing named `PlayFrameworkClient` instances.
|
|
1829
|
-
|
|
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 |
|
|
1840
|
-
|
|
1841
|
-
```typescript
|
|
1842
|
-
// Configure
|
|
1843
|
-
await PlayFrameworkServices.configure("chat", "http://localhost:5158/api/ai");
|
|
1844
|
-
|
|
1845
|
-
// Resolve
|
|
1846
|
-
const client = PlayFrameworkServices.resolve("chat");
|
|
1847
|
-
|
|
1848
|
-
// Check & remove
|
|
1849
|
-
if (PlayFrameworkServices.isConfigured("chat")) {
|
|
1850
|
-
PlayFrameworkServices.remove("chat");
|
|
391
|
+
await client.updateConversationVisibility(selected.conversationKey, true);
|
|
392
|
+
await client.deleteConversation(selected.conversationKey);
|
|
1851
393
|
}
|
|
1852
394
|
```
|
|
1853
395
|
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
### `PlayFrameworkClient`
|
|
1857
|
-
|
|
1858
|
-
Main client for executing AI requests via SSE streaming.
|
|
1859
|
-
|
|
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 |
|
|
1868
|
-
|
|
1869
|
-
---
|
|
1870
|
-
|
|
1871
|
-
### `ClientInteractionRegistry`
|
|
1872
|
-
|
|
1873
|
-
Registry for client-side tools and commands invoked by the AI during execution.
|
|
1874
|
-
|
|
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 |
|
|
1886
|
-
|
|
1887
|
-
**Types:**
|
|
1888
|
-
|
|
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';
|
|
1893
|
-
|
|
1894
|
-
interface CommandOptions {
|
|
1895
|
-
feedbackMode?: CommandFeedbackMode;
|
|
1896
|
-
}
|
|
1897
|
-
```
|
|
1898
|
-
|
|
1899
|
-
```typescript
|
|
1900
|
-
// Tool — server waits for the result
|
|
1901
|
-
registry.register("myTool", async (args?: { key: string }) => {
|
|
1902
|
-
return [AIContentConverter.fromText(args?.key || "default")];
|
|
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' });
|
|
1910
|
-
```
|
|
1911
|
-
|
|
1912
|
-
---
|
|
1913
|
-
|
|
1914
|
-
### `AIContentConverter`
|
|
1915
|
-
|
|
1916
|
-
#### Static Methods
|
|
396
|
+
These methods call:
|
|
1917
397
|
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
- `fromFile(file: File | Blob): Promise<AIContent>` - Convert file to Base64
|
|
1921
|
-
- `fromMultipleFiles(files: FileList): Promise<AIContent[]>` - Convert multiple files
|
|
1922
|
-
- `fromMicrophone(durationMs?: number, mimeType?: string): Promise<AIContent>` - Record audio
|
|
1923
|
-
- `fromText(text: string): AIContent` - Create text content
|
|
1924
|
-
|
|
1925
|
-
---
|
|
1926
|
-
|
|
1927
|
-
## 🎨 React Hook (`usePlayFramework`)
|
|
1928
|
-
|
|
1929
|
-
```tsx
|
|
1930
|
-
import { usePlayFramework } from "@rystem/playframework-client";
|
|
1931
|
-
|
|
1932
|
-
function MyComponent() {
|
|
1933
|
-
const client = usePlayFramework("default");
|
|
1934
|
-
|
|
1935
|
-
const handleClick = async () => {
|
|
1936
|
-
for await (const step of client.executeStepByStep({ message: "Hello" })) {
|
|
1937
|
-
console.log(step);
|
|
1938
|
-
}
|
|
1939
|
-
};
|
|
1940
|
-
|
|
1941
|
-
return <button onClick={handleClick}>Send</button>;
|
|
1942
|
-
}
|
|
398
|
+
```text
|
|
399
|
+
{baseUrl}/{factoryName}/conversations
|
|
1943
400
|
```
|
|
1944
401
|
|
|
1945
|
-
|
|
402
|
+
They only work when the server has both:
|
|
1946
403
|
|
|
1947
|
-
|
|
404
|
+
- `UseRepository()` and a matching `IRepository<StoredConversation, string>` registration
|
|
405
|
+
- `EnableConversationEndpoints = true` in `MapPlayFramework(...)`
|
|
1948
406
|
|
|
1949
|
-
|
|
407
|
+
## Example: server voice endpoint
|
|
1950
408
|
|
|
1951
|
-
|
|
409
|
+
`executeVoice(...)` targets the PlayFramework HTTP voice endpoint and streams `VoiceEvent` objects back.
|
|
1952
410
|
|
|
1953
411
|
```typescript
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
showNotification(args?.text ?? "");
|
|
1959
|
-
return CommandResult.ok();
|
|
1960
|
-
});
|
|
412
|
+
import {
|
|
413
|
+
PlayFrameworkServices,
|
|
414
|
+
VoiceRecorder
|
|
415
|
+
} from "rystem.playframework.client";
|
|
1961
416
|
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
417
|
+
const client = PlayFrameworkServices.resolve("default");
|
|
418
|
+
const recorder = new VoiceRecorder({ mode: "pushToTalk" });
|
|
419
|
+
|
|
420
|
+
await recorder.start({
|
|
421
|
+
onRecorded: async (blob) => {
|
|
422
|
+
for await (const event of client.executeVoice({
|
|
423
|
+
audio: blob,
|
|
424
|
+
conversationKey: "voice-conversation-1",
|
|
425
|
+
metadata: { userId: "user-42" }
|
|
426
|
+
})) {
|
|
427
|
+
if (event.type === "transcription") {
|
|
428
|
+
console.log("user said", event.text);
|
|
429
|
+
}
|
|
430
|
+
if (event.type === "scene") {
|
|
431
|
+
console.log(event.status, event.message);
|
|
432
|
+
}
|
|
433
|
+
if (event.type === "audio") {
|
|
434
|
+
console.log("received audio chunk", event.audio?.length ?? 0);
|
|
435
|
+
}
|
|
1969
436
|
}
|
|
1970
|
-
}
|
|
437
|
+
}
|
|
438
|
+
});
|
|
1971
439
|
|
|
1972
|
-
//
|
|
1973
|
-
|
|
1974
|
-
await audioPlayer.play(args?.soundId ?? "notification");
|
|
1975
|
-
return CommandResult.ok("Sound played");
|
|
1976
|
-
}, { feedbackMode: 'always' });
|
|
440
|
+
// In push-to-talk mode you stop manually.
|
|
441
|
+
recorder.stop();
|
|
1977
442
|
```
|
|
1978
443
|
|
|
1979
|
-
|
|
444
|
+
This calls:
|
|
1980
445
|
|
|
1981
|
-
```
|
|
1982
|
-
|
|
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" }
|
|
446
|
+
```text
|
|
447
|
+
POST {baseUrl}/{factoryName}/voice
|
|
1991
448
|
```
|
|
1992
449
|
|
|
1993
|
-
|
|
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:
|
|
450
|
+
It only works when the server enables the PlayFramework voice endpoint and has a matching `IVoiceAdapter`.
|
|
2006
451
|
|
|
2007
|
-
|
|
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
|
-
---
|
|
452
|
+
## Example: browser-native voice flow
|
|
2021
453
|
|
|
2022
|
-
|
|
454
|
+
`BrowserVoiceClient` is different from `executeVoice(...)`.
|
|
2023
455
|
|
|
2024
|
-
|
|
456
|
+
It does not use the server voice endpoint. Instead it uses browser speech recognition plus browser speech synthesis and sends the recognized text through the normal PlayFramework SSE endpoints.
|
|
2025
457
|
|
|
2026
458
|
```typescript
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
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
|
-
---
|
|
459
|
+
import {
|
|
460
|
+
BrowserVoiceClient,
|
|
461
|
+
PlayFrameworkServices
|
|
462
|
+
} from "rystem.playframework.client";
|
|
2043
463
|
|
|
2044
|
-
|
|
464
|
+
const client = PlayFrameworkServices.resolve("default");
|
|
2045
465
|
|
|
2046
|
-
|
|
466
|
+
if (BrowserVoiceClient.isSupported()) {
|
|
467
|
+
const voice = new BrowserVoiceClient(
|
|
468
|
+
client,
|
|
469
|
+
{ lang: "en-US" },
|
|
470
|
+
{ lang: "en-US" }
|
|
471
|
+
);
|
|
2047
472
|
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
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
|
|
473
|
+
for await (const event of voice.executeWithBrowserVoice({
|
|
474
|
+
streamingMode: "tokenStreaming",
|
|
475
|
+
request: {
|
|
476
|
+
metadata: { userId: "user-42" },
|
|
477
|
+
settings: {
|
|
478
|
+
executionMode: "Scene",
|
|
479
|
+
sceneName: "General_Requests"
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
})) {
|
|
483
|
+
if (event.voiceStatus === "recognized") {
|
|
484
|
+
console.log("transcript", event.transcript);
|
|
485
|
+
}
|
|
486
|
+
if (event.response?.streamingChunk) {
|
|
487
|
+
console.log(event.response.streamingChunk);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
2073
490
|
}
|
|
2074
491
|
```
|
|
2075
492
|
|
|
2076
|
-
|
|
493
|
+
Useful notes:
|
|
2077
494
|
|
|
2078
|
-
|
|
495
|
+
- `BrowserVoiceClient.isSupported()` checks browser STT + TTS support
|
|
496
|
+
- `speakResponse(...)` is a shortcut when you already have the input text
|
|
497
|
+
- `cancelSpeech()`, `cancelStream()`, and `cancelAll()` are available for UI controls
|
|
498
|
+
- scene names used in direct scene execution must match the server's normalized scene name, so a server scene like `AddScene("General Requests", ...)` is addressed as `General_Requests`
|
|
2079
499
|
|
|
2080
|
-
|
|
500
|
+
## `usePlayFramework`
|
|
2081
501
|
|
|
2082
|
-
|
|
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
|
-
```
|
|
502
|
+
The library exports `usePlayFramework(name?)`, but it is only a convenience accessor over `PlayFrameworkServices.resolve(name)`.
|
|
2111
503
|
|
|
2112
|
-
|
|
504
|
+
It does not manage React state or subscribe to updates by itself.
|
|
2113
505
|
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
Each message in a `StoredConversation.messages` array:
|
|
506
|
+
So even though the name looks React-specific, it is effectively a thin helper rather than a stateful hook system.
|
|
2117
507
|
|
|
2118
508
|
```typescript
|
|
2119
|
-
|
|
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
|
-
---
|
|
509
|
+
import { usePlayFramework } from "rystem.playframework.client";
|
|
2130
510
|
|
|
2131
|
-
|
|
511
|
+
const client = usePlayFramework("default");
|
|
2132
512
|
|
|
2133
|
-
|
|
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
|
|
513
|
+
for await (const step of client.executeStepByStep({ message: "Hello" })) {
|
|
514
|
+
console.log(step.message);
|
|
2143
515
|
}
|
|
2144
516
|
```
|
|
2145
517
|
|
|
2146
|
-
|
|
518
|
+
## Useful exports
|
|
2147
519
|
|
|
2148
|
-
|
|
520
|
+
Besides the main client classes, the package also exports:
|
|
2149
521
|
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
|
|
522
|
+
- `AIContentConverter`
|
|
523
|
+
- `ContentUrlConverter`
|
|
524
|
+
- `VoiceRecorder`
|
|
525
|
+
- `BrowserSpeechRecognizer`
|
|
526
|
+
- `BrowserSpeechSynthesizer`
|
|
527
|
+
- `BrowserVoiceClient`
|
|
528
|
+
- `ConversationSortOrder`
|
|
529
|
+
- `CommandResultHelper`
|
|
2156
530
|
|
|
2157
|
-
|
|
531
|
+
## Important caveats
|
|
2158
532
|
|
|
2159
|
-
|
|
533
|
+
### The final `completed` marker is consumed internally
|
|
2160
534
|
|
|
2161
|
-
|
|
2162
|
-
- 💻 **GitHub**: https://github.com/KeyserDSoze/Rystem
|
|
2163
|
-
- 📦 **npm**: https://www.npmjs.com/package/@rystem/playframework-client
|
|
2164
|
-
- 🎯 **MCP Tools**: https://rystem.net/mcp
|
|
535
|
+
`PlayFrameworkClient` treats `status === "completed"` as an internal stop marker and does not yield that marker to callers as a final event.
|
|
2165
536
|
|
|
2166
|
-
|
|
537
|
+
### `status === "error"` throws
|
|
2167
538
|
|
|
2168
|
-
|
|
539
|
+
Server error markers are converted into thrown exceptions rather than yielded error events.
|
|
2169
540
|
|
|
2170
|
-
|
|
541
|
+
### Library code logs to the console
|
|
2171
542
|
|
|
2172
|
-
|
|
543
|
+
The current runtime includes several `console.log`, `console.warn`, and `console.error` calls.
|
|
2173
544
|
|
|
2174
|
-
|
|
545
|
+
### Auto-resume depends on registered tools
|
|
2175
546
|
|
|
2176
|
-
|
|
547
|
+
If the server asks for a client-side tool and the registry does not contain it, the library sends back an error result rather than magically handling the operation.
|
|
2177
548
|
|
|
2178
|
-
|
|
2179
|
-
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
|
|
2180
|
-
3. Commit your changes (`git commit -m 'Add amazing feature'`)
|
|
2181
|
-
4. Push to the branch (`git push origin feature/amazing-feature`)
|
|
2182
|
-
5. Open a Pull Request
|
|
549
|
+
### `baseUrl` must point to the PlayFramework base path only
|
|
2183
550
|
|
|
2184
|
-
|
|
551
|
+
Use a base such as `http://localhost:5158/api/ai`, not `http://localhost:5158/api/ai/default`. The library appends `/{factoryName}` itself.
|
|
2185
552
|
|
|
2186
|
-
|
|
553
|
+
### Many helpers are browser-only
|
|
2187
554
|
|
|
2188
|
-
|
|
555
|
+
`AIContentConverter.fromCamera(...)`, `AIContentConverter.fromGeolocation(...)`, `AIContentConverter.fromMicrophone(...)`, `VoiceRecorder`, and `BrowserSpeech*` utilities depend on browser APIs and are not SSR-safe by default.
|
|
2189
556
|
|
|
2190
|
-
|
|
2191
|
-
import React, { useState, useRef, useEffect } from 'react';
|
|
2192
|
-
import { usePlayFramework, AIContentConverter } from '@rystem/playframework-client';
|
|
557
|
+
### Browser voice and server voice are different paths
|
|
2193
558
|
|
|
2194
|
-
|
|
2195
|
-
role: 'user' | 'assistant';
|
|
2196
|
-
text: string;
|
|
2197
|
-
status?: string;
|
|
2198
|
-
}
|
|
559
|
+
`BrowserVoiceClient` uses browser STT/TTS plus normal SSE endpoints. `executeVoice(...)` uses the server-side `/voice` endpoint with a server `IVoiceAdapter`.
|
|
2199
560
|
|
|
2200
|
-
|
|
2201
|
-
const client = usePlayFramework('default');
|
|
2202
|
-
const [messages, setMessages] = useState<Message[]>([]);
|
|
2203
|
-
const [input, setInput] = useState('');
|
|
2204
|
-
const [loading, setLoading] = useState(false);
|
|
2205
|
-
const [conversationKey] = useState(crypto.randomUUID());
|
|
2206
|
-
|
|
2207
|
-
// Register client tools
|
|
2208
|
-
useEffect(() => {
|
|
2209
|
-
const registry = client.getClientRegistry();
|
|
2210
|
-
|
|
2211
|
-
registry.register('getCurrentLocation', async () => {
|
|
2212
|
-
const content = await AIContentConverter.fromGeolocation();
|
|
2213
|
-
return [content];
|
|
2214
|
-
});
|
|
2215
|
-
|
|
2216
|
-
registry.register('getUserConfirmation', async (args?: { question?: string }) => {
|
|
2217
|
-
const confirmed = window.confirm(args?.question ?? 'Do you confirm?');
|
|
2218
|
-
return [AIContentConverter.fromText(confirmed ? 'confirmed' : 'denied')];
|
|
2219
|
-
});
|
|
2220
|
-
}, [client]);
|
|
2221
|
-
|
|
2222
|
-
const handleSend = async () => {
|
|
2223
|
-
if (!input.trim() || loading) return;
|
|
2224
|
-
|
|
2225
|
-
const userMessage: Message = { role: 'user', text: input };
|
|
2226
|
-
setMessages(prev => [...prev, userMessage]);
|
|
2227
|
-
setInput('');
|
|
2228
|
-
setLoading(true);
|
|
2229
|
-
|
|
2230
|
-
try {
|
|
2231
|
-
const assistantMessage: Message = { role: 'assistant', text: '', status: 'initializing' };
|
|
2232
|
-
setMessages(prev => [...prev, assistantMessage]);
|
|
2233
|
-
|
|
2234
|
-
for await (const step of client.executeStepByStep({
|
|
2235
|
-
message: input,
|
|
2236
|
-
settings: {
|
|
2237
|
-
conversationKey,
|
|
2238
|
-
executionMode: 'Direct',
|
|
2239
|
-
enableStreaming: true
|
|
2240
|
-
}
|
|
2241
|
-
})) {
|
|
2242
|
-
setMessages(prev => {
|
|
2243
|
-
const updated = [...prev];
|
|
2244
|
-
const last = updated[updated.length - 1];
|
|
2245
|
-
|
|
2246
|
-
if (step.streamingChunk) {
|
|
2247
|
-
last.text += step.streamingChunk;
|
|
2248
|
-
} else if (step.message) {
|
|
2249
|
-
last.text = step.message;
|
|
2250
|
-
}
|
|
2251
|
-
last.status = step.status;
|
|
2252
|
-
|
|
2253
|
-
return updated;
|
|
2254
|
-
});
|
|
2255
|
-
}
|
|
2256
|
-
} catch (error) {
|
|
2257
|
-
console.error('Chat error:', error);
|
|
2258
|
-
setMessages(prev => [...prev, {
|
|
2259
|
-
role: 'assistant',
|
|
2260
|
-
text: `Error: ${error instanceof Error ? error.message : 'Unknown error'}`,
|
|
2261
|
-
status: 'error'
|
|
2262
|
-
}]);
|
|
2263
|
-
} finally {
|
|
2264
|
-
setLoading(false);
|
|
2265
|
-
}
|
|
2266
|
-
};
|
|
561
|
+
### `usePlayFramework(...)` is not a real reactive hook
|
|
2267
562
|
|
|
2268
|
-
|
|
2269
|
-
<div style={{ maxWidth: '800px', margin: '0 auto', padding: '20px' }}>
|
|
2270
|
-
<h1>PlayFramework Chat</h1>
|
|
2271
|
-
|
|
2272
|
-
<div style={{ height: '500px', overflowY: 'auto', border: '1px solid #ccc', padding: '10px', marginBottom: '10px' }}>
|
|
2273
|
-
{messages.map((msg, i) => (
|
|
2274
|
-
<div key={i} style={{
|
|
2275
|
-
padding: '10px',
|
|
2276
|
-
margin: '5px 0',
|
|
2277
|
-
borderRadius: '8px',
|
|
2278
|
-
backgroundColor: msg.role === 'user' ? '#e3f2fd' : '#f5f5f5',
|
|
2279
|
-
textAlign: msg.role === 'user' ? 'right' : 'left'
|
|
2280
|
-
}}>
|
|
2281
|
-
<strong>{msg.role === 'user' ? 'You' : 'AI'}</strong>
|
|
2282
|
-
{msg.status && <small style={{ color: '#666', marginLeft: '8px' }}>[{msg.status}]</small>}
|
|
2283
|
-
<div>{msg.text}</div>
|
|
2284
|
-
</div>
|
|
2285
|
-
))}
|
|
2286
|
-
</div>
|
|
2287
|
-
|
|
2288
|
-
<div style={{ display: 'flex', gap: '10px' }}>
|
|
2289
|
-
<input
|
|
2290
|
-
type="text"
|
|
2291
|
-
value={input}
|
|
2292
|
-
onChange={e => setInput(e.target.value)}
|
|
2293
|
-
onKeyDown={e => e.key === 'Enter' && handleSend()}
|
|
2294
|
-
placeholder="Type a message..."
|
|
2295
|
-
disabled={loading}
|
|
2296
|
-
style={{ flex: 1, padding: '10px', fontSize: '16px' }}
|
|
2297
|
-
/>
|
|
2298
|
-
<button onClick={handleSend} disabled={loading} style={{ padding: '10px 20px', fontSize: '16px' }}>
|
|
2299
|
-
{loading ? 'Sending...' : 'Send'}
|
|
2300
|
-
</button>
|
|
2301
|
-
</div>
|
|
2302
|
-
</div>
|
|
2303
|
-
);
|
|
2304
|
-
}
|
|
563
|
+
It is only a resolver helper over `PlayFrameworkServices.resolve(...)`.
|
|
2305
564
|
|
|
2306
|
-
|
|
2307
|
-
```
|
|
565
|
+
## Grounded by source files
|
|
2308
566
|
|
|
2309
|
-
|
|
567
|
+
- `src/AI/Rystem.PlayFramework.Client/src/rystem/src/servicecollection/PlayFrameworkServices.ts`
|
|
568
|
+
- `src/AI/Rystem.PlayFramework.Client/src/rystem/src/servicecollection/PlayFrameworkSettings.ts`
|
|
569
|
+
- `src/AI/Rystem.PlayFramework.Client/src/rystem/src/engine/PlayFrameworkClient.ts`
|
|
570
|
+
- `src/AI/Rystem.PlayFramework.Client/src/rystem/src/engine/ClientInteractionRegistry.ts`
|
|
571
|
+
- `src/AI/Rystem.PlayFramework.Client/src/rystem/src/utils/AIContentConverter.ts`
|
|
572
|
+
- `src/AI/Rystem.PlayFramework.Client/src/rystem/src/utils/ContentUrlConverter.ts`
|
|
573
|
+
- `src/AI/Rystem.PlayFramework.Client/src/rystem/src/utils/VoiceRecorder.ts`
|
|
574
|
+
- `src/AI/Rystem.PlayFramework.Client/src/rystem/src/utils/BrowserVoiceClient.ts`
|
|
575
|
+
- `src/AI/Rystem.PlayFramework.Client/src/rystem/src/hooks/hooks.ts`
|
|
576
|
+
- `src/AI/Rystem.PlayFramework.Client/src/App.tsx`
|
|
2310
577
|
|
|
2311
|
-
|
|
578
|
+
Use this package when you want a typed client for a PlayFramework backend, including SSE execution, browser tool continuation, conversations, and both server-side and browser-side voice flows.
|