rystem.playframework.client 0.1.2 → 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 +380 -1666
- package/lib/engine/PlayFrameworkClient.d.ts +19 -0
- package/lib/engine/PlayFrameworkClient.d.ts.map +1 -1
- package/lib/engine/PlayFrameworkClient.js +95 -7
- package/lib/index.d.ts +9 -0
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +9 -1
- package/lib/models/PlayFrameworkRequest.d.ts +10 -0
- package/lib/models/PlayFrameworkRequest.d.ts.map +1 -1
- package/lib/models/VoiceResponse.d.ts +39 -0
- package/lib/models/VoiceResponse.d.ts.map +1 -0
- package/lib/models/VoiceResponse.js +2 -0
- package/lib/utils/BrowserSpeechRecognizer.d.ts +128 -0
- package/lib/utils/BrowserSpeechRecognizer.d.ts.map +1 -0
- package/lib/utils/BrowserSpeechRecognizer.js +150 -0
- package/lib/utils/BrowserSpeechSynthesizer.d.ts +148 -0
- package/lib/utils/BrowserSpeechSynthesizer.d.ts.map +1 -0
- package/lib/utils/BrowserSpeechSynthesizer.js +400 -0
- package/lib/utils/BrowserVoiceClient.d.ts +142 -0
- package/lib/utils/BrowserVoiceClient.d.ts.map +1 -0
- package/lib/utils/BrowserVoiceClient.js +200 -0
- package/lib/utils/VoiceRecorder.d.ts +90 -0
- package/lib/utils/VoiceRecorder.d.ts.map +1 -0
- package/lib/utils/VoiceRecorder.js +195 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,1864 +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
|
|
7
|
+
## Installation
|
|
18
8
|
|
|
19
|
-
---
|
|
20
|
-
|
|
21
|
-
## 📦 Installation
|
|
22
|
-
|
|
23
|
-
```bash
|
|
24
|
-
npm install @rystem/playframework-client
|
|
25
|
-
```
|
|
26
|
-
|
|
27
|
-
Or with yarn:
|
|
28
9
|
```bash
|
|
29
|
-
|
|
10
|
+
npm install rystem.playframework.client
|
|
30
11
|
```
|
|
31
12
|
|
|
32
|
-
|
|
13
|
+
The current package name in `package.json` is `rystem.playframework.client`.
|
|
33
14
|
|
|
34
|
-
##
|
|
15
|
+
## What this package expects from the server
|
|
35
16
|
|
|
36
|
-
|
|
17
|
+
This client assumes a backend that maps PlayFramework under a base path such as:
|
|
37
18
|
|
|
38
|
-
```
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
settings.
|
|
44
|
-
settings.maxReconnectAttempts = 3;
|
|
45
|
-
settings.reconnectBaseDelay = 1000;
|
|
19
|
+
```csharp
|
|
20
|
+
app.MapPlayFramework("default", settings =>
|
|
21
|
+
{
|
|
22
|
+
settings.BasePath = "/api/ai";
|
|
23
|
+
settings.EnableConversationEndpoints = true;
|
|
24
|
+
settings.EnableVoiceEndpoints = true;
|
|
46
25
|
});
|
|
47
26
|
```
|
|
48
27
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
```typescript
|
|
52
|
-
const client = PlayFrameworkServices.resolve("default");
|
|
53
|
-
|
|
54
|
-
// Step-by-step streaming
|
|
55
|
-
for await (const step of client.executeStepByStep({
|
|
56
|
-
message: "Tell me a joke"
|
|
57
|
-
})) {
|
|
58
|
-
console.log(`[${step.status}] ${step.message}`);
|
|
59
|
-
}
|
|
60
|
-
// Output:
|
|
61
|
-
// [planning] Analyzing request...
|
|
62
|
-
// [executingScene] Generating joke...
|
|
63
|
-
// [completed] Why did the chicken cross the road? To get to the other side!
|
|
64
|
-
|
|
65
|
-
// Token-level streaming (real-time chunks)
|
|
66
|
-
for await (const chunk of client.executeTokenStreaming({
|
|
67
|
-
message: "Write a short story"
|
|
68
|
-
})) {
|
|
69
|
-
process.stdout.write(chunk.streamingChunk || "");
|
|
70
|
-
}
|
|
71
|
-
// Output: "Once" → " upon" → " a" → " time" → "..."
|
|
72
|
-
```
|
|
73
|
-
|
|
74
|
-
### 3. Use with React
|
|
75
|
-
|
|
76
|
-
```tsx
|
|
77
|
-
import { usePlayFramework } from "@rystem/playframework-client";
|
|
78
|
-
import { useState } from "react";
|
|
79
|
-
|
|
80
|
-
function ChatComponent() {
|
|
81
|
-
const client = usePlayFramework("default");
|
|
82
|
-
const [messages, setMessages] = useState<string[]>([]);
|
|
83
|
-
const [loading, setLoading] = useState(false);
|
|
84
|
-
|
|
85
|
-
const handleSend = async (input: string) => {
|
|
86
|
-
setLoading(true);
|
|
87
|
-
const newMessages: string[] = [];
|
|
88
|
-
|
|
89
|
-
try {
|
|
90
|
-
for await (const step of client.executeStepByStep({
|
|
91
|
-
message: input
|
|
92
|
-
})) {
|
|
93
|
-
if (step.streamingChunk) {
|
|
94
|
-
// Real-time token streaming
|
|
95
|
-
newMessages.push(step.streamingChunk);
|
|
96
|
-
} else if (step.message) {
|
|
97
|
-
// Step-by-step message
|
|
98
|
-
newMessages.push(`[${step.status}] ${step.message}`);
|
|
99
|
-
}
|
|
100
|
-
setMessages([...newMessages]);
|
|
101
|
-
}
|
|
102
|
-
} finally {
|
|
103
|
-
setLoading(false);
|
|
104
|
-
}
|
|
105
|
-
};
|
|
28
|
+
When you configure the TypeScript client with:
|
|
106
29
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
<input onKeyDown={e => e.key === 'Enter' && handleSend(e.currentTarget.value)} />
|
|
110
|
-
<div>
|
|
111
|
-
{messages.map((msg, i) => <div key={i}>{msg}</div>)}
|
|
112
|
-
</div>
|
|
113
|
-
</div>
|
|
114
|
-
);
|
|
115
|
-
}
|
|
30
|
+
```text
|
|
31
|
+
http://localhost:5158/api/ai
|
|
116
32
|
```
|
|
117
33
|
|
|
118
|
-
|
|
34
|
+
the library appends `/{factoryName}` itself.
|
|
119
35
|
|
|
120
|
-
|
|
36
|
+
So for the `default` factory it calls:
|
|
121
37
|
|
|
122
|
-
|
|
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`
|
|
123
42
|
|
|
124
|
-
|
|
125
|
-
- Returns each **scene/actor execution** as separate event
|
|
126
|
-
- Best for: Multi-step workflows, debugging, progress tracking
|
|
127
|
-
- Example: Planning → Actor1 → Actor2 → Completed
|
|
43
|
+
## Architecture
|
|
128
44
|
|
|
129
|
-
|
|
130
|
-
- Returns **individual text chunks** as they're generated
|
|
131
|
-
- Best for: Real-time chat UIs, typewriter effects
|
|
132
|
-
- Example: "Hello" → " world" → "!" → "..."
|
|
45
|
+
The package is built around:
|
|
133
46
|
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
// Token streaming - real-time chunks
|
|
143
|
-
for await (const chunk of client.executeTokenStreaming({ message: "..." })) {
|
|
144
|
-
console.log(chunk.streamingChunk); // "Hello", " world", "!"
|
|
145
|
-
}
|
|
146
|
-
```
|
|
47
|
+
- `PlayFrameworkServices`
|
|
48
|
+
- `PlayFrameworkClient`
|
|
49
|
+
- `ClientInteractionRegistry`
|
|
50
|
+
- `AIContentConverter`
|
|
51
|
+
- `ContentUrlConverter`
|
|
52
|
+
- `VoiceRecorder`
|
|
53
|
+
- `BrowserVoiceClient`
|
|
54
|
+
- `usePlayFramework`
|
|
147
55
|
|
|
148
|
-
|
|
56
|
+
The usual lifecycle is:
|
|
149
57
|
|
|
150
|
-
|
|
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
|
|
151
63
|
|
|
152
|
-
|
|
64
|
+
## Example: bootstrap one client
|
|
153
65
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
```csharp
|
|
157
|
-
services.AddPlayFramework(builder =>
|
|
158
|
-
{
|
|
159
|
-
builder.AddScene("vision", "Analyze user photos", scene =>
|
|
160
|
-
{
|
|
161
|
-
scene.OnClient(client =>
|
|
162
|
-
{
|
|
163
|
-
client.AddTool("capturePhoto", "Take photo from camera");
|
|
164
|
-
client.AddTool("getCurrentLocation", "Get GPS coordinates");
|
|
165
|
-
client.AddTool("selectFiles", "Open file picker");
|
|
166
|
-
});
|
|
167
|
-
});
|
|
168
|
-
});
|
|
169
|
-
```
|
|
170
|
-
|
|
171
|
-
### Client Setup (TypeScript)
|
|
66
|
+
`PlayFrameworkServices.configure(...)` is async and should usually run during application startup.
|
|
172
67
|
|
|
173
68
|
```typescript
|
|
174
|
-
import { PlayFrameworkServices
|
|
69
|
+
import { PlayFrameworkServices } from "rystem.playframework.client";
|
|
175
70
|
|
|
176
|
-
|
|
177
|
-
|
|
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;
|
|
178
75
|
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
return [content];
|
|
186
|
-
});
|
|
187
|
-
|
|
188
|
-
// Register geolocation tool
|
|
189
|
-
registry.register("getCurrentLocation", async () => {
|
|
190
|
-
const content = await AIContentConverter.fromGeolocation({ timeout: 10_000 });
|
|
191
|
-
return [content];
|
|
192
|
-
});
|
|
76
|
+
settings.addHeadersEnricher(async (_url, _method, headers) => {
|
|
77
|
+
return {
|
|
78
|
+
...Object.fromEntries(new Headers(headers).entries()),
|
|
79
|
+
Authorization: `Bearer ${localStorage.getItem("token") ?? ""}`
|
|
80
|
+
};
|
|
81
|
+
});
|
|
193
82
|
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
input.onchange = async () => {
|
|
201
|
-
const contents = await AIContentConverter.fromMultipleFiles(input.files!);
|
|
202
|
-
resolve(contents);
|
|
203
|
-
};
|
|
204
|
-
input.click();
|
|
205
|
-
});
|
|
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
|
+
});
|
|
206
89
|
});
|
|
207
|
-
```
|
|
208
|
-
|
|
209
|
-
**Client automatically resumes execution after tool completion!**
|
|
210
90
|
|
|
211
|
-
|
|
212
|
-
for await (const step of client.executeStepByStep({ message: "Take a photo and describe it" })) {
|
|
213
|
-
console.log(step.status);
|
|
214
|
-
// 1. "executingScene" - LLM requests camera
|
|
215
|
-
// 2. "awaitingClient" - Client executes tool
|
|
216
|
-
// 3. "executingScene" - LLM analyzes photo
|
|
217
|
-
// 4. "completed" - Final response
|
|
218
|
-
}
|
|
91
|
+
const client = PlayFrameworkServices.resolve("default");
|
|
219
92
|
```
|
|
220
93
|
|
|
221
|
-
|
|
94
|
+
If you only configure one factory, `resolve()` with no name returns the first configured client:
|
|
222
95
|
|
|
223
96
|
```typescript
|
|
224
|
-
|
|
225
|
-
const photo = await AIContentConverter.fromCamera();
|
|
226
|
-
|
|
227
|
-
// Geolocation (returns JSON with lat/lng)
|
|
228
|
-
const location = await AIContentConverter.fromGeolocation();
|
|
229
|
-
|
|
230
|
-
// File upload (returns Base64 data)
|
|
231
|
-
const file = await AIContentConverter.fromFile(fileInput.files[0]);
|
|
232
|
-
|
|
233
|
-
// Multiple files
|
|
234
|
-
const files = await AIContentConverter.fromMultipleFiles(fileInput.files);
|
|
235
|
-
|
|
236
|
-
// Microphone (returns Base64 audio)
|
|
237
|
-
const audio = await AIContentConverter.fromMicrophone(5000); // 5 seconds
|
|
238
|
-
|
|
239
|
-
// Plain text
|
|
240
|
-
const text = AIContentConverter.fromText("Hello world");
|
|
97
|
+
const defaultClient = PlayFrameworkServices.resolve();
|
|
241
98
|
```
|
|
242
99
|
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
## 🎛️ Execution Modes
|
|
100
|
+
## Example: configure multiple factories
|
|
246
101
|
|
|
247
|
-
|
|
102
|
+
The sample workspace in `src/AI/Rystem.PlayFramework.Client/src/App.tsx` configures both `default` and `foundry` against the same base path.
|
|
248
103
|
|
|
249
104
|
```typescript
|
|
250
|
-
|
|
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
|
+
]);
|
|
251
113
|
|
|
252
|
-
const
|
|
253
|
-
|
|
254
|
-
settings: {
|
|
255
|
-
executionMode: "Planning", // Direct | Planning | DynamicChaining | Scene
|
|
256
|
-
maxRecursionDepth: 5,
|
|
257
|
-
enableSummarization: true,
|
|
258
|
-
enableDirector: false
|
|
259
|
-
}
|
|
260
|
-
};
|
|
114
|
+
const cloudClient = PlayFrameworkServices.resolve("default");
|
|
115
|
+
const localClient = PlayFrameworkServices.resolve("foundry");
|
|
261
116
|
```
|
|
262
117
|
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
| Mode | Description | Use Case |
|
|
266
|
-
|------|-------------|----------|
|
|
267
|
-
| `Direct` | Single scene, no planning | Simple queries, fast responses |
|
|
268
|
-
| `Planning` | Upfront multi-step plan | Known workflows (booking, checkout) |
|
|
269
|
-
| `DynamicChaining` | LLM decides next step live | Exploratory tasks (research, debugging) |
|
|
270
|
-
| `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.
|
|
271
119
|
|
|
272
|
-
|
|
120
|
+
## Example: step-by-step streaming
|
|
273
121
|
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
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.
|
|
277
123
|
|
|
278
124
|
```typescript
|
|
279
|
-
import { PlayFrameworkRequest
|
|
125
|
+
import type { PlayFrameworkRequest } from "rystem.playframework.client";
|
|
280
126
|
|
|
281
127
|
const request: PlayFrameworkRequest = {
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
data: "JVBERi0xLjQKJeLjz9M...",
|
|
292
|
-
mediaType: "application/pdf"
|
|
293
|
-
},
|
|
294
|
-
{
|
|
295
|
-
type: "uri",
|
|
296
|
-
uri: "https://example.com/document.pdf",
|
|
297
|
-
mediaType: "application/pdf"
|
|
298
|
-
},
|
|
299
|
-
{
|
|
300
|
-
type: "text",
|
|
301
|
-
text: "Additional context"
|
|
302
|
-
}
|
|
303
|
-
]
|
|
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
|
+
}
|
|
304
137
|
};
|
|
305
138
|
|
|
306
139
|
for await (const step of client.executeStepByStep(request)) {
|
|
307
|
-
|
|
140
|
+
console.log(step.status, step.sceneName, step.message);
|
|
141
|
+
|
|
142
|
+
if (step.totalTokens != null || step.totalCost != null) {
|
|
143
|
+
console.log("usage", step.totalTokens, step.totalCost);
|
|
144
|
+
}
|
|
308
145
|
}
|
|
309
146
|
```
|
|
310
147
|
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
## ⚙️ Configuration & Settings
|
|
314
|
-
|
|
315
|
-
### Global Configuration
|
|
316
|
-
|
|
317
|
-
```typescript
|
|
318
|
-
import { PlayFrameworkServices } from "@rystem/playframework-client";
|
|
319
|
-
|
|
320
|
-
await PlayFrameworkServices.configure("premium", "https://api.example.com/api/ai", settings => {
|
|
321
|
-
// Timeout (ms)
|
|
322
|
-
settings.timeout = 120_000; // 2 minutes
|
|
323
|
-
|
|
324
|
-
// Reconnection on SSE failures
|
|
325
|
-
settings.maxReconnectAttempts = 3;
|
|
326
|
-
settings.reconnectBaseDelay = 1000; // 1 second
|
|
148
|
+
This calls:
|
|
327
149
|
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
"Content-Type": "application/json",
|
|
331
|
-
"X-App-Version": "1.0.0"
|
|
332
|
-
};
|
|
333
|
-
|
|
334
|
-
// Dynamic headers (auth token)
|
|
335
|
-
settings.addHeadersEnricher(async (url, method, headers, body) => {
|
|
336
|
-
const token = await getAuthToken();
|
|
337
|
-
return {
|
|
338
|
-
...headers,
|
|
339
|
-
"Authorization": `Bearer ${token}`
|
|
340
|
-
};
|
|
341
|
-
});
|
|
342
|
-
|
|
343
|
-
// Error handling with retry
|
|
344
|
-
settings.addErrorHandler(async (url, method, headers, body, error) => {
|
|
345
|
-
if (error.message.includes("401")) {
|
|
346
|
-
await refreshAuthToken();
|
|
347
|
-
return true; // Retry
|
|
348
|
-
}
|
|
349
|
-
return false; // Don't retry
|
|
350
|
-
});
|
|
351
|
-
});
|
|
150
|
+
```text
|
|
151
|
+
POST {baseUrl}/{factoryName}
|
|
352
152
|
```
|
|
353
153
|
|
|
354
|
-
|
|
154
|
+
Common yielded statuses include:
|
|
355
155
|
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
maxRecursionDepth: 5, // Max planning depth
|
|
365
|
-
maxDynamicScenes: 10, // Max scenes in DynamicChaining
|
|
366
|
-
|
|
367
|
-
// Features
|
|
368
|
-
enableSummarization: true, // Auto-summarize long contexts
|
|
369
|
-
enableDirector: false, // Multi-scene orchestration
|
|
370
|
-
enableStreaming: true, // Token-level streaming
|
|
371
|
-
|
|
372
|
-
// Model overrides
|
|
373
|
-
modelId: "gpt-4o", // Override default model
|
|
374
|
-
temperature: 0.7, // 0.0 - 2.0
|
|
375
|
-
maxTokens: 4096, // Max response tokens
|
|
376
|
-
|
|
377
|
-
// Caching
|
|
378
|
-
cacheBehavior: "Default", // Default | Avoidable | Forever
|
|
379
|
-
conversationKey: "user-123-session-1", // Unique conversation ID
|
|
380
|
-
|
|
381
|
-
// Budget
|
|
382
|
-
maxBudget: 0.50, // Max cost in USD (null = unlimited)
|
|
383
|
-
|
|
384
|
-
// Scene selection (Scene mode only)
|
|
385
|
-
sceneName: "SpecificScene" // Execute specific scene
|
|
386
|
-
},
|
|
387
|
-
metadata: {
|
|
388
|
-
userId: "user-123",
|
|
389
|
-
sessionId: "session-abc",
|
|
390
|
-
customKey: "customValue"
|
|
391
|
-
}
|
|
392
|
-
};
|
|
393
|
-
```
|
|
156
|
+
- `initializing`
|
|
157
|
+
- `planning`
|
|
158
|
+
- `executingScene`
|
|
159
|
+
- `functionRequest`
|
|
160
|
+
- `functionCompleted`
|
|
161
|
+
- `running`
|
|
162
|
+
- `awaitingClient`
|
|
163
|
+
- `commandClient`
|
|
394
164
|
|
|
395
|
-
|
|
165
|
+
Completion and error markers are handled internally by the client runtime rather than surfaced as normal yielded events.
|
|
396
166
|
|
|
397
|
-
##
|
|
167
|
+
## Example: token streaming
|
|
398
168
|
|
|
399
|
-
|
|
169
|
+
`executeTokenStreaming(...)` still yields `AiSceneResponse` objects, but the text arrives through `streamingChunk`.
|
|
400
170
|
|
|
401
171
|
```typescript
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
// First request
|
|
405
|
-
for await (const step of client.executeStepByStep({
|
|
406
|
-
message: "What's the weather in Paris?",
|
|
407
|
-
settings: { conversationKey }
|
|
408
|
-
})) {
|
|
409
|
-
console.log(step.message);
|
|
410
|
-
}
|
|
172
|
+
let finalText = "";
|
|
411
173
|
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
174
|
+
for await (const chunk of client.executeTokenStreaming({
|
|
175
|
+
message: "Write a short summary of PlayFramework",
|
|
176
|
+
settings: {
|
|
177
|
+
executionMode: "Direct"
|
|
178
|
+
}
|
|
416
179
|
})) {
|
|
417
|
-
|
|
180
|
+
if (chunk.streamingChunk) {
|
|
181
|
+
finalText += chunk.streamingChunk;
|
|
182
|
+
console.log(chunk.streamingChunk);
|
|
183
|
+
}
|
|
418
184
|
}
|
|
419
|
-
```
|
|
420
|
-
|
|
421
|
-
---
|
|
422
|
-
|
|
423
|
-
## 💾 Conversation Management (Repository Pattern)
|
|
424
|
-
|
|
425
|
-
If the backend has **Repository persistence enabled**, you can manage conversations using REST endpoints.
|
|
426
|
-
|
|
427
|
-
### List Conversations
|
|
428
|
-
|
|
429
|
-
```typescript
|
|
430
|
-
import { ConversationSortOrder } from "@rystem/playframework-client";
|
|
431
|
-
|
|
432
|
-
// Get conversations with filters
|
|
433
|
-
const conversations = await client.listConversations({
|
|
434
|
-
searchText: "weather", // Search in message text
|
|
435
|
-
includePublic: true, // Include public conversations
|
|
436
|
-
includePrivate: true, // Include private conversations
|
|
437
|
-
orderBy: ConversationSortOrder.TimestampDescending, // Sort by newest first
|
|
438
|
-
skip: 0, // Pagination offset
|
|
439
|
-
take: 50 // Page size
|
|
440
|
-
});
|
|
441
|
-
|
|
442
|
-
console.log(conversations);
|
|
443
|
-
// [
|
|
444
|
-
// {
|
|
445
|
-
// conversationKey: "abc-123",
|
|
446
|
-
// userId: "user@example.com",
|
|
447
|
-
// isPublic: false,
|
|
448
|
-
// timestamp: "2025-01-15T10:30:00Z",
|
|
449
|
-
// messages: [...],
|
|
450
|
-
// executionState: {...}
|
|
451
|
-
// }
|
|
452
|
-
// ]
|
|
453
|
-
```
|
|
454
|
-
|
|
455
|
-
### Get Single Conversation
|
|
456
185
|
|
|
457
|
-
|
|
458
|
-
const conversation = await client.getConversation("abc-123");
|
|
459
|
-
|
|
460
|
-
if (conversation) {
|
|
461
|
-
console.log(conversation.messages); // Full message history
|
|
462
|
-
console.log(conversation.isPublic); // Public vs private
|
|
463
|
-
} else {
|
|
464
|
-
console.log("Conversation not found or unauthorized");
|
|
465
|
-
}
|
|
186
|
+
console.log("final", finalText);
|
|
466
187
|
```
|
|
467
188
|
|
|
468
|
-
|
|
189
|
+
This calls:
|
|
469
190
|
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
```typescript
|
|
473
|
-
// Owner-only operation
|
|
474
|
-
await client.deleteConversation("abc-123");
|
|
475
|
-
console.log("Conversation deleted");
|
|
191
|
+
```text
|
|
192
|
+
POST {baseUrl}/{factoryName}/streaming
|
|
476
193
|
```
|
|
477
194
|
|
|
478
|
-
|
|
479
|
-
- ✅ Success - Conversation deleted
|
|
480
|
-
- ❌ `403 Forbidden` - Not the owner
|
|
481
|
-
- ❌ `404 Not Found` - Conversation not found
|
|
195
|
+
## Request model
|
|
482
196
|
|
|
483
|
-
|
|
197
|
+
The main request type is `PlayFrameworkRequest`.
|
|
484
198
|
|
|
485
199
|
```typescript
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
const client = usePlayFramework("default");
|
|
499
|
-
const [conversations, setConversations] = useState<StoredConversation[]>([]);
|
|
500
|
-
const [searchText, setSearchText] = useState("");
|
|
501
|
-
const [showPublic, setShowPublic] = useState(true);
|
|
502
|
-
const [showPrivate, setShowPrivate] = useState(true);
|
|
503
|
-
const [loading, setLoading] = useState(false);
|
|
504
|
-
|
|
505
|
-
const loadConversations = async () => {
|
|
506
|
-
setLoading(true);
|
|
507
|
-
try {
|
|
508
|
-
const result = await client.listConversations({
|
|
509
|
-
searchText: searchText || undefined,
|
|
510
|
-
includePublic: showPublic,
|
|
511
|
-
includePrivate: showPrivate,
|
|
512
|
-
orderBy: ConversationSortOrder.TimestampDescending,
|
|
513
|
-
take: 100
|
|
514
|
-
});
|
|
515
|
-
setConversations(result);
|
|
516
|
-
} catch (error) {
|
|
517
|
-
console.error("Failed to load conversations:", error);
|
|
518
|
-
} finally {
|
|
519
|
-
setLoading(false);
|
|
520
|
-
}
|
|
521
|
-
};
|
|
522
|
-
|
|
523
|
-
useEffect(() => {
|
|
524
|
-
loadConversations();
|
|
525
|
-
}, [showPublic, showPrivate]);
|
|
526
|
-
|
|
527
|
-
const handleDelete = async (key: string) => {
|
|
528
|
-
if (!window.confirm("Delete this conversation?")) return;
|
|
529
|
-
try {
|
|
530
|
-
await client.deleteConversation(key);
|
|
531
|
-
await loadConversations(); // Reload list
|
|
532
|
-
} catch (error: any) {
|
|
533
|
-
alert(`Failed to delete: ${error.message}`);
|
|
534
|
-
}
|
|
535
|
-
};
|
|
536
|
-
|
|
537
|
-
const handleLoadConversation = async (key: string) => {
|
|
538
|
-
const conv = await client.getConversation(key);
|
|
539
|
-
if (conv) {
|
|
540
|
-
// Load conversation into chat UI
|
|
541
|
-
console.log("Loaded:", conv.messages);
|
|
542
|
-
}
|
|
543
|
-
};
|
|
544
|
-
|
|
545
|
-
return (
|
|
546
|
-
<div>
|
|
547
|
-
<h2>Conversations</h2>
|
|
548
|
-
|
|
549
|
-
{/* Search & Filters */}
|
|
550
|
-
<input
|
|
551
|
-
type="text"
|
|
552
|
-
placeholder="Search messages..."
|
|
553
|
-
value={searchText}
|
|
554
|
-
onChange={e => setSearchText(e.target.value)}
|
|
555
|
-
/>
|
|
556
|
-
<button onClick={loadConversations}>Search</button>
|
|
557
|
-
|
|
558
|
-
<label>
|
|
559
|
-
<input
|
|
560
|
-
type="checkbox"
|
|
561
|
-
checked={showPublic}
|
|
562
|
-
onChange={e => setShowPublic(e.target.checked)}
|
|
563
|
-
/>
|
|
564
|
-
Public
|
|
565
|
-
</label>
|
|
566
|
-
<label>
|
|
567
|
-
<input
|
|
568
|
-
type="checkbox"
|
|
569
|
-
checked={showPrivate}
|
|
570
|
-
onChange={e => setShowPrivate(e.target.checked)}
|
|
571
|
-
/>
|
|
572
|
-
Private
|
|
573
|
-
</label>
|
|
574
|
-
|
|
575
|
-
{/* Conversation List */}
|
|
576
|
-
{loading ? (
|
|
577
|
-
<div>Loading...</div>
|
|
578
|
-
) : (
|
|
579
|
-
<ul>
|
|
580
|
-
{conversations.map(conv => (
|
|
581
|
-
<li key={conv.conversationKey}>
|
|
582
|
-
<div onClick={() => handleLoadConversation(conv.conversationKey)}>
|
|
583
|
-
<strong>{new Date(conv.timestamp).toLocaleString()}</strong>
|
|
584
|
-
<span style={{ color: conv.isPublic ? "green" : "red" }}>
|
|
585
|
-
{conv.isPublic ? "Public" : "Private"}
|
|
586
|
-
</span>
|
|
587
|
-
<p>{conv.messages[0]?.text || "Empty conversation"}</p>
|
|
588
|
-
<small>{conv.messages.length} messages</small>
|
|
589
|
-
</div>
|
|
590
|
-
<button onClick={() => handleDelete(conv.conversationKey)}>Delete</button>
|
|
591
|
-
</li>
|
|
592
|
-
))}
|
|
593
|
-
</ul>
|
|
594
|
-
)}
|
|
595
|
-
</div>
|
|
596
|
-
);
|
|
597
|
-
}
|
|
598
|
-
```
|
|
599
|
-
|
|
600
|
-
### Backend Setup Required
|
|
601
|
-
|
|
602
|
-
For conversation management to work, the backend must:
|
|
603
|
-
|
|
604
|
-
1. **Enable Repository persistence:**
|
|
605
|
-
```csharp
|
|
606
|
-
builder.Services.AddPlayFramework("default", pb => pb
|
|
607
|
-
.UseRepository());
|
|
608
|
-
```
|
|
609
|
-
|
|
610
|
-
2. **Enable conversation endpoints:**
|
|
611
|
-
```csharp
|
|
612
|
-
app.MapPlayFramework("default", settings =>
|
|
613
|
-
{
|
|
614
|
-
settings.EnableConversationEndpoints = true;
|
|
615
|
-
});
|
|
616
|
-
```
|
|
617
|
-
|
|
618
|
-
See [Backend README](../../../README.md) for full setup guide.
|
|
619
|
-
|
|
620
|
-
---
|
|
621
|
-
|
|
622
|
-
## 🔄 Combining Stored Conversations with Live Streaming
|
|
623
|
-
|
|
624
|
-
This section shows how to **load historic messages** from `StoredConversation` and **continue the conversation** with live SSE streaming.
|
|
625
|
-
|
|
626
|
-
### Understanding the Two Models
|
|
627
|
-
|
|
628
|
-
PlayFramework uses **two different models** for different purposes:
|
|
629
|
-
|
|
630
|
-
| Model | Purpose | When | Format | Content |
|
|
631
|
-
|-------|---------|------|--------|---------|
|
|
632
|
-
| **`AiSceneResponse`** | Real-time execution tracking | During `executeStepByStep()` / `executeTokenStreaming()` | SSE (Server-Sent Events) | Status updates, streaming chunks, scene metadata |
|
|
633
|
-
| **`StoredConversation`** | Persistent conversation history | When loading from repository via REST API | JSON | Complete messages, user metadata, execution state |
|
|
634
|
-
|
|
635
|
-
**Why two models?**
|
|
636
|
-
- `AiSceneResponse` contains **temporary execution metadata** (status, sceneName, functionName) needed for real-time UI updates
|
|
637
|
-
- `StoredConversation` contains **only essential data** (messages, userId, timestamp) for efficient storage and querying
|
|
638
|
-
|
|
639
|
-
### Complete Example: Chat with History
|
|
640
|
-
|
|
641
|
-
```tsx
|
|
642
|
-
import React, { useState, useEffect } from 'react';
|
|
643
|
-
import { usePlayFramework, StoredConversation, AiSceneResponse } from '@rystem/playframework-client';
|
|
644
|
-
|
|
645
|
-
interface ChatMessage {
|
|
646
|
-
role: 'user' | 'assistant';
|
|
647
|
-
text: string;
|
|
648
|
-
isStreaming?: boolean; // Distinguishes streaming vs historic messages
|
|
649
|
-
status?: string; // For showing execution status
|
|
650
|
-
}
|
|
651
|
-
|
|
652
|
-
function ChatWithHistory() {
|
|
653
|
-
const client = usePlayFramework('default');
|
|
654
|
-
|
|
655
|
-
// State
|
|
656
|
-
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
|
657
|
-
const [input, setInput] = useState('');
|
|
658
|
-
const [conversationKey, setConversationKey] = useState<string | null>(null);
|
|
659
|
-
const [loading, setLoading] = useState(false);
|
|
660
|
-
|
|
661
|
-
// 📥 LOAD: Load historic conversation from repository
|
|
662
|
-
const loadConversation = async (key: string) => {
|
|
663
|
-
try {
|
|
664
|
-
// Fetch from REST API → StoredConversation
|
|
665
|
-
const stored = await client.getConversation(key);
|
|
666
|
-
|
|
667
|
-
if (!stored) {
|
|
668
|
-
alert('Conversation not found or unauthorized');
|
|
669
|
-
return;
|
|
670
|
-
}
|
|
671
|
-
|
|
672
|
-
// Convert StoredMessage[] → ChatMessage[]
|
|
673
|
-
const historicMessages: ChatMessage[] = stored.messages.map(msg => ({
|
|
674
|
-
role: msg.role as 'user' | 'assistant',
|
|
675
|
-
text: msg.text || '',
|
|
676
|
-
isStreaming: false // Historic messages are complete
|
|
677
|
-
}));
|
|
678
|
-
|
|
679
|
-
setMessages(historicMessages);
|
|
680
|
-
setConversationKey(stored.conversationKey);
|
|
681
|
-
|
|
682
|
-
console.log(`✅ Loaded ${stored.messages.length} messages from conversation ${key}`);
|
|
683
|
-
} catch (error) {
|
|
684
|
-
console.error('Failed to load conversation:', error);
|
|
685
|
-
alert(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
686
|
-
}
|
|
687
|
-
};
|
|
688
|
-
|
|
689
|
-
// 📤 SEND: Send message and stream response
|
|
690
|
-
const sendMessage = async () => {
|
|
691
|
-
if (!input.trim() || loading) return;
|
|
692
|
-
|
|
693
|
-
const userMessage = input;
|
|
694
|
-
setInput('');
|
|
695
|
-
setLoading(true);
|
|
696
|
-
|
|
697
|
-
// Add user message to UI
|
|
698
|
-
const userMsg: ChatMessage = { role: 'user', text: userMessage };
|
|
699
|
-
setMessages(prev => [...prev, userMsg]);
|
|
700
|
-
|
|
701
|
-
// Add placeholder for assistant response
|
|
702
|
-
const assistantMsg: ChatMessage = {
|
|
703
|
-
role: 'assistant',
|
|
704
|
-
text: '',
|
|
705
|
-
isStreaming: true, // Flag: currently streaming
|
|
706
|
-
status: 'initializing'
|
|
707
|
-
};
|
|
708
|
-
setMessages(prev => [...prev, assistantMsg]);
|
|
709
|
-
|
|
710
|
-
try {
|
|
711
|
-
// 🔄 Stream from PlayFramework → AiSceneResponse events
|
|
712
|
-
for await (const step of client.executeStepByStep({
|
|
713
|
-
message: userMessage,
|
|
714
|
-
settings: {
|
|
715
|
-
conversationKey: conversationKey || undefined, // Resume existing or start new
|
|
716
|
-
enableStreaming: true
|
|
717
|
-
}
|
|
718
|
-
})) {
|
|
719
|
-
// Update conversationKey from first response
|
|
720
|
-
if (step.conversationKey && !conversationKey) {
|
|
721
|
-
setConversationKey(step.conversationKey);
|
|
722
|
-
}
|
|
723
|
-
|
|
724
|
-
// Update message with streaming chunks
|
|
725
|
-
if (step.streamingChunk) {
|
|
726
|
-
setMessages(prev => {
|
|
727
|
-
const updated = [...prev];
|
|
728
|
-
const last = updated[updated.length - 1];
|
|
729
|
-
last.text += step.streamingChunk;
|
|
730
|
-
last.status = step.status;
|
|
731
|
-
return updated;
|
|
732
|
-
});
|
|
733
|
-
}
|
|
734
|
-
|
|
735
|
-
// Update status (planning, executingScene, etc.)
|
|
736
|
-
else if (step.status) {
|
|
737
|
-
setMessages(prev => {
|
|
738
|
-
const updated = [...prev];
|
|
739
|
-
const last = updated[updated.length - 1];
|
|
740
|
-
last.status = step.status;
|
|
741
|
-
return updated;
|
|
742
|
-
});
|
|
743
|
-
}
|
|
744
|
-
}
|
|
745
|
-
|
|
746
|
-
// Mark streaming as complete
|
|
747
|
-
setMessages(prev => {
|
|
748
|
-
const updated = [...prev];
|
|
749
|
-
const last = updated[updated.length - 1];
|
|
750
|
-
last.isStreaming = false;
|
|
751
|
-
delete last.status;
|
|
752
|
-
return updated;
|
|
753
|
-
});
|
|
754
|
-
|
|
755
|
-
} catch (error) {
|
|
756
|
-
console.error('Streaming error:', error);
|
|
757
|
-
setMessages(prev => {
|
|
758
|
-
const updated = [...prev];
|
|
759
|
-
updated[updated.length - 1] = {
|
|
760
|
-
role: 'assistant',
|
|
761
|
-
text: `Error: ${error instanceof Error ? error.message : 'Unknown error'}`,
|
|
762
|
-
isStreaming: false,
|
|
763
|
-
status: 'error'
|
|
764
|
-
};
|
|
765
|
-
return updated;
|
|
766
|
-
});
|
|
767
|
-
} finally {
|
|
768
|
-
setLoading(false);
|
|
769
|
-
}
|
|
770
|
-
};
|
|
771
|
-
|
|
772
|
-
// 🗑️ CLEAR: Start new conversation
|
|
773
|
-
const clearConversation = () => {
|
|
774
|
-
setMessages([]);
|
|
775
|
-
setConversationKey(null);
|
|
776
|
-
};
|
|
777
|
-
|
|
778
|
-
return (
|
|
779
|
-
<div style={{ maxWidth: '900px', margin: '0 auto', padding: '20px', fontFamily: 'sans-serif' }}>
|
|
780
|
-
<h1>💬 PlayFramework Chat</h1>
|
|
781
|
-
|
|
782
|
-
{/* Conversation Info */}
|
|
783
|
-
<div style={{
|
|
784
|
-
padding: '10px',
|
|
785
|
-
marginBottom: '10px',
|
|
786
|
-
backgroundColor: '#f0f0f0',
|
|
787
|
-
borderRadius: '8px',
|
|
788
|
-
display: 'flex',
|
|
789
|
-
justifyContent: 'space-between',
|
|
790
|
-
alignItems: 'center'
|
|
791
|
-
}}>
|
|
792
|
-
<div>
|
|
793
|
-
{conversationKey ? (
|
|
794
|
-
<>
|
|
795
|
-
<strong>Conversation:</strong> {conversationKey.substring(0, 8)}...
|
|
796
|
-
<span style={{ marginLeft: '10px', color: '#666' }}>
|
|
797
|
-
({messages.length} messages)
|
|
798
|
-
</span>
|
|
799
|
-
</>
|
|
800
|
-
) : (
|
|
801
|
-
<span style={{ color: '#999' }}>New conversation</span>
|
|
802
|
-
)}
|
|
803
|
-
</div>
|
|
804
|
-
<button
|
|
805
|
-
onClick={clearConversation}
|
|
806
|
-
style={{
|
|
807
|
-
padding: '5px 15px',
|
|
808
|
-
borderRadius: '6px',
|
|
809
|
-
border: '1px solid #ccc',
|
|
810
|
-
backgroundColor: '#fff',
|
|
811
|
-
cursor: 'pointer'
|
|
812
|
-
}}
|
|
813
|
-
>
|
|
814
|
-
Clear
|
|
815
|
-
</button>
|
|
816
|
-
</div>
|
|
817
|
-
|
|
818
|
-
{/* Messages */}
|
|
819
|
-
<div style={{
|
|
820
|
-
height: '500px',
|
|
821
|
-
overflowY: 'auto',
|
|
822
|
-
border: '1px solid #ddd',
|
|
823
|
-
borderRadius: '8px',
|
|
824
|
-
padding: '15px',
|
|
825
|
-
marginBottom: '15px',
|
|
826
|
-
backgroundColor: '#fafafa'
|
|
827
|
-
}}>
|
|
828
|
-
{messages.length === 0 ? (
|
|
829
|
-
<div style={{ textAlign: 'center', color: '#999', marginTop: '50px' }}>
|
|
830
|
-
<p>No messages yet. Start a conversation or load an existing one.</p>
|
|
831
|
-
<button
|
|
832
|
-
onClick={() => loadConversation('some-conversation-key')}
|
|
833
|
-
style={{
|
|
834
|
-
padding: '8px 16px',
|
|
835
|
-
borderRadius: '6px',
|
|
836
|
-
border: '1px solid #61dafb',
|
|
837
|
-
backgroundColor: '#61dafb',
|
|
838
|
-
color: '#fff',
|
|
839
|
-
cursor: 'pointer',
|
|
840
|
-
marginTop: '10px'
|
|
841
|
-
}}
|
|
842
|
-
>
|
|
843
|
-
Load Example Conversation
|
|
844
|
-
</button>
|
|
845
|
-
</div>
|
|
846
|
-
) : (
|
|
847
|
-
messages.map((msg, i) => (
|
|
848
|
-
<div
|
|
849
|
-
key={i}
|
|
850
|
-
style={{
|
|
851
|
-
padding: '12px',
|
|
852
|
-
margin: '8px 0',
|
|
853
|
-
borderRadius: '12px',
|
|
854
|
-
backgroundColor: msg.role === 'user' ? '#e3f2fd' : '#fff',
|
|
855
|
-
border: msg.role === 'assistant' ? '1px solid #e0e0e0' : 'none',
|
|
856
|
-
maxWidth: '85%',
|
|
857
|
-
marginLeft: msg.role === 'user' ? 'auto' : '0',
|
|
858
|
-
marginRight: msg.role === 'user' ? '0' : 'auto',
|
|
859
|
-
}}
|
|
860
|
-
>
|
|
861
|
-
<div style={{
|
|
862
|
-
display: 'flex',
|
|
863
|
-
justifyContent: 'space-between',
|
|
864
|
-
marginBottom: '6px',
|
|
865
|
-
fontSize: '12px',
|
|
866
|
-
color: '#666'
|
|
867
|
-
}}>
|
|
868
|
-
<strong style={{ color: msg.role === 'user' ? '#1976d2' : '#388e3c' }}>
|
|
869
|
-
{msg.role === 'user' ? '👤 You' : '🤖 AI'}
|
|
870
|
-
</strong>
|
|
871
|
-
|
|
872
|
-
{/* Show streaming indicator or status */}
|
|
873
|
-
{msg.isStreaming && (
|
|
874
|
-
<span style={{
|
|
875
|
-
color: '#ff6b6b',
|
|
876
|
-
fontStyle: 'italic',
|
|
877
|
-
fontSize: '11px'
|
|
878
|
-
}}>
|
|
879
|
-
{msg.status || 'streaming'} ●
|
|
880
|
-
</span>
|
|
881
|
-
)}
|
|
882
|
-
</div>
|
|
883
|
-
|
|
884
|
-
<div style={{
|
|
885
|
-
whiteSpace: 'pre-wrap',
|
|
886
|
-
wordBreak: 'break-word',
|
|
887
|
-
lineHeight: '1.5'
|
|
888
|
-
}}>
|
|
889
|
-
{msg.text || '...'}
|
|
890
|
-
</div>
|
|
891
|
-
</div>
|
|
892
|
-
))
|
|
893
|
-
)}
|
|
894
|
-
</div>
|
|
895
|
-
|
|
896
|
-
{/* Input */}
|
|
897
|
-
<div style={{ display: 'flex', gap: '10px' }}>
|
|
898
|
-
<input
|
|
899
|
-
type="text"
|
|
900
|
-
value={input}
|
|
901
|
-
onChange={e => setInput(e.target.value)}
|
|
902
|
-
onKeyDown={e => e.key === 'Enter' && !loading && sendMessage()}
|
|
903
|
-
placeholder={loading ? 'AI is responding...' : 'Type your message...'}
|
|
904
|
-
disabled={loading}
|
|
905
|
-
style={{
|
|
906
|
-
flex: 1,
|
|
907
|
-
padding: '12px 16px',
|
|
908
|
-
fontSize: '15px',
|
|
909
|
-
borderRadius: '8px',
|
|
910
|
-
border: '1px solid #ddd',
|
|
911
|
-
outline: 'none'
|
|
912
|
-
}}
|
|
913
|
-
/>
|
|
914
|
-
<button
|
|
915
|
-
onClick={sendMessage}
|
|
916
|
-
disabled={loading || !input.trim()}
|
|
917
|
-
style={{
|
|
918
|
-
padding: '12px 24px',
|
|
919
|
-
fontSize: '15px',
|
|
920
|
-
borderRadius: '8px',
|
|
921
|
-
border: 'none',
|
|
922
|
-
backgroundColor: loading ? '#ccc' : '#61dafb',
|
|
923
|
-
color: loading ? '#666' : '#fff',
|
|
924
|
-
cursor: loading ? 'not-allowed' : 'pointer',
|
|
925
|
-
fontWeight: 600
|
|
926
|
-
}}
|
|
927
|
-
>
|
|
928
|
-
{loading ? 'Sending...' : 'Send'}
|
|
929
|
-
</button>
|
|
930
|
-
</div>
|
|
931
|
-
|
|
932
|
-
{/* Helper Text */}
|
|
933
|
-
<div style={{
|
|
934
|
-
marginTop: '15px',
|
|
935
|
-
fontSize: '13px',
|
|
936
|
-
color: '#666',
|
|
937
|
-
textAlign: 'center'
|
|
938
|
-
}}>
|
|
939
|
-
💡 Messages are automatically saved to the repository when backend persistence is enabled.
|
|
940
|
-
<br />
|
|
941
|
-
Use the conversation list to browse and load previous conversations.
|
|
942
|
-
</div>
|
|
943
|
-
</div>
|
|
944
|
-
);
|
|
945
|
-
}
|
|
946
|
-
|
|
947
|
-
export default ChatWithHistory;
|
|
948
|
-
```
|
|
949
|
-
|
|
950
|
-
### Key Features Demonstrated
|
|
951
|
-
|
|
952
|
-
✅ **Load Historic Messages**: Converts `StoredMessage[]` → `ChatMessage[]`
|
|
953
|
-
✅ **Continue Conversation**: Uses same `conversationKey` to resume context
|
|
954
|
-
✅ **Real-Time Streaming**: Updates UI with `AiSceneResponse` chunks
|
|
955
|
-
✅ **Status Indicators**: Shows execution status during streaming
|
|
956
|
-
✅ **Seamless UX**: Historic + streaming messages in same UI
|
|
957
|
-
|
|
958
|
-
### Flow Diagram
|
|
959
|
-
|
|
960
|
-
```
|
|
961
|
-
1. User clicks "Load Conversation"
|
|
962
|
-
↓
|
|
963
|
-
2. GET /api/ai/default/conversations/{key}
|
|
964
|
-
↓
|
|
965
|
-
3. Receives StoredConversation (REST JSON)
|
|
966
|
-
├─ messages: StoredMessage[]
|
|
967
|
-
├─ conversationKey: "abc-123"
|
|
968
|
-
└─ timestamp, userId, isPublic
|
|
969
|
-
↓
|
|
970
|
-
4. Convert to ChatMessage[] and display
|
|
971
|
-
↓
|
|
972
|
-
5. User types new message
|
|
973
|
-
↓
|
|
974
|
-
6. POST /api/ai/default (SSE streaming)
|
|
975
|
-
settings: { conversationKey: "abc-123" }
|
|
976
|
-
↓
|
|
977
|
-
7. Receives AiSceneResponse events (SSE)
|
|
978
|
-
├─ status: "planning" → "executingScene" → "streaming"
|
|
979
|
-
├─ streamingChunk: "Hello", " world", "!"
|
|
980
|
-
└─ conversationKey: "abc-123" (same as before)
|
|
981
|
-
↓
|
|
982
|
-
8. Backend loads context from cache/repository
|
|
983
|
-
↓
|
|
984
|
-
9. LLM generates response using historic context
|
|
985
|
-
↓
|
|
986
|
-
10. Response streamed to UI in real-time
|
|
987
|
-
↓
|
|
988
|
-
11. Backend saves new messages to repository
|
|
989
|
-
↓
|
|
990
|
-
12. Conversation continues seamlessly
|
|
991
|
-
```
|
|
992
|
-
|
|
993
|
-
### Best Practices
|
|
994
|
-
|
|
995
|
-
1. **Separate concerns**: Use `StoredMessage` for storage, `AiSceneResponse` for streaming
|
|
996
|
-
2. **Flag streaming state**: Add `isStreaming` flag to distinguish live vs historic
|
|
997
|
-
3. **Show status**: Display execution status (`planning`, `executingScene`) during streaming
|
|
998
|
-
4. **Handle errors**: Wrap streaming in try-catch and show error messages
|
|
999
|
-
5. **Auto-save**: Backend automatically persists conversations when repository is enabled
|
|
1000
|
-
|
|
1001
|
-
---
|
|
1002
|
-
|
|
1003
|
-
## 📸 Multi-Modal Content (Images, Audio, Video, PDFs)
|
|
1004
|
-
|
|
1005
|
-
PlayFramework supports **base64-encoded media content** in messages. The client provides helper utilities to convert Base64 data to Blob URLs for browser display.
|
|
1006
|
-
|
|
1007
|
-
### ContentUrlConverter Helper
|
|
1008
|
-
|
|
1009
|
-
Converts `AIContent` (base64 data) to Blob URLs that can be used in HTML `<img>`, `<audio>`, `<video>`, and `<iframe>` elements.
|
|
1010
|
-
|
|
1011
|
-
```typescript
|
|
1012
|
-
import { ContentUrlConverter, AIContent } from "@rystem/playframework-client";
|
|
1013
|
-
|
|
1014
|
-
const content: AIContent = {
|
|
1015
|
-
type: "data",
|
|
1016
|
-
data: "iVBORw0KGgoAAAANSUhEUgAA...", // Base64 JPEG
|
|
1017
|
-
mediaType: "image/jpeg"
|
|
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"
|
|
1018
212
|
};
|
|
1019
|
-
|
|
1020
|
-
// Convert to Blob URL
|
|
1021
|
-
const url = ContentUrlConverter.toBlobUrl(content);
|
|
1022
|
-
|
|
1023
|
-
// Use in <img> tag
|
|
1024
|
-
<img src={url} alt="Image" />
|
|
1025
|
-
|
|
1026
|
-
// IMPORTANT: Cleanup when done (frees memory!)
|
|
1027
|
-
ContentUrlConverter.revokeUrl(url);
|
|
1028
|
-
```
|
|
1029
|
-
|
|
1030
|
-
### API Methods
|
|
1031
|
-
|
|
1032
|
-
#### `toBlob(content: AIContent): Blob | null`
|
|
1033
|
-
Decodes Base64 string to Blob object.
|
|
1034
|
-
|
|
1035
|
-
```typescript
|
|
1036
|
-
const blob = ContentUrlConverter.toBlob(content);
|
|
1037
|
-
```
|
|
1038
|
-
|
|
1039
|
-
#### `toBlobUrl(content: AIContent, cacheKey?: string): string | null`
|
|
1040
|
-
Creates `blob:` URL for browser display. Supports optional caching.
|
|
1041
|
-
|
|
1042
|
-
```typescript
|
|
1043
|
-
const url = ContentUrlConverter.toBlobUrl(content, 'image-123');
|
|
1044
|
-
```
|
|
1045
|
-
|
|
1046
|
-
#### `revokeUrl(url: string, cacheKey?: string): void`
|
|
1047
|
-
Revokes Blob URL to free memory. **Always call this when done!**
|
|
1048
|
-
|
|
1049
|
-
```typescript
|
|
1050
|
-
ContentUrlConverter.revokeUrl(url, 'image-123');
|
|
1051
213
|
```
|
|
1052
214
|
|
|
1053
|
-
|
|
1054
|
-
Revokes all cached URLs at once.
|
|
215
|
+
The `settings` object mirrors the server-side `SceneRequestSettings`, including:
|
|
1055
216
|
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
217
|
+
- `executionMode`
|
|
218
|
+
- `sceneName`
|
|
219
|
+
- `conversationKey`
|
|
220
|
+
- `clientInteractionResults`
|
|
221
|
+
- `enableStreaming`
|
|
222
|
+
- `enableSummarization`
|
|
223
|
+
- `enableDirector`
|
|
224
|
+
- `maxRecursionDepth`
|
|
1059
225
|
|
|
1060
|
-
|
|
1061
|
-
Triggers browser download.
|
|
226
|
+
The request can also include `contents` for multi-modal inputs.
|
|
1062
227
|
|
|
1063
|
-
|
|
1064
|
-
ContentUrlConverter.downloadAsFile(content, 'image.jpg');
|
|
1065
|
-
```
|
|
228
|
+
## Example: send files and multi-modal contents
|
|
1066
229
|
|
|
1067
|
-
|
|
1068
|
-
Maps MIME type to file extension.
|
|
230
|
+
The request model accepts `ContentItem[]`, while `AIContentConverter` helps you build the base64 payloads in the browser.
|
|
1069
231
|
|
|
1070
232
|
```typescript
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
### React Example: Image Viewer
|
|
1077
|
-
|
|
1078
|
-
```tsx
|
|
1079
|
-
import { useState, useEffect } from 'react';
|
|
1080
|
-
import { ContentUrlConverter, AIContent } from "@rystem/playframework-client";
|
|
1081
|
-
|
|
1082
|
-
interface ImageViewerProps {
|
|
1083
|
-
content: AIContent;
|
|
1084
|
-
}
|
|
1085
|
-
|
|
1086
|
-
function ImageViewer({ content }: ImageViewerProps) {
|
|
1087
|
-
const [url, setUrl] = useState<string | null>(null);
|
|
1088
|
-
|
|
1089
|
-
useEffect(() => {
|
|
1090
|
-
// Create Blob URL when component mounts
|
|
1091
|
-
const blobUrl = ContentUrlConverter.toBlobUrl(content, `image-${Date.now()}`);
|
|
1092
|
-
setUrl(blobUrl);
|
|
1093
|
-
|
|
1094
|
-
// Cleanup when component unmounts (important for memory!)
|
|
1095
|
-
return () => {
|
|
1096
|
-
if (blobUrl) {
|
|
1097
|
-
ContentUrlConverter.revokeUrl(blobUrl);
|
|
1098
|
-
}
|
|
1099
|
-
};
|
|
1100
|
-
}, [content]);
|
|
1101
|
-
|
|
1102
|
-
if (!url) return <div>Loading image...</div>;
|
|
1103
|
-
|
|
1104
|
-
return (
|
|
1105
|
-
<div>
|
|
1106
|
-
<img src={url} alt="Image" style={{ maxWidth: '100%' }} />
|
|
1107
|
-
<button onClick={() => ContentUrlConverter.downloadAsFile(content, 'image.jpg')}>
|
|
1108
|
-
Download
|
|
1109
|
-
</button>
|
|
1110
|
-
</div>
|
|
1111
|
-
);
|
|
1112
|
-
}
|
|
1113
|
-
```
|
|
1114
|
-
|
|
1115
|
-
---
|
|
1116
|
-
|
|
1117
|
-
### React Example: Auto-Detection Content Viewer
|
|
1118
|
-
|
|
1119
|
-
```tsx
|
|
1120
|
-
import { ContentUrlConverter, AIContent } from "@rystem/playframework-client";
|
|
1121
|
-
|
|
1122
|
-
function ContentViewer({ content }: { content: AIContent }) {
|
|
1123
|
-
const mediaType = content.mediaType?.toLowerCase() || '';
|
|
1124
|
-
const [url, setUrl] = useState<string | null>(null);
|
|
1125
|
-
|
|
1126
|
-
useEffect(() => {
|
|
1127
|
-
const blobUrl = ContentUrlConverter.toBlobUrl(content);
|
|
1128
|
-
setUrl(blobUrl);
|
|
1129
|
-
|
|
1130
|
-
return () => {
|
|
1131
|
-
if (blobUrl) ContentUrlConverter.revokeUrl(blobUrl);
|
|
1132
|
-
};
|
|
1133
|
-
}, [content]);
|
|
233
|
+
import {
|
|
234
|
+
AIContentConverter,
|
|
235
|
+
type ContentItem,
|
|
236
|
+
type PlayFrameworkRequest
|
|
237
|
+
} from "rystem.playframework.client";
|
|
1134
238
|
|
|
1135
|
-
|
|
239
|
+
async function buildRequest(file: File): Promise<PlayFrameworkRequest> {
|
|
240
|
+
const converted = await AIContentConverter.fromFile(file);
|
|
1136
241
|
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
if (mediaType.startsWith('audio/')) {
|
|
1144
|
-
return (
|
|
1145
|
-
<audio controls style={{ width: '100%' }}>
|
|
1146
|
-
<source src={url} type={mediaType} />
|
|
1147
|
-
</audio>
|
|
1148
|
-
);
|
|
1149
|
-
}
|
|
1150
|
-
|
|
1151
|
-
// Video
|
|
1152
|
-
if (mediaType.startsWith('video/')) {
|
|
1153
|
-
return (
|
|
1154
|
-
<video controls style={{ maxWidth: '100%' }}>
|
|
1155
|
-
<source src={url} type={mediaType} />
|
|
1156
|
-
</video>
|
|
1157
|
-
);
|
|
242
|
+
const contents: ContentItem[] = [
|
|
243
|
+
{
|
|
244
|
+
type: "file",
|
|
245
|
+
data: converted.data,
|
|
246
|
+
mediaType: converted.mediaType,
|
|
247
|
+
name: file.name
|
|
1158
248
|
}
|
|
249
|
+
];
|
|
1159
250
|
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
title="PDF Document"
|
|
1166
|
-
style={{ width: '100%', height: '600px', border: '1px solid #ddd' }}
|
|
1167
|
-
/>
|
|
1168
|
-
);
|
|
251
|
+
return {
|
|
252
|
+
message: "Summarize the attached document and extract the risks.",
|
|
253
|
+
contents,
|
|
254
|
+
settings: {
|
|
255
|
+
executionMode: "Planning"
|
|
1169
256
|
}
|
|
1170
|
-
|
|
1171
|
-
// Fallback for unknown types
|
|
1172
|
-
return (
|
|
1173
|
-
<div>
|
|
1174
|
-
<p>📎 Attachment: {content.mediaType || 'unknown type'}</p>
|
|
1175
|
-
<button onClick={() => ContentUrlConverter.downloadAsFile(content)}>
|
|
1176
|
-
Download File
|
|
1177
|
-
</button>
|
|
1178
|
-
</div>
|
|
1179
|
-
);
|
|
257
|
+
};
|
|
1180
258
|
}
|
|
1181
|
-
```
|
|
1182
|
-
|
|
1183
|
-
---
|
|
1184
|
-
|
|
1185
|
-
### includeContents Parameter
|
|
1186
259
|
|
|
1187
|
-
|
|
260
|
+
const request = await buildRequest(selectedFile);
|
|
1188
261
|
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
includeContents: false, // Default: false
|
|
1193
|
-
take: 50
|
|
1194
|
-
});
|
|
1195
|
-
|
|
1196
|
-
// ✅ Load single conversation WITH media (for display)
|
|
1197
|
-
const conv = await client.getConversation(key, true); // includeContents=true
|
|
262
|
+
for await (const step of client.executeStepByStep(request)) {
|
|
263
|
+
console.log(step.status, step.message);
|
|
264
|
+
}
|
|
1198
265
|
```
|
|
1199
266
|
|
|
1200
|
-
|
|
267
|
+
Browser helpers available in this package include:
|
|
1201
268
|
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
269
|
+
- `AIContentConverter.fromFile(...)`
|
|
270
|
+
- `AIContentConverter.fromMultipleFiles(...)`
|
|
271
|
+
- `AIContentConverter.fromCamera(...)`
|
|
272
|
+
- `AIContentConverter.fromGeolocation(...)`
|
|
273
|
+
- `AIContentConverter.fromMicrophone(...)`
|
|
274
|
+
- `AIContentConverter.fromText(...)`
|
|
1207
275
|
|
|
1208
|
-
|
|
276
|
+
## Example: render or download returned contents
|
|
1209
277
|
|
|
1210
|
-
|
|
278
|
+
`AiSceneResponse.contents` can include generated images, audio, or files. `ContentUrlConverter` is the browser-side helper for previewing or downloading them.
|
|
1211
279
|
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
```tsx
|
|
1215
|
-
import { useState, useEffect } from 'react';
|
|
1216
|
-
import { usePlayFramework, StoredMessage, AIContent, ContentUrlConverter } from "@rystem/playframework-client";
|
|
1217
|
-
|
|
1218
|
-
function ChatWithMedia() {
|
|
1219
|
-
const client = usePlayFramework('default');
|
|
1220
|
-
const [messages, setMessages] = useState<StoredMessage[]>([]);
|
|
1221
|
-
const [conversationKey, setConversationKey] = useState<string | null>(null);
|
|
280
|
+
```typescript
|
|
281
|
+
import { ContentUrlConverter } from "rystem.playframework.client";
|
|
1222
282
|
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
283
|
+
for await (const step of client.executeStepByStep({
|
|
284
|
+
message: "Generate an image of a blue robot"
|
|
285
|
+
})) {
|
|
286
|
+
const media = step.contents?.[0];
|
|
287
|
+
if (!media) continue;
|
|
1226
288
|
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
};
|
|
289
|
+
const url = ContentUrlConverter.toBlobUrl(media, `response-${Date.now()}`);
|
|
290
|
+
if (url) {
|
|
291
|
+
console.log("preview", url);
|
|
292
|
+
}
|
|
1232
293
|
|
|
1233
|
-
|
|
1234
|
-
<div>
|
|
1235
|
-
<h1>Chat with Media Support</h1>
|
|
1236
|
-
|
|
1237
|
-
{messages.map((msg, i) => (
|
|
1238
|
-
<div key={i} style={{
|
|
1239
|
-
backgroundColor: msg.role === 'user' ? '#e3f2fd' : '#fff',
|
|
1240
|
-
padding: '12px',
|
|
1241
|
-
margin: '8px 0',
|
|
1242
|
-
borderRadius: '8px'
|
|
1243
|
-
}}>
|
|
1244
|
-
<strong>{msg.role === 'user' ? '👤 You' : '🤖 AI'}</strong>
|
|
1245
|
-
<p>{msg.text}</p>
|
|
1246
|
-
|
|
1247
|
-
{/* Display attached content (images, PDFs, etc.) */}
|
|
1248
|
-
{msg.contents && msg.contents.length > 0 && (
|
|
1249
|
-
<div style={{ marginTop: '8px' }}>
|
|
1250
|
-
{msg.contents.map((content, idx) => (
|
|
1251
|
-
<ContentViewer key={idx} content={content} />
|
|
1252
|
-
))}
|
|
1253
|
-
</div>
|
|
1254
|
-
)}
|
|
1255
|
-
</div>
|
|
1256
|
-
))}
|
|
1257
|
-
|
|
1258
|
-
<button onClick={() => loadConversation('example-key')}>
|
|
1259
|
-
Load Example Conversation
|
|
1260
|
-
</button>
|
|
1261
|
-
</div>
|
|
1262
|
-
);
|
|
294
|
+
ContentUrlConverter.downloadAsFile(media, "playframework-output");
|
|
1263
295
|
}
|
|
1264
296
|
```
|
|
1265
297
|
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
### Memory Management Best Practices
|
|
1269
|
-
|
|
1270
|
-
1. **Always cleanup Blob URLs**: Use `useEffect` cleanup function in React
|
|
1271
|
-
2. **Use caching for repeated content**: Pass `cacheKey` parameter
|
|
1272
|
-
3. **Clear cache on unmount**: Call `ContentUrlConverter.clearCache()` when appropriate
|
|
1273
|
-
4. **Lazy load media**: Only convert to Blob URL when needed for display
|
|
1274
|
-
5. **Use includeContents wisely**: Exclude contents from list operations
|
|
1275
|
-
|
|
1276
|
-
**Example cleanup:**
|
|
1277
|
-
```tsx
|
|
1278
|
-
useEffect(() => {
|
|
1279
|
-
const url = ContentUrlConverter.toBlobUrl(content);
|
|
1280
|
-
setImageUrl(url);
|
|
1281
|
-
|
|
1282
|
-
// Cleanup when component unmounts
|
|
1283
|
-
return () => {
|
|
1284
|
-
if (url) ContentUrlConverter.revokeUrl(url);
|
|
1285
|
-
};
|
|
1286
|
-
}, [content]);
|
|
1287
|
-
|
|
1288
|
-
// Clear all on app unmount
|
|
1289
|
-
useEffect(() => {
|
|
1290
|
-
return () => ContentUrlConverter.clearCache();
|
|
1291
|
-
}, []);
|
|
1292
|
-
```
|
|
1293
|
-
|
|
1294
|
-
---
|
|
1295
|
-
|
|
1296
|
-
## 🚫 Cancellation
|
|
1297
|
-
|
|
1298
|
-
Use `AbortController` to **cancel ongoing requests**:
|
|
298
|
+
Remember to revoke blob URLs you keep around:
|
|
1299
299
|
|
|
1300
300
|
```typescript
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
// Start streaming
|
|
1304
|
-
const promise = (async () => {
|
|
1305
|
-
try {
|
|
1306
|
-
for await (const step of client.executeStepByStep(
|
|
1307
|
-
{ message: "Long task..." },
|
|
1308
|
-
controller.signal
|
|
1309
|
-
)) {
|
|
1310
|
-
console.log(step.message);
|
|
1311
|
-
}
|
|
1312
|
-
} catch (error) {
|
|
1313
|
-
if (error instanceof DOMException && error.name === "AbortError") {
|
|
1314
|
-
console.log("Request cancelled");
|
|
1315
|
-
}
|
|
1316
|
-
}
|
|
1317
|
-
})();
|
|
1318
|
-
|
|
1319
|
-
// Cancel after 5 seconds
|
|
1320
|
-
setTimeout(() => controller.abort(), 5000);
|
|
301
|
+
ContentUrlConverter.revokeUrl(url, cacheKey);
|
|
1321
302
|
```
|
|
1322
303
|
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
## 📊 Response Status Types
|
|
1326
|
-
|
|
1327
|
-
```typescript
|
|
1328
|
-
type AiResponseStatus =
|
|
1329
|
-
| "initializing" // Starting execution
|
|
1330
|
-
| "loadingCache" // Loading cached conversation context
|
|
1331
|
-
| "executingMainActors" // Running global system prompts
|
|
1332
|
-
| "planning" // Creating execution plan
|
|
1333
|
-
| "executingScene" // Running scene/actor
|
|
1334
|
-
| "functionRequest" // Calling server-side tool
|
|
1335
|
-
| "functionCompleted" // Tool call completed
|
|
1336
|
-
| "toolSkipped" // Tool was skipped
|
|
1337
|
-
| "streaming" // Streaming text chunks
|
|
1338
|
-
| "running" // General execution in progress
|
|
1339
|
-
| "summarizing" // Summarizing conversation
|
|
1340
|
-
| "directorDecision" // Director evaluating results
|
|
1341
|
-
| "generatingFinalResponse" // Generating final response
|
|
1342
|
-
| "savingCache" // Saving to cache
|
|
1343
|
-
| "savingMemory" // Saving conversation memory
|
|
1344
|
-
| "awaitingClient" // Waiting for client-side tool response
|
|
1345
|
-
| "commandClient" // Fire-and-forget command sent to client
|
|
1346
|
-
| "completed" // Success
|
|
1347
|
-
| "budgetExceeded" // Max cost exceeded
|
|
1348
|
-
| "error" // Failure
|
|
1349
|
-
| "unauthorized"; // Authorization failed
|
|
1350
|
-
```
|
|
304
|
+
## Example: client-side tools and commands
|
|
1351
305
|
|
|
1352
|
-
|
|
306
|
+
When the server emits `awaitingClient` or `commandClient`, the library can execute browser-side tools locally and resume automatically.
|
|
1353
307
|
|
|
1354
|
-
|
|
308
|
+
This is the same pattern used by the sample app in `src/AI/Rystem.PlayFramework.Client/src/App.tsx`.
|
|
1355
309
|
|
|
1356
310
|
```typescript
|
|
1357
|
-
import {
|
|
311
|
+
import {
|
|
312
|
+
AIContentConverter,
|
|
313
|
+
CommandResultHelper,
|
|
314
|
+
PlayFrameworkServices
|
|
315
|
+
} from "rystem.playframework.client";
|
|
1358
316
|
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
const settings = new PlayFrameworkSettings("default", "http://localhost:5158/api/ai");
|
|
1362
|
-
const client = new PlayFrameworkClient(settings);
|
|
1363
|
-
|
|
1364
|
-
const responses: string[] = [];
|
|
1365
|
-
|
|
1366
|
-
for await (const step of client.executeStepByStep({ message: "Test" })) {
|
|
1367
|
-
if (step.message) responses.push(step.message);
|
|
1368
|
-
}
|
|
317
|
+
const client = PlayFrameworkServices.resolve("default");
|
|
318
|
+
const registry = client.getClientRegistry();
|
|
1369
319
|
|
|
1370
|
-
|
|
1371
|
-
|
|
320
|
+
registry.register("getCurrentLocation", async () => {
|
|
321
|
+
const content = await AIContentConverter.fromGeolocation({ timeout: 10_000 });
|
|
322
|
+
return [content];
|
|
1372
323
|
});
|
|
1373
|
-
```
|
|
1374
|
-
|
|
1375
|
-
---
|
|
1376
|
-
|
|
1377
|
-
## 📚 API Reference
|
|
1378
|
-
|
|
1379
|
-
### `PlayFrameworkServices`
|
|
1380
|
-
|
|
1381
|
-
Static service locator for managing named `PlayFrameworkClient` instances.
|
|
1382
324
|
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
| `getClient` | `(name: string): PlayFrameworkClient` | Get client by exact name (throws if not found) |
|
|
1388
|
-
| `getDefaultClient` | `(): PlayFrameworkClient` | Get the first registered client |
|
|
1389
|
-
| `getSettings` | `(name: string): PlayFrameworkSettings` | Get settings by name (throws if not found) |
|
|
1390
|
-
| `isConfigured` | `(name: string): boolean` | Check if a named client exists |
|
|
1391
|
-
| `remove` | `(name: string): void` | Remove a named client and its settings |
|
|
1392
|
-
| `clear` | `(): void` | Remove all clients and settings |
|
|
1393
|
-
|
|
1394
|
-
```typescript
|
|
1395
|
-
// Configure
|
|
1396
|
-
await PlayFrameworkServices.configure("chat", "http://localhost:5158/api/ai");
|
|
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
|
+
});
|
|
1397
329
|
|
|
1398
|
-
|
|
1399
|
-
|
|
330
|
+
registry.registerCommand("logUserAction", async (args?: { action?: string }) => {
|
|
331
|
+
console.log("action", args?.action);
|
|
332
|
+
return CommandResultHelper.ok();
|
|
333
|
+
}, { feedbackMode: "never" });
|
|
1400
334
|
|
|
1401
|
-
|
|
1402
|
-
if (
|
|
1403
|
-
|
|
1404
|
-
}
|
|
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" });
|
|
1405
342
|
```
|
|
1406
343
|
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
### `PlayFrameworkClient`
|
|
344
|
+
Supported command feedback modes are:
|
|
1410
345
|
|
|
1411
|
-
|
|
346
|
+
- `never`
|
|
347
|
+
- `onError`
|
|
348
|
+
- `always`
|
|
1412
349
|
|
|
1413
|
-
|
|
1414
|
-
|--------|-----------|-------------|
|
|
1415
|
-
| `executeStepByStep` | `(request: PlayFrameworkRequest, signal?: AbortSignal): AsyncIterableIterator<AiSceneResponse>` | Step-by-step streaming (one event per scene completion) |
|
|
1416
|
-
| `executeTokenStreaming` | `(request: PlayFrameworkRequest, signal?: AbortSignal): AsyncIterableIterator<AiSceneResponse>` | Token-level streaming (one event per text chunk) |
|
|
1417
|
-
| `getClientRegistry` | `(): ClientInteractionRegistry` | Get the client-side tool/command registry |
|
|
1418
|
-
| `getConversation` | `(conversationKey: string): Promise<StoredConversation \| null>` | Load a stored conversation by key |
|
|
1419
|
-
| `getConversations` | `(sortOrder?: ConversationSortOrder): Promise<StoredConversation[]>` | List conversations for the authenticated user |
|
|
1420
|
-
| `deleteConversation` | `(conversationKey: string): Promise<boolean>` | Delete a stored conversation |
|
|
350
|
+
Important behavior:
|
|
1421
351
|
|
|
1422
|
-
|
|
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
|
|
1423
356
|
|
|
1424
|
-
|
|
357
|
+
## Example: conversation management
|
|
1425
358
|
|
|
1426
|
-
|
|
359
|
+
`PlayFrameworkClient` exposes:
|
|
1427
360
|
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
| `execute` | `(request: ClientInteractionRequest): Promise<ClientInteractionResult>` | Execute a registered tool/command |
|
|
1433
|
-
| `has` | `(toolName: string): boolean` | Check if a tool/command is registered |
|
|
1434
|
-
| `isCommand` | `(toolName: string): boolean` | Check if the registration is a command |
|
|
1435
|
-
| `getCommandOptions` | `(toolName: string): CommandOptions \| undefined` | Get the command's feedback options |
|
|
1436
|
-
| `getToolNames` | `(): string[]` | List all registered tool/command names |
|
|
1437
|
-
| `unregister` | `(toolName: string): boolean` | Remove a registration |
|
|
1438
|
-
| `clear` | `(): void` | Remove all registrations |
|
|
361
|
+
- `listConversations(...)`
|
|
362
|
+
- `getConversation(...)`
|
|
363
|
+
- `deleteConversation(...)`
|
|
364
|
+
- `updateConversationVisibility(...)`
|
|
1439
365
|
|
|
1440
|
-
|
|
366
|
+
Example:
|
|
1441
367
|
|
|
1442
368
|
```typescript
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
369
|
+
import {
|
|
370
|
+
ConversationSortOrder,
|
|
371
|
+
PlayFrameworkServices
|
|
372
|
+
} from "rystem.playframework.client";
|
|
1446
373
|
|
|
1447
|
-
|
|
1448
|
-
feedbackMode?: CommandFeedbackMode;
|
|
1449
|
-
}
|
|
1450
|
-
```
|
|
374
|
+
const client = PlayFrameworkServices.resolve("default");
|
|
1451
375
|
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
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
|
|
1456
383
|
});
|
|
1457
384
|
|
|
1458
|
-
|
|
1459
|
-
registry.registerCommand("showNotification", async (args?: { text: string }) => {
|
|
1460
|
-
showToast(args?.text ?? "");
|
|
1461
|
-
return CommandResult.ok();
|
|
1462
|
-
}, { feedbackMode: 'onError' });
|
|
1463
|
-
```
|
|
1464
|
-
|
|
1465
|
-
---
|
|
1466
|
-
|
|
1467
|
-
### `AIContentConverter`
|
|
1468
|
-
|
|
1469
|
-
#### Static Methods
|
|
385
|
+
const selected = conversations[0];
|
|
1470
386
|
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
- `fromMultipleFiles(files: FileList): Promise<AIContent[]>` - Convert multiple files
|
|
1475
|
-
- `fromMicrophone(durationMs?: number, mimeType?: string): Promise<AIContent>` - Record audio
|
|
1476
|
-
- `fromText(text: string): AIContent` - Create text content
|
|
387
|
+
if (selected) {
|
|
388
|
+
const fullConversation = await client.getConversation(selected.conversationKey, true);
|
|
389
|
+
console.log(fullConversation?.messages.length);
|
|
1477
390
|
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
```tsx
|
|
1483
|
-
import { usePlayFramework } from "@rystem/playframework-client";
|
|
1484
|
-
|
|
1485
|
-
function MyComponent() {
|
|
1486
|
-
const client = usePlayFramework("default");
|
|
391
|
+
await client.updateConversationVisibility(selected.conversationKey, true);
|
|
392
|
+
await client.deleteConversation(selected.conversationKey);
|
|
393
|
+
}
|
|
394
|
+
```
|
|
1487
395
|
|
|
1488
|
-
|
|
1489
|
-
for await (const step of client.executeStepByStep({ message: "Hello" })) {
|
|
1490
|
-
console.log(step);
|
|
1491
|
-
}
|
|
1492
|
-
};
|
|
396
|
+
These methods call:
|
|
1493
397
|
|
|
1494
|
-
|
|
1495
|
-
}
|
|
398
|
+
```text
|
|
399
|
+
{baseUrl}/{factoryName}/conversations
|
|
1496
400
|
```
|
|
1497
401
|
|
|
1498
|
-
|
|
402
|
+
They only work when the server has both:
|
|
1499
403
|
|
|
1500
|
-
|
|
404
|
+
- `UseRepository()` and a matching `IRepository<StoredConversation, string>` registration
|
|
405
|
+
- `EnableConversationEndpoints = true` in `MapPlayFramework(...)`
|
|
1501
406
|
|
|
1502
|
-
|
|
407
|
+
## Example: server voice endpoint
|
|
1503
408
|
|
|
1504
|
-
|
|
409
|
+
`executeVoice(...)` targets the PlayFramework HTTP voice endpoint and streams `VoiceEvent` objects back.
|
|
1505
410
|
|
|
1506
411
|
```typescript
|
|
1507
|
-
|
|
412
|
+
import {
|
|
413
|
+
PlayFrameworkServices,
|
|
414
|
+
VoiceRecorder
|
|
415
|
+
} from "rystem.playframework.client";
|
|
1508
416
|
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
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
|
+
}
|
|
1522
436
|
}
|
|
1523
|
-
}
|
|
437
|
+
}
|
|
438
|
+
});
|
|
1524
439
|
|
|
1525
|
-
//
|
|
1526
|
-
|
|
1527
|
-
await audioPlayer.play(args?.soundId ?? "notification");
|
|
1528
|
-
return CommandResult.ok("Sound played");
|
|
1529
|
-
}, { feedbackMode: 'always' });
|
|
440
|
+
// In push-to-talk mode you stop manually.
|
|
441
|
+
recorder.stop();
|
|
1530
442
|
```
|
|
1531
443
|
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
```typescript
|
|
1535
|
-
interface CommandResult {
|
|
1536
|
-
success: boolean;
|
|
1537
|
-
message?: string;
|
|
1538
|
-
}
|
|
444
|
+
This calls:
|
|
1539
445
|
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
CommandResult.ok("Done"); // { success: true, message: "Done" }
|
|
1543
|
-
CommandResult.fail("Reason"); // { success: false, message: "Reason" }
|
|
446
|
+
```text
|
|
447
|
+
POST {baseUrl}/{factoryName}/voice
|
|
1544
448
|
```
|
|
1545
449
|
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
| Mode | Behavior |
|
|
1549
|
-
|------|----------|
|
|
1550
|
-
| `'never'` | Server ignores the command's result (default) |
|
|
1551
|
-
| `'onError'` | Server receives feedback only when `success: false` |
|
|
1552
|
-
| `'always'` | Server always receives the command's result |
|
|
450
|
+
It only works when the server enables the PlayFramework voice endpoint and has a matching `IVoiceAdapter`.
|
|
1553
451
|
|
|
1554
|
-
|
|
452
|
+
## Example: browser-native voice flow
|
|
1555
453
|
|
|
1556
|
-
|
|
454
|
+
`BrowserVoiceClient` is different from `executeVoice(...)`.
|
|
1557
455
|
|
|
1558
|
-
|
|
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.
|
|
1559
457
|
|
|
1560
458
|
```typescript
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
arguments?: Record<string, any>; // Arguments from AI
|
|
1566
|
-
argumentsSchema?: string; // JSON Schema string
|
|
1567
|
-
timeoutSeconds: number; // Max time to wait (tools only)
|
|
1568
|
-
isCommand?: boolean; // true = fire-and-forget command
|
|
1569
|
-
feedbackMode?: 'never' | 'onError' | 'always'; // Command feedback mode
|
|
1570
|
-
}
|
|
1571
|
-
```
|
|
459
|
+
import {
|
|
460
|
+
BrowserVoiceClient,
|
|
461
|
+
PlayFrameworkServices
|
|
462
|
+
} from "rystem.playframework.client";
|
|
1572
463
|
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
## 📋 `ClientInteractionResult` Model
|
|
1576
|
-
|
|
1577
|
-
The response your tool handler returns to the server:
|
|
1578
|
-
|
|
1579
|
-
```typescript
|
|
1580
|
-
interface AIContent {
|
|
1581
|
-
type: "text" | "data";
|
|
1582
|
-
text?: string; // For type "text"
|
|
1583
|
-
data?: string; // Base64-encoded (for type "data")
|
|
1584
|
-
mediaType?: string; // e.g., "image/jpeg", "audio/webm"
|
|
1585
|
-
}
|
|
1586
|
-
|
|
1587
|
-
interface ClientInteractionResult {
|
|
1588
|
-
interactionId: string; // Must match the request
|
|
1589
|
-
contents: AIContent[]; // Tool output
|
|
1590
|
-
error?: string; // Error message (if failed)
|
|
1591
|
-
executedAt: string; // ISO 8601 timestamp
|
|
1592
|
-
}
|
|
1593
|
-
```
|
|
1594
|
-
|
|
1595
|
-
---
|
|
1596
|
-
|
|
1597
|
-
## 📋 `ExecutionState` and `ExecutionPhase`
|
|
1598
|
-
|
|
1599
|
-
The `ExecutionState` object tracks the AI orchestration progress during execution:
|
|
464
|
+
const client = PlayFrameworkServices.resolve("default");
|
|
1600
465
|
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
currentSceneName?: string | null; // Currently running scene
|
|
466
|
+
if (BrowserVoiceClient.isSupported()) {
|
|
467
|
+
const voice = new BrowserVoiceClient(
|
|
468
|
+
client,
|
|
469
|
+
{ lang: "en-US" },
|
|
470
|
+
{ lang: "en-US" }
|
|
471
|
+
);
|
|
472
|
+
|
|
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
|
+
}
|
|
1626
490
|
}
|
|
1627
491
|
```
|
|
1628
492
|
|
|
1629
|
-
|
|
493
|
+
Useful notes:
|
|
1630
494
|
|
|
1631
|
-
|
|
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`
|
|
1632
499
|
|
|
1633
|
-
|
|
500
|
+
## `usePlayFramework`
|
|
1634
501
|
|
|
1635
|
-
|
|
1636
|
-
interface AiSceneResponse {
|
|
1637
|
-
status: AiResponseStatus;
|
|
1638
|
-
sceneName?: string;
|
|
1639
|
-
functionName?: string;
|
|
1640
|
-
functionArguments?: string;
|
|
1641
|
-
message?: string; // Final response text (step-by-step)
|
|
1642
|
-
streamingChunk?: string; // Partial text (token streaming)
|
|
1643
|
-
isStreamingComplete?: boolean;
|
|
1644
|
-
errorMessage?: string;
|
|
1645
|
-
inputTokens?: number;
|
|
1646
|
-
cachedInputTokens?: number;
|
|
1647
|
-
outputTokens?: number;
|
|
1648
|
-
totalTokens?: number;
|
|
1649
|
-
cost?: number; // Cost for this step
|
|
1650
|
-
totalCost?: number; // Accumulated total cost
|
|
1651
|
-
conversationKey?: string;
|
|
1652
|
-
continuationToken?: string; // Token for resuming after client tool
|
|
1653
|
-
clientInteractionRequest?: ClientInteractionRequest;
|
|
1654
|
-
timestamp?: string;
|
|
1655
|
-
metadata?: Record<string, any>;
|
|
1656
|
-
contents?: Array<{
|
|
1657
|
-
type: string;
|
|
1658
|
-
text?: string;
|
|
1659
|
-
data?: string; // Base64 encoded
|
|
1660
|
-
mediaType?: string;
|
|
1661
|
-
}>;
|
|
1662
|
-
}
|
|
1663
|
-
```
|
|
502
|
+
The library exports `usePlayFramework(name?)`, but it is only a convenience accessor over `PlayFrameworkServices.resolve(name)`.
|
|
1664
503
|
|
|
1665
|
-
|
|
504
|
+
It does not manage React state or subscribe to updates by itself.
|
|
1666
505
|
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
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.
|
|
1670
507
|
|
|
1671
508
|
```typescript
|
|
1672
|
-
|
|
1673
|
-
businessType: number; // Internal type discriminator
|
|
1674
|
-
label?: string | null; // Optional label (e.g., scene name)
|
|
1675
|
-
role: string; // "user" | "assistant" | "system" | "tool"
|
|
1676
|
-
text?: string | null; // Plain text content
|
|
1677
|
-
contents?: any[] | null; // Multi-modal content items
|
|
1678
|
-
additionalProperties?: Record<string, any> | null; // Extra metadata
|
|
1679
|
-
}
|
|
1680
|
-
```
|
|
1681
|
-
|
|
1682
|
-
---
|
|
509
|
+
import { usePlayFramework } from "rystem.playframework.client";
|
|
1683
510
|
|
|
1684
|
-
|
|
511
|
+
const client = usePlayFramework("default");
|
|
1685
512
|
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
```typescript
|
|
1689
|
-
interface ContentItem {
|
|
1690
|
-
type: "text" | "image" | "audio" | "video" | "file" | "uri";
|
|
1691
|
-
text?: string; // For type "text"
|
|
1692
|
-
data?: string; // Base64-encoded binary data
|
|
1693
|
-
uri?: string; // For type "uri"
|
|
1694
|
-
mediaType?: string; // MIME type (e.g., "image/png", "audio/webm")
|
|
1695
|
-
name?: string; // Optional filename
|
|
513
|
+
for await (const step of client.executeStepByStep({ message: "Hello" })) {
|
|
514
|
+
console.log(step.message);
|
|
1696
515
|
}
|
|
1697
516
|
```
|
|
1698
517
|
|
|
1699
|
-
|
|
518
|
+
## Useful exports
|
|
1700
519
|
|
|
1701
|
-
|
|
520
|
+
Besides the main client classes, the package also exports:
|
|
1702
521
|
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
522
|
+
- `AIContentConverter`
|
|
523
|
+
- `ContentUrlConverter`
|
|
524
|
+
- `VoiceRecorder`
|
|
525
|
+
- `BrowserSpeechRecognizer`
|
|
526
|
+
- `BrowserSpeechSynthesizer`
|
|
527
|
+
- `BrowserVoiceClient`
|
|
528
|
+
- `ConversationSortOrder`
|
|
529
|
+
- `CommandResultHelper`
|
|
1707
530
|
|
|
1708
|
-
|
|
531
|
+
## Important caveats
|
|
1709
532
|
|
|
1710
|
-
|
|
533
|
+
### The final `completed` marker is consumed internally
|
|
1711
534
|
|
|
1712
|
-
|
|
535
|
+
`PlayFrameworkClient` treats `status === "completed"` as an internal stop marker and does not yield that marker to callers as a final event.
|
|
1713
536
|
|
|
1714
|
-
|
|
1715
|
-
- 💻 **GitHub**: https://github.com/KeyserDSoze/Rystem
|
|
1716
|
-
- 📦 **npm**: https://www.npmjs.com/package/@rystem/playframework-client
|
|
1717
|
-
- 🎯 **MCP Tools**: https://rystem.net/mcp
|
|
537
|
+
### `status === "error"` throws
|
|
1718
538
|
|
|
1719
|
-
|
|
539
|
+
Server error markers are converted into thrown exceptions rather than yielded error events.
|
|
1720
540
|
|
|
1721
|
-
|
|
541
|
+
### Library code logs to the console
|
|
1722
542
|
|
|
1723
|
-
|
|
543
|
+
The current runtime includes several `console.log`, `console.warn`, and `console.error` calls.
|
|
1724
544
|
|
|
1725
|
-
|
|
545
|
+
### Auto-resume depends on registered tools
|
|
1726
546
|
|
|
1727
|
-
|
|
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.
|
|
1728
548
|
|
|
1729
|
-
|
|
549
|
+
### `baseUrl` must point to the PlayFramework base path only
|
|
1730
550
|
|
|
1731
|
-
|
|
1732
|
-
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
|
|
1733
|
-
3. Commit your changes (`git commit -m 'Add amazing feature'`)
|
|
1734
|
-
4. Push to the branch (`git push origin feature/amazing-feature`)
|
|
1735
|
-
5. Open a Pull Request
|
|
551
|
+
Use a base such as `http://localhost:5158/api/ai`, not `http://localhost:5158/api/ai/default`. The library appends `/{factoryName}` itself.
|
|
1736
552
|
|
|
1737
|
-
|
|
553
|
+
### Many helpers are browser-only
|
|
1738
554
|
|
|
1739
|
-
|
|
555
|
+
`AIContentConverter.fromCamera(...)`, `AIContentConverter.fromGeolocation(...)`, `AIContentConverter.fromMicrophone(...)`, `VoiceRecorder`, and `BrowserSpeech*` utilities depend on browser APIs and are not SSR-safe by default.
|
|
1740
556
|
|
|
1741
|
-
###
|
|
557
|
+
### Browser voice and server voice are different paths
|
|
1742
558
|
|
|
1743
|
-
|
|
1744
|
-
import React, { useState, useRef, useEffect } from 'react';
|
|
1745
|
-
import { usePlayFramework, AIContentConverter } from '@rystem/playframework-client';
|
|
559
|
+
`BrowserVoiceClient` uses browser STT/TTS plus normal SSE endpoints. `executeVoice(...)` uses the server-side `/voice` endpoint with a server `IVoiceAdapter`.
|
|
1746
560
|
|
|
1747
|
-
|
|
1748
|
-
role: 'user' | 'assistant';
|
|
1749
|
-
text: string;
|
|
1750
|
-
status?: string;
|
|
1751
|
-
}
|
|
561
|
+
### `usePlayFramework(...)` is not a real reactive hook
|
|
1752
562
|
|
|
1753
|
-
|
|
1754
|
-
const client = usePlayFramework('default');
|
|
1755
|
-
const [messages, setMessages] = useState<Message[]>([]);
|
|
1756
|
-
const [input, setInput] = useState('');
|
|
1757
|
-
const [loading, setLoading] = useState(false);
|
|
1758
|
-
const [conversationKey] = useState(crypto.randomUUID());
|
|
1759
|
-
|
|
1760
|
-
// Register client tools
|
|
1761
|
-
useEffect(() => {
|
|
1762
|
-
const registry = client.getClientRegistry();
|
|
1763
|
-
|
|
1764
|
-
registry.register('getCurrentLocation', async () => {
|
|
1765
|
-
const content = await AIContentConverter.fromGeolocation();
|
|
1766
|
-
return [content];
|
|
1767
|
-
});
|
|
1768
|
-
|
|
1769
|
-
registry.register('getUserConfirmation', async (args?: { question?: string }) => {
|
|
1770
|
-
const confirmed = window.confirm(args?.question ?? 'Do you confirm?');
|
|
1771
|
-
return [AIContentConverter.fromText(confirmed ? 'confirmed' : 'denied')];
|
|
1772
|
-
});
|
|
1773
|
-
}, [client]);
|
|
1774
|
-
|
|
1775
|
-
const handleSend = async () => {
|
|
1776
|
-
if (!input.trim() || loading) return;
|
|
1777
|
-
|
|
1778
|
-
const userMessage: Message = { role: 'user', text: input };
|
|
1779
|
-
setMessages(prev => [...prev, userMessage]);
|
|
1780
|
-
setInput('');
|
|
1781
|
-
setLoading(true);
|
|
1782
|
-
|
|
1783
|
-
try {
|
|
1784
|
-
const assistantMessage: Message = { role: 'assistant', text: '', status: 'initializing' };
|
|
1785
|
-
setMessages(prev => [...prev, assistantMessage]);
|
|
1786
|
-
|
|
1787
|
-
for await (const step of client.executeStepByStep({
|
|
1788
|
-
message: input,
|
|
1789
|
-
settings: {
|
|
1790
|
-
conversationKey,
|
|
1791
|
-
executionMode: 'Direct',
|
|
1792
|
-
enableStreaming: true
|
|
1793
|
-
}
|
|
1794
|
-
})) {
|
|
1795
|
-
setMessages(prev => {
|
|
1796
|
-
const updated = [...prev];
|
|
1797
|
-
const last = updated[updated.length - 1];
|
|
1798
|
-
|
|
1799
|
-
if (step.streamingChunk) {
|
|
1800
|
-
last.text += step.streamingChunk;
|
|
1801
|
-
} else if (step.message) {
|
|
1802
|
-
last.text = step.message;
|
|
1803
|
-
}
|
|
1804
|
-
last.status = step.status;
|
|
1805
|
-
|
|
1806
|
-
return updated;
|
|
1807
|
-
});
|
|
1808
|
-
}
|
|
1809
|
-
} catch (error) {
|
|
1810
|
-
console.error('Chat error:', error);
|
|
1811
|
-
setMessages(prev => [...prev, {
|
|
1812
|
-
role: 'assistant',
|
|
1813
|
-
text: `Error: ${error instanceof Error ? error.message : 'Unknown error'}`,
|
|
1814
|
-
status: 'error'
|
|
1815
|
-
}]);
|
|
1816
|
-
} finally {
|
|
1817
|
-
setLoading(false);
|
|
1818
|
-
}
|
|
1819
|
-
};
|
|
1820
|
-
|
|
1821
|
-
return (
|
|
1822
|
-
<div style={{ maxWidth: '800px', margin: '0 auto', padding: '20px' }}>
|
|
1823
|
-
<h1>PlayFramework Chat</h1>
|
|
1824
|
-
|
|
1825
|
-
<div style={{ height: '500px', overflowY: 'auto', border: '1px solid #ccc', padding: '10px', marginBottom: '10px' }}>
|
|
1826
|
-
{messages.map((msg, i) => (
|
|
1827
|
-
<div key={i} style={{
|
|
1828
|
-
padding: '10px',
|
|
1829
|
-
margin: '5px 0',
|
|
1830
|
-
borderRadius: '8px',
|
|
1831
|
-
backgroundColor: msg.role === 'user' ? '#e3f2fd' : '#f5f5f5',
|
|
1832
|
-
textAlign: msg.role === 'user' ? 'right' : 'left'
|
|
1833
|
-
}}>
|
|
1834
|
-
<strong>{msg.role === 'user' ? 'You' : 'AI'}</strong>
|
|
1835
|
-
{msg.status && <small style={{ color: '#666', marginLeft: '8px' }}>[{msg.status}]</small>}
|
|
1836
|
-
<div>{msg.text}</div>
|
|
1837
|
-
</div>
|
|
1838
|
-
))}
|
|
1839
|
-
</div>
|
|
1840
|
-
|
|
1841
|
-
<div style={{ display: 'flex', gap: '10px' }}>
|
|
1842
|
-
<input
|
|
1843
|
-
type="text"
|
|
1844
|
-
value={input}
|
|
1845
|
-
onChange={e => setInput(e.target.value)}
|
|
1846
|
-
onKeyDown={e => e.key === 'Enter' && handleSend()}
|
|
1847
|
-
placeholder="Type a message..."
|
|
1848
|
-
disabled={loading}
|
|
1849
|
-
style={{ flex: 1, padding: '10px', fontSize: '16px' }}
|
|
1850
|
-
/>
|
|
1851
|
-
<button onClick={handleSend} disabled={loading} style={{ padding: '10px 20px', fontSize: '16px' }}>
|
|
1852
|
-
{loading ? 'Sending...' : 'Send'}
|
|
1853
|
-
</button>
|
|
1854
|
-
</div>
|
|
1855
|
-
</div>
|
|
1856
|
-
);
|
|
1857
|
-
}
|
|
563
|
+
It is only a resolver helper over `PlayFrameworkServices.resolve(...)`.
|
|
1858
564
|
|
|
1859
|
-
|
|
1860
|
-
```
|
|
565
|
+
## Grounded by source files
|
|
1861
566
|
|
|
1862
|
-
|
|
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`
|
|
1863
577
|
|
|
1864
|
-
|
|
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.
|