rystem.playframework.client 0.1.0 → 0.1.2
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 +1701 -102
- package/lib/engine/ClientInteractionRegistry.d.ts +49 -1
- package/lib/engine/ClientInteractionRegistry.d.ts.map +1 -0
- package/lib/engine/ClientInteractionRegistry.js +84 -13
- package/lib/engine/PlayFrameworkClient.d.ts +40 -0
- package/lib/engine/PlayFrameworkClient.d.ts.map +1 -0
- package/lib/engine/PlayFrameworkClient.js +190 -30
- package/lib/hooks/hooks.d.ts +1 -0
- package/lib/hooks/hooks.d.ts.map +1 -0
- package/lib/index.d.ts +9 -1
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +7 -1
- package/lib/models/AiSceneResponse.d.ts +3 -2
- package/lib/models/AiSceneResponse.d.ts.map +1 -0
- package/lib/models/ClientInteractionRequest.d.ts +16 -0
- package/lib/models/ClientInteractionRequest.d.ts.map +1 -0
- package/lib/models/ClientInteractionResult.d.ts +1 -0
- package/lib/models/ClientInteractionResult.d.ts.map +1 -0
- package/lib/models/CommandResult.d.ts +31 -0
- package/lib/models/CommandResult.d.ts.map +1 -0
- package/lib/models/CommandResult.js +18 -0
- package/lib/models/ContentItem.d.ts +1 -0
- package/lib/models/ContentItem.d.ts.map +1 -0
- package/lib/models/ExecutionState.d.ts +35 -0
- package/lib/models/ExecutionState.d.ts.map +1 -0
- package/lib/models/ExecutionState.js +2 -0
- package/lib/models/PlayFrameworkRequest.d.ts +5 -6
- package/lib/models/PlayFrameworkRequest.d.ts.map +1 -0
- package/lib/models/StoredConversation.d.ts +88 -0
- package/lib/models/StoredConversation.d.ts.map +1 -0
- package/lib/models/StoredConversation.js +17 -0
- package/lib/models/StoredMessage.d.ts +30 -0
- package/lib/models/StoredMessage.d.ts.map +1 -0
- package/lib/models/StoredMessage.js +2 -0
- package/lib/servicecollection/PlayFrameworkServices.d.ts +1 -0
- package/lib/servicecollection/PlayFrameworkServices.d.ts.map +1 -0
- package/lib/servicecollection/PlayFrameworkSettings.d.ts +1 -0
- package/lib/servicecollection/PlayFrameworkSettings.d.ts.map +1 -0
- package/lib/utils/AIContentConverter.d.ts +1 -0
- package/lib/utils/AIContentConverter.d.ts.map +1 -0
- package/lib/utils/ContentUrlConverter.d.ts +62 -0
- package/lib/utils/ContentUrlConverter.d.ts.map +1 -0
- package/lib/utils/ContentUrlConverter.js +151 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,104 +1,115 @@
|
|
|
1
|
-
# Rystem PlayFramework Client
|
|
1
|
+
# 🎮 Rystem PlayFramework Client
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
-
|
|
5
|
-
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
-
|
|
3
|
+
[](https://www.npmjs.com/package/@rystem/playframework-client)
|
|
4
|
+
[](https://www.typescriptlang.org/)
|
|
5
|
+
[](LICENSE)
|
|
6
|
+
|
|
7
|
+
> **Official TypeScript/JavaScript client for [Rystem PlayFramework](https://rystem.net) HTTP API**
|
|
8
|
+
|
|
9
|
+
Production-ready client with full support for:
|
|
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
|
|
10
18
|
|
|
11
19
|
---
|
|
12
20
|
|
|
13
|
-
## Installation
|
|
21
|
+
## 📦 Installation
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
npm install @rystem/playframework-client
|
|
25
|
+
```
|
|
14
26
|
|
|
27
|
+
Or with yarn:
|
|
15
28
|
```bash
|
|
16
|
-
|
|
29
|
+
yarn add @rystem/playframework-client
|
|
17
30
|
```
|
|
18
31
|
|
|
19
32
|
---
|
|
20
33
|
|
|
21
|
-
## Quick Start
|
|
34
|
+
## 🚀 Quick Start
|
|
22
35
|
|
|
23
36
|
### 1. Configure Client
|
|
24
37
|
|
|
25
38
|
```typescript
|
|
26
|
-
import { PlayFrameworkServices } from "rystem
|
|
27
|
-
|
|
28
|
-
// Configure factory
|
|
29
|
-
PlayFrameworkServices.configure("chat", "https://api.example.com/api/ai", settings => {
|
|
30
|
-
// Add Authorization header
|
|
31
|
-
settings.addHeadersEnricher(async (url, method, headers, body) => {
|
|
32
|
-
return {
|
|
33
|
-
...headers,
|
|
34
|
-
"Authorization": `Bearer ${getToken()}`
|
|
35
|
-
};
|
|
36
|
-
});
|
|
39
|
+
import { PlayFrameworkServices } from "@rystem/playframework-client";
|
|
37
40
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
41
|
+
// Configure factory (once at app startup)
|
|
42
|
+
await PlayFrameworkServices.configure("default", "http://localhost:5158/api/ai", settings => {
|
|
43
|
+
settings.timeout = 120_000; // 2 minutes
|
|
44
|
+
settings.maxReconnectAttempts = 3;
|
|
45
|
+
settings.reconnectBaseDelay = 1000;
|
|
43
46
|
});
|
|
44
47
|
```
|
|
45
48
|
|
|
46
49
|
### 2. Use Client (Vanilla JS/TS)
|
|
47
50
|
|
|
48
51
|
```typescript
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
const client = PlayFrameworkServices.getClient("chat");
|
|
52
|
+
const client = PlayFrameworkServices.resolve("default");
|
|
52
53
|
|
|
53
54
|
// Step-by-step streaming
|
|
54
55
|
for await (const step of client.executeStepByStep({
|
|
55
|
-
|
|
56
|
-
sceneName: "ChatScene"
|
|
56
|
+
message: "Tell me a joke"
|
|
57
57
|
})) {
|
|
58
58
|
console.log(`[${step.status}] ${step.message}`);
|
|
59
|
-
// Output:
|
|
60
|
-
// [Planning] Analyzing request...
|
|
61
|
-
// [Running] Generating joke...
|
|
62
|
-
// [Running] Why did the chicken cross the road? To get to the other side!
|
|
63
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
64
|
|
|
65
|
-
// Token-level streaming (
|
|
65
|
+
// Token-level streaming (real-time chunks)
|
|
66
66
|
for await (const chunk of client.executeTokenStreaming({
|
|
67
|
-
|
|
67
|
+
message: "Write a short story"
|
|
68
68
|
})) {
|
|
69
|
-
process.stdout.write(chunk.
|
|
70
|
-
// Output: "Once" → " upon" → " a" → " time" → "..."
|
|
69
|
+
process.stdout.write(chunk.streamingChunk || "");
|
|
71
70
|
}
|
|
71
|
+
// Output: "Once" → " upon" → " a" → " time" → "..."
|
|
72
72
|
```
|
|
73
73
|
|
|
74
74
|
### 3. Use with React
|
|
75
75
|
|
|
76
76
|
```tsx
|
|
77
|
-
import { usePlayFramework } from "rystem
|
|
77
|
+
import { usePlayFramework } from "@rystem/playframework-client";
|
|
78
78
|
import { useState } from "react";
|
|
79
79
|
|
|
80
80
|
function ChatComponent() {
|
|
81
|
-
const client = usePlayFramework("
|
|
81
|
+
const client = usePlayFramework("default");
|
|
82
82
|
const [messages, setMessages] = useState<string[]>([]);
|
|
83
|
+
const [loading, setLoading] = useState(false);
|
|
83
84
|
|
|
84
|
-
const handleSend = async () => {
|
|
85
|
+
const handleSend = async (input: string) => {
|
|
86
|
+
setLoading(true);
|
|
85
87
|
const newMessages: string[] = [];
|
|
86
88
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
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
|
+
}
|
|
93
100
|
setMessages([...newMessages]);
|
|
94
101
|
}
|
|
102
|
+
} finally {
|
|
103
|
+
setLoading(false);
|
|
95
104
|
}
|
|
96
105
|
};
|
|
97
106
|
|
|
98
107
|
return (
|
|
99
108
|
<div>
|
|
100
|
-
<
|
|
101
|
-
|
|
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>
|
|
102
113
|
</div>
|
|
103
114
|
);
|
|
104
115
|
}
|
|
@@ -106,28 +117,188 @@ function ChatComponent() {
|
|
|
106
117
|
|
|
107
118
|
---
|
|
108
119
|
|
|
109
|
-
##
|
|
120
|
+
## 🎯 Core Features
|
|
121
|
+
|
|
122
|
+
### Step-by-Step vs Token Streaming
|
|
123
|
+
|
|
124
|
+
**Step-by-Step** (`executeStepByStep`):
|
|
125
|
+
- Returns each **scene/actor execution** as separate event
|
|
126
|
+
- Best for: Multi-step workflows, debugging, progress tracking
|
|
127
|
+
- Example: Planning → Actor1 → Actor2 → Completed
|
|
128
|
+
|
|
129
|
+
**Token Streaming** (`executeTokenStreaming`):
|
|
130
|
+
- Returns **individual text chunks** as they're generated
|
|
131
|
+
- Best for: Real-time chat UIs, typewriter effects
|
|
132
|
+
- Example: "Hello" → " world" → "!" → "..."
|
|
133
|
+
|
|
134
|
+
```typescript
|
|
135
|
+
// Step-by-step - structured workflow
|
|
136
|
+
for await (const step of client.executeStepByStep({ message: "..." })) {
|
|
137
|
+
console.log(step.status); // "planning", "executingScene", "completed"
|
|
138
|
+
console.log(step.sceneName); // "ChatScene"
|
|
139
|
+
console.log(step.message); // Full response
|
|
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
|
+
```
|
|
147
|
+
|
|
148
|
+
---
|
|
149
|
+
|
|
150
|
+
## 🛠️ Client-Side Tools
|
|
151
|
+
|
|
152
|
+
Execute **browser-specific operations** (camera, geolocation, file picker) when LLM requests them.
|
|
153
|
+
|
|
154
|
+
### Server Setup (C#)
|
|
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)
|
|
172
|
+
|
|
173
|
+
```typescript
|
|
174
|
+
import { PlayFrameworkServices, AIContentConverter } from "@rystem/playframework-client";
|
|
175
|
+
|
|
176
|
+
const client = PlayFrameworkServices.resolve("default");
|
|
177
|
+
const registry = client.getClientRegistry();
|
|
178
|
+
|
|
179
|
+
// Register camera tool
|
|
180
|
+
registry.register("capturePhoto", async () => {
|
|
181
|
+
const content = await AIContentConverter.fromCamera(
|
|
182
|
+
{ video: { facingMode: "environment" } }, // Rear camera
|
|
183
|
+
1920, 1080
|
|
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
|
+
});
|
|
193
|
+
|
|
194
|
+
// Register file picker
|
|
195
|
+
registry.register("selectFiles", async (args?: { accept?: string }) => {
|
|
196
|
+
return new Promise((resolve) => {
|
|
197
|
+
const input = document.createElement("input");
|
|
198
|
+
input.type = "file";
|
|
199
|
+
input.accept = args?.accept || "*/*";
|
|
200
|
+
input.onchange = async () => {
|
|
201
|
+
const contents = await AIContentConverter.fromMultipleFiles(input.files!);
|
|
202
|
+
resolve(contents);
|
|
203
|
+
};
|
|
204
|
+
input.click();
|
|
205
|
+
});
|
|
206
|
+
});
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
**Client automatically resumes execution after tool completion!**
|
|
210
|
+
|
|
211
|
+
```typescript
|
|
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
|
+
}
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
### AIContentConverter Helpers
|
|
222
|
+
|
|
223
|
+
```typescript
|
|
224
|
+
// Camera (returns Base64 JPEG)
|
|
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");
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
---
|
|
244
|
+
|
|
245
|
+
## 🎛️ Execution Modes
|
|
246
|
+
|
|
247
|
+
Control **how scenes are selected and executed**:
|
|
110
248
|
|
|
111
249
|
```typescript
|
|
112
|
-
import { PlayFrameworkRequest
|
|
250
|
+
import { PlayFrameworkRequest } from "@rystem/playframework-client";
|
|
113
251
|
|
|
114
252
|
const request: PlayFrameworkRequest = {
|
|
115
|
-
|
|
116
|
-
|
|
253
|
+
message: "Book a flight to Paris",
|
|
254
|
+
settings: {
|
|
255
|
+
executionMode: "Planning", // Direct | Planning | DynamicChaining | Scene
|
|
256
|
+
maxRecursionDepth: 5,
|
|
257
|
+
enableSummarization: true,
|
|
258
|
+
enableDirector: false
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
### Available Modes
|
|
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 |
|
|
271
|
+
|
|
272
|
+
---
|
|
273
|
+
|
|
274
|
+
## 📸 Multi-Modal Content
|
|
275
|
+
|
|
276
|
+
Send **images, audio, video, PDFs, URIs** with your request:
|
|
277
|
+
|
|
278
|
+
```typescript
|
|
279
|
+
import { PlayFrameworkRequest, ContentItem } from "@rystem/playframework-client";
|
|
280
|
+
|
|
281
|
+
const request: PlayFrameworkRequest = {
|
|
282
|
+
message: "Describe this image and summarize the PDF",
|
|
117
283
|
contents: [
|
|
118
284
|
{
|
|
119
285
|
type: "image",
|
|
120
|
-
|
|
286
|
+
data: "iVBORw0KGgoAAAANSUhEUgAA...",
|
|
121
287
|
mediaType: "image/png"
|
|
122
288
|
},
|
|
123
289
|
{
|
|
124
|
-
type: "
|
|
125
|
-
|
|
290
|
+
type: "data",
|
|
291
|
+
data: "JVBERi0xLjQKJeLjz9M...",
|
|
292
|
+
mediaType: "application/pdf"
|
|
126
293
|
},
|
|
127
294
|
{
|
|
128
295
|
type: "uri",
|
|
129
296
|
uri: "https://example.com/document.pdf",
|
|
130
297
|
mediaType: "application/pdf"
|
|
298
|
+
},
|
|
299
|
+
{
|
|
300
|
+
type: "text",
|
|
301
|
+
text: "Additional context"
|
|
131
302
|
}
|
|
132
303
|
]
|
|
133
304
|
};
|
|
@@ -139,26 +310,28 @@ for await (const step of client.executeStepByStep(request)) {
|
|
|
139
310
|
|
|
140
311
|
---
|
|
141
312
|
|
|
142
|
-
## Configuration
|
|
313
|
+
## ⚙️ Configuration & Settings
|
|
314
|
+
|
|
315
|
+
### Global Configuration
|
|
143
316
|
|
|
144
317
|
```typescript
|
|
145
|
-
PlayFrameworkServices
|
|
146
|
-
|
|
147
|
-
|
|
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
|
|
148
323
|
|
|
149
|
-
//
|
|
150
|
-
settings.
|
|
324
|
+
// Reconnection on SSE failures
|
|
325
|
+
settings.maxReconnectAttempts = 3;
|
|
326
|
+
settings.reconnectBaseDelay = 1000; // 1 second
|
|
151
327
|
|
|
152
328
|
// Default headers
|
|
153
329
|
settings.defaultHeaders = {
|
|
154
330
|
"Content-Type": "application/json",
|
|
155
|
-
"X-
|
|
331
|
+
"X-App-Version": "1.0.0"
|
|
156
332
|
};
|
|
157
333
|
|
|
158
|
-
//
|
|
159
|
-
settings.timeout = 120000; // 2 minutes
|
|
160
|
-
|
|
161
|
-
// Add dynamic headers (e.g., auth token)
|
|
334
|
+
// Dynamic headers (auth token)
|
|
162
335
|
settings.addHeadersEnricher(async (url, method, headers, body) => {
|
|
163
336
|
const token = await getAuthToken();
|
|
164
337
|
return {
|
|
@@ -170,7 +343,7 @@ PlayFrameworkServices.configure("premium", "https://api.example.com/api/ai/premi
|
|
|
170
343
|
// Error handling with retry
|
|
171
344
|
settings.addErrorHandler(async (url, method, headers, body, error) => {
|
|
172
345
|
if (error.message.includes("401")) {
|
|
173
|
-
await
|
|
346
|
+
await refreshAuthToken();
|
|
174
347
|
return true; // Retry
|
|
175
348
|
}
|
|
176
349
|
return false; // Don't retry
|
|
@@ -178,20 +351,968 @@ PlayFrameworkServices.configure("premium", "https://api.example.com/api/ai/premi
|
|
|
178
351
|
});
|
|
179
352
|
```
|
|
180
353
|
|
|
354
|
+
### Per-Request Settings
|
|
355
|
+
|
|
356
|
+
```typescript
|
|
357
|
+
const request: PlayFrameworkRequest = {
|
|
358
|
+
message: "Your query",
|
|
359
|
+
settings: {
|
|
360
|
+
// Execution mode
|
|
361
|
+
executionMode: "Planning", // Direct | Planning | DynamicChaining | Scene
|
|
362
|
+
|
|
363
|
+
// Planning settings
|
|
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
|
+
```
|
|
394
|
+
|
|
395
|
+
---
|
|
396
|
+
|
|
397
|
+
## 🔄 Conversation State & Caching
|
|
398
|
+
|
|
399
|
+
Use `conversationKey` to maintain **multi-turn conversations**:
|
|
400
|
+
|
|
401
|
+
```typescript
|
|
402
|
+
const conversationKey = crypto.randomUUID();
|
|
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
|
+
}
|
|
411
|
+
|
|
412
|
+
// Follow-up request (uses cached context)
|
|
413
|
+
for await (const step of client.executeStepByStep({
|
|
414
|
+
message: "And in London?",
|
|
415
|
+
settings: { conversationKey }
|
|
416
|
+
})) {
|
|
417
|
+
console.log(step.message); // LLM remembers Paris context
|
|
418
|
+
}
|
|
419
|
+
```
|
|
420
|
+
|
|
181
421
|
---
|
|
182
422
|
|
|
183
|
-
##
|
|
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
|
+
|
|
457
|
+
```typescript
|
|
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
|
+
}
|
|
466
|
+
```
|
|
467
|
+
|
|
468
|
+
**Authorization**: Private conversations require userId match (set via backend `IAuthorizationLayer`).
|
|
469
|
+
|
|
470
|
+
### Delete Conversation
|
|
471
|
+
|
|
472
|
+
```typescript
|
|
473
|
+
// Owner-only operation
|
|
474
|
+
await client.deleteConversation("abc-123");
|
|
475
|
+
console.log("Conversation deleted");
|
|
476
|
+
```
|
|
477
|
+
|
|
478
|
+
**Response:**
|
|
479
|
+
- ✅ Success - Conversation deleted
|
|
480
|
+
- ❌ `403 Forbidden` - Not the owner
|
|
481
|
+
- ❌ `404 Not Found` - Conversation not found
|
|
482
|
+
|
|
483
|
+
### Update Visibility (Public/Private)
|
|
484
|
+
|
|
485
|
+
```typescript
|
|
486
|
+
// Toggle conversation visibility (owner-only)
|
|
487
|
+
const updated = await client.updateConversationVisibility("abc-123", true);
|
|
488
|
+
console.log(`Conversation is now ${updated.isPublic ? "public" : "private"}`);
|
|
489
|
+
```
|
|
490
|
+
|
|
491
|
+
### React Example: Conversation List UI
|
|
492
|
+
|
|
493
|
+
```tsx
|
|
494
|
+
import { useState, useEffect } from "react";
|
|
495
|
+
import { usePlayFramework, StoredConversation, ConversationSortOrder } from "@rystem/playframework-client";
|
|
496
|
+
|
|
497
|
+
function ConversationList() {
|
|
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"
|
|
1018
|
+
};
|
|
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
|
+
```
|
|
1052
|
+
|
|
1053
|
+
#### `clearCache(): void`
|
|
1054
|
+
Revokes all cached URLs at once.
|
|
1055
|
+
|
|
1056
|
+
```typescript
|
|
1057
|
+
ContentUrlConverter.clearCache();
|
|
1058
|
+
```
|
|
1059
|
+
|
|
1060
|
+
#### `downloadAsFile(content: AIContent, filename?: string): void`
|
|
1061
|
+
Triggers browser download.
|
|
1062
|
+
|
|
1063
|
+
```typescript
|
|
1064
|
+
ContentUrlConverter.downloadAsFile(content, 'image.jpg');
|
|
1065
|
+
```
|
|
1066
|
+
|
|
1067
|
+
#### `getFileExtension(mediaType?: string): string`
|
|
1068
|
+
Maps MIME type to file extension.
|
|
1069
|
+
|
|
1070
|
+
```typescript
|
|
1071
|
+
const ext = ContentUrlConverter.getFileExtension('image/jpeg'); // ".jpg"
|
|
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]);
|
|
1134
|
+
|
|
1135
|
+
if (!url) return <div>Loading...</div>;
|
|
1136
|
+
|
|
1137
|
+
// Image
|
|
1138
|
+
if (mediaType.startsWith('image/')) {
|
|
1139
|
+
return <img src={url} alt="Image" style={{ maxWidth: '100%' }} />;
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
// Audio
|
|
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
|
+
);
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
// PDF
|
|
1161
|
+
if (mediaType === 'application/pdf') {
|
|
1162
|
+
return (
|
|
1163
|
+
<iframe
|
|
1164
|
+
src={url}
|
|
1165
|
+
title="PDF Document"
|
|
1166
|
+
style={{ width: '100%', height: '600px', border: '1px solid #ddd' }}
|
|
1167
|
+
/>
|
|
1168
|
+
);
|
|
1169
|
+
}
|
|
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
|
+
);
|
|
1180
|
+
}
|
|
1181
|
+
```
|
|
1182
|
+
|
|
1183
|
+
---
|
|
1184
|
+
|
|
1185
|
+
### includeContents Parameter
|
|
1186
|
+
|
|
1187
|
+
When loading conversations, control whether to fetch base64 content:
|
|
1188
|
+
|
|
1189
|
+
```typescript
|
|
1190
|
+
// ❌ List conversations WITHOUT media (faster, smaller payload)
|
|
1191
|
+
const list = await client.listConversations({
|
|
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
|
|
1198
|
+
```
|
|
1199
|
+
|
|
1200
|
+
**Why this matters:**
|
|
1201
|
+
|
|
1202
|
+
| Operation | includeContents | Payload Size | Speed |
|
|
1203
|
+
|-----------|----------------|--------------|-------|
|
|
1204
|
+
| List 100 conversations | `false` | ~50 KB | ⚡ Fast (~50ms) |
|
|
1205
|
+
| List 100 conversations | `true` | ~5-50 MB | 🐢 Slow (~500ms) |
|
|
1206
|
+
| Get single conversation | `true` | ~50-500 KB | ✅ Acceptable |
|
|
1207
|
+
|
|
1208
|
+
**Best Practice**: Always use `includeContents=false` for list operations, `true` only when loading a conversation for display.
|
|
1209
|
+
|
|
1210
|
+
---
|
|
1211
|
+
|
|
1212
|
+
### Full Example: Chat with Multi-Modal Support
|
|
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);
|
|
1222
|
+
|
|
1223
|
+
const loadConversation = async (key: string) => {
|
|
1224
|
+
// Load conversation WITH contents
|
|
1225
|
+
const conv = await client.getConversation(key, true);
|
|
1226
|
+
|
|
1227
|
+
if (conv) {
|
|
1228
|
+
setMessages(conv.messages);
|
|
1229
|
+
setConversationKey(conv.conversationKey);
|
|
1230
|
+
}
|
|
1231
|
+
};
|
|
1232
|
+
|
|
1233
|
+
return (
|
|
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
|
+
);
|
|
1263
|
+
}
|
|
1264
|
+
```
|
|
1265
|
+
|
|
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**:
|
|
184
1299
|
|
|
185
1300
|
```typescript
|
|
186
1301
|
const controller = new AbortController();
|
|
187
1302
|
|
|
188
1303
|
// Start streaming
|
|
189
1304
|
const promise = (async () => {
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
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
|
+
}
|
|
195
1316
|
}
|
|
196
1317
|
})();
|
|
197
1318
|
|
|
@@ -201,65 +1322,543 @@ setTimeout(() => controller.abort(), 5000);
|
|
|
201
1322
|
|
|
202
1323
|
---
|
|
203
1324
|
|
|
204
|
-
##
|
|
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
|
+
```
|
|
1351
|
+
|
|
1352
|
+
---
|
|
1353
|
+
|
|
1354
|
+
## 🧪 Testing
|
|
1355
|
+
|
|
1356
|
+
```typescript
|
|
1357
|
+
import { PlayFrameworkClient, PlayFrameworkSettings } from "@rystem/playframework-client";
|
|
1358
|
+
|
|
1359
|
+
describe("PlayFramework Client", () => {
|
|
1360
|
+
it("should stream responses", async () => {
|
|
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
|
+
}
|
|
1369
|
+
|
|
1370
|
+
expect(responses.length).toBeGreaterThan(0);
|
|
1371
|
+
});
|
|
1372
|
+
});
|
|
1373
|
+
```
|
|
1374
|
+
|
|
1375
|
+
---
|
|
1376
|
+
|
|
1377
|
+
## 📚 API Reference
|
|
1378
|
+
|
|
1379
|
+
### `PlayFrameworkServices`
|
|
1380
|
+
|
|
1381
|
+
Static service locator for managing named `PlayFrameworkClient` instances.
|
|
1382
|
+
|
|
1383
|
+
| Method | Signature | Description |
|
|
1384
|
+
|--------|-----------|-------------|
|
|
1385
|
+
| `configure` | `(name: string, baseUrl: string, configure?: (settings: PlayFrameworkSettings) => void \| Promise<void>): Promise<PlayFrameworkSettings>` | Register and configure a named client factory |
|
|
1386
|
+
| `resolve` | `(name?: string): PlayFrameworkClient` | Get client by name (defaults to first registered) |
|
|
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");
|
|
1397
|
+
|
|
1398
|
+
// Resolve
|
|
1399
|
+
const client = PlayFrameworkServices.resolve("chat");
|
|
1400
|
+
|
|
1401
|
+
// Check & remove
|
|
1402
|
+
if (PlayFrameworkServices.isConfigured("chat")) {
|
|
1403
|
+
PlayFrameworkServices.remove("chat");
|
|
1404
|
+
}
|
|
1405
|
+
```
|
|
1406
|
+
|
|
1407
|
+
---
|
|
1408
|
+
|
|
1409
|
+
### `PlayFrameworkClient`
|
|
1410
|
+
|
|
1411
|
+
Main client for executing AI requests via SSE streaming.
|
|
1412
|
+
|
|
1413
|
+
| Method | Signature | Description |
|
|
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 |
|
|
1421
|
+
|
|
1422
|
+
---
|
|
1423
|
+
|
|
1424
|
+
### `ClientInteractionRegistry`
|
|
205
1425
|
|
|
206
|
-
|
|
1426
|
+
Registry for client-side tools and commands invoked by the AI during execution.
|
|
207
1427
|
|
|
208
|
-
|
|
1428
|
+
| Method | Signature | Description |
|
|
1429
|
+
|--------|-----------|-------------|
|
|
1430
|
+
| `register` | `<TArgs>(toolName: string, handler: ClientTool<TArgs>): void` | Register a tool (server waits for response) |
|
|
1431
|
+
| `registerCommand` | `<TArgs>(toolName: string, handler: ClientCommand<TArgs>, options?: CommandOptions): void` | Register a fire-and-forget command |
|
|
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 |
|
|
209
1439
|
|
|
210
|
-
|
|
1440
|
+
**Types:**
|
|
211
1441
|
|
|
212
|
-
|
|
1442
|
+
```typescript
|
|
1443
|
+
type ClientTool<TArgs = any> = (args?: TArgs) => Promise<AIContent[]>;
|
|
1444
|
+
type ClientCommand<TArgs = any> = (args?: TArgs) => Promise<CommandResult>;
|
|
1445
|
+
type CommandFeedbackMode = 'never' | 'onError' | 'always';
|
|
213
1446
|
|
|
214
|
-
|
|
1447
|
+
interface CommandOptions {
|
|
1448
|
+
feedbackMode?: CommandFeedbackMode;
|
|
1449
|
+
}
|
|
1450
|
+
```
|
|
215
1451
|
|
|
216
|
-
|
|
1452
|
+
```typescript
|
|
1453
|
+
// Tool — server waits for the result
|
|
1454
|
+
registry.register("myTool", async (args?: { key: string }) => {
|
|
1455
|
+
return [AIContentConverter.fromText(args?.key || "default")];
|
|
1456
|
+
});
|
|
217
1457
|
|
|
218
|
-
|
|
1458
|
+
// Command — fire-and-forget, feedback optional
|
|
1459
|
+
registry.registerCommand("showNotification", async (args?: { text: string }) => {
|
|
1460
|
+
showToast(args?.text ?? "");
|
|
1461
|
+
return CommandResult.ok();
|
|
1462
|
+
}, { feedbackMode: 'onError' });
|
|
1463
|
+
```
|
|
219
1464
|
|
|
220
1465
|
---
|
|
221
1466
|
|
|
222
|
-
###
|
|
1467
|
+
### `AIContentConverter`
|
|
1468
|
+
|
|
1469
|
+
#### Static Methods
|
|
1470
|
+
|
|
1471
|
+
- `fromCamera(constraints?, width?, height?): Promise<AIContent>` - Capture photo
|
|
1472
|
+
- `fromGeolocation(options?): Promise<AIContent>` - Get GPS coordinates
|
|
1473
|
+
- `fromFile(file: File | Blob): Promise<AIContent>` - Convert file to Base64
|
|
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
|
|
1477
|
+
|
|
1478
|
+
---
|
|
1479
|
+
|
|
1480
|
+
## 🎨 React Hook (`usePlayFramework`)
|
|
1481
|
+
|
|
1482
|
+
```tsx
|
|
1483
|
+
import { usePlayFramework } from "@rystem/playframework-client";
|
|
1484
|
+
|
|
1485
|
+
function MyComponent() {
|
|
1486
|
+
const client = usePlayFramework("default");
|
|
1487
|
+
|
|
1488
|
+
const handleClick = async () => {
|
|
1489
|
+
for await (const step of client.executeStepByStep({ message: "Hello" })) {
|
|
1490
|
+
console.log(step);
|
|
1491
|
+
}
|
|
1492
|
+
};
|
|
1493
|
+
|
|
1494
|
+
return <button onClick={handleClick}>Send</button>;
|
|
1495
|
+
}
|
|
1496
|
+
```
|
|
1497
|
+
|
|
1498
|
+
---
|
|
223
1499
|
|
|
224
|
-
|
|
1500
|
+
## � Client Commands (Fire-and-Forget)
|
|
225
1501
|
|
|
226
|
-
|
|
1502
|
+
Commands are client-side tools that the server invokes but **does not wait for a response**. Use them for UI side effects (toasts, navigation, animations, etc.).
|
|
1503
|
+
|
|
1504
|
+
### Registering Commands
|
|
227
1505
|
|
|
228
1506
|
```typescript
|
|
229
|
-
|
|
1507
|
+
const registry = client.getClientRegistry();
|
|
1508
|
+
|
|
1509
|
+
// Simple command — no feedback to server
|
|
1510
|
+
registry.registerCommand("showToast", async (args?: { text: string }) => {
|
|
1511
|
+
showNotification(args?.text ?? "");
|
|
1512
|
+
return CommandResult.ok();
|
|
1513
|
+
});
|
|
1514
|
+
|
|
1515
|
+
// Command with error feedback — server receives failure info
|
|
1516
|
+
registry.registerCommand("navigateTo", async (args?: { url: string }) => {
|
|
1517
|
+
try {
|
|
1518
|
+
window.location.href = args?.url ?? "/";
|
|
1519
|
+
return CommandResult.ok();
|
|
1520
|
+
} catch (e) {
|
|
1521
|
+
return CommandResult.fail(`Navigation failed: ${e}`);
|
|
1522
|
+
}
|
|
1523
|
+
}, { feedbackMode: 'onError' });
|
|
1524
|
+
|
|
1525
|
+
// Command with always-feedback — server always gets the result
|
|
1526
|
+
registry.registerCommand("playSound", async (args?: { soundId: string }) => {
|
|
1527
|
+
await audioPlayer.play(args?.soundId ?? "notification");
|
|
1528
|
+
return CommandResult.ok("Sound played");
|
|
1529
|
+
}, { feedbackMode: 'always' });
|
|
230
1530
|
```
|
|
231
1531
|
|
|
232
|
-
|
|
1532
|
+
### `CommandResult` Helper
|
|
1533
|
+
|
|
1534
|
+
```typescript
|
|
1535
|
+
interface CommandResult {
|
|
1536
|
+
success: boolean;
|
|
1537
|
+
message?: string;
|
|
1538
|
+
}
|
|
1539
|
+
|
|
1540
|
+
// Factory methods
|
|
1541
|
+
CommandResult.ok(); // { success: true }
|
|
1542
|
+
CommandResult.ok("Done"); // { success: true, message: "Done" }
|
|
1543
|
+
CommandResult.fail("Reason"); // { success: false, message: "Reason" }
|
|
1544
|
+
```
|
|
1545
|
+
|
|
1546
|
+
### `CommandFeedbackMode`
|
|
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 |
|
|
1553
|
+
|
|
1554
|
+
---
|
|
1555
|
+
|
|
1556
|
+
## 📋 `ClientInteractionRequest` Model
|
|
233
1557
|
|
|
234
|
-
|
|
1558
|
+
When the server invokes a client-side tool or command, it sends this object:
|
|
235
1559
|
|
|
236
1560
|
```typescript
|
|
237
|
-
|
|
1561
|
+
interface ClientInteractionRequest {
|
|
1562
|
+
interactionId: string; // Unique ID for this invocation
|
|
1563
|
+
toolName: string; // Registered tool/command name
|
|
1564
|
+
description?: string; // Human-readable description
|
|
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
|
+
}
|
|
238
1571
|
```
|
|
239
1572
|
|
|
240
|
-
|
|
1573
|
+
---
|
|
1574
|
+
|
|
1575
|
+
## 📋 `ClientInteractionResult` Model
|
|
241
1576
|
|
|
242
|
-
|
|
1577
|
+
The response your tool handler returns to the server:
|
|
243
1578
|
|
|
244
1579
|
```typescript
|
|
245
|
-
|
|
246
|
-
|
|
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
|
+
}
|
|
247
1593
|
```
|
|
248
1594
|
|
|
249
1595
|
---
|
|
250
1596
|
|
|
251
|
-
|
|
1597
|
+
## 📋 `ExecutionState` and `ExecutionPhase`
|
|
252
1598
|
|
|
253
|
-
|
|
1599
|
+
The `ExecutionState` object tracks the AI orchestration progress during execution:
|
|
254
1600
|
|
|
255
|
-
|
|
1601
|
+
```typescript
|
|
1602
|
+
type ExecutionPhase =
|
|
1603
|
+
| "notStarted"
|
|
1604
|
+
| "initialized"
|
|
1605
|
+
| "sceneSelected"
|
|
1606
|
+
| "executingScene"
|
|
1607
|
+
| "awaitingClient"
|
|
1608
|
+
| "sceneCompleted"
|
|
1609
|
+
| "chaining"
|
|
1610
|
+
| "generatingFinalResponse"
|
|
1611
|
+
| "completed"
|
|
1612
|
+
| "completedNoResponse"
|
|
1613
|
+
| "budgetExceeded"
|
|
1614
|
+
| "sceneNotFound"
|
|
1615
|
+
| "tooManyToolRequests"
|
|
1616
|
+
| "break"
|
|
1617
|
+
| "unauthorized";
|
|
1618
|
+
|
|
1619
|
+
interface ExecutionState {
|
|
1620
|
+
phase: ExecutionPhase; // Current execution phase
|
|
1621
|
+
executedSceneOrder: string[]; // Scene names in execution order
|
|
1622
|
+
executedScenes: Record<string, any[]>; // Scene name → results
|
|
1623
|
+
executedTools: string[]; // Tool names invoked
|
|
1624
|
+
accumulatedCost: number; // Total $ cost so far
|
|
1625
|
+
currentSceneName?: string | null; // Currently running scene
|
|
1626
|
+
}
|
|
1627
|
+
```
|
|
1628
|
+
|
|
1629
|
+
---
|
|
256
1630
|
|
|
257
|
-
|
|
1631
|
+
## 📋 `AiSceneResponse` Full Model
|
|
258
1632
|
|
|
259
|
-
|
|
1633
|
+
Each SSE event yields an `AiSceneResponse`:
|
|
1634
|
+
|
|
1635
|
+
```typescript
|
|
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
|
+
```
|
|
1664
|
+
|
|
1665
|
+
---
|
|
1666
|
+
|
|
1667
|
+
## 📋 `StoredMessage` Full Model
|
|
1668
|
+
|
|
1669
|
+
Each message in a `StoredConversation.messages` array:
|
|
1670
|
+
|
|
1671
|
+
```typescript
|
|
1672
|
+
interface StoredMessage {
|
|
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
|
+
---
|
|
1683
|
+
|
|
1684
|
+
## 📋 `ContentItem` Full Model
|
|
1685
|
+
|
|
1686
|
+
Used in `PlayFrameworkRequest.contents` for multi-modal input:
|
|
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
|
|
1696
|
+
}
|
|
1697
|
+
```
|
|
1698
|
+
|
|
1699
|
+
---
|
|
1700
|
+
|
|
1701
|
+
## �📁 Where to Place This README
|
|
1702
|
+
|
|
1703
|
+
This README should be placed in:
|
|
1704
|
+
```
|
|
1705
|
+
src/AI/Rystem.PlayFramework.Client/src/rystem/README.md
|
|
1706
|
+
```
|
|
1707
|
+
|
|
1708
|
+
This is the **library source** directory that gets published to npm.
|
|
1709
|
+
|
|
1710
|
+
---
|
|
1711
|
+
|
|
1712
|
+
## 🔗 Links
|
|
1713
|
+
|
|
1714
|
+
- 📖 **Documentation**: https://rystem.net/playframework
|
|
1715
|
+
- 💻 **GitHub**: https://github.com/KeyserDSoze/Rystem
|
|
1716
|
+
- 📦 **npm**: https://www.npmjs.com/package/@rystem/playframework-client
|
|
1717
|
+
- 🎯 **MCP Tools**: https://rystem.net/mcp
|
|
1718
|
+
|
|
1719
|
+
---
|
|
1720
|
+
|
|
1721
|
+
## 📄 License
|
|
1722
|
+
|
|
1723
|
+
MIT © [Alessandro Rapiti](https://github.com/KeyserDSoze)
|
|
1724
|
+
|
|
1725
|
+
---
|
|
1726
|
+
|
|
1727
|
+
## 🤝 Contributing
|
|
1728
|
+
|
|
1729
|
+
Contributions welcome! Please open an issue or PR.
|
|
1730
|
+
|
|
1731
|
+
1. Fork the repo
|
|
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
|
|
260
1736
|
|
|
261
1737
|
---
|
|
262
1738
|
|
|
263
|
-
##
|
|
1739
|
+
## 💡 Examples
|
|
1740
|
+
|
|
1741
|
+
### Complete Chat Application
|
|
1742
|
+
|
|
1743
|
+
```tsx
|
|
1744
|
+
import React, { useState, useRef, useEffect } from 'react';
|
|
1745
|
+
import { usePlayFramework, AIContentConverter } from '@rystem/playframework-client';
|
|
1746
|
+
|
|
1747
|
+
interface Message {
|
|
1748
|
+
role: 'user' | 'assistant';
|
|
1749
|
+
text: string;
|
|
1750
|
+
status?: string;
|
|
1751
|
+
}
|
|
1752
|
+
|
|
1753
|
+
function ChatApp() {
|
|
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
|
+
}
|
|
1858
|
+
|
|
1859
|
+
export default ChatApp;
|
|
1860
|
+
```
|
|
1861
|
+
|
|
1862
|
+
---
|
|
264
1863
|
|
|
265
|
-
|
|
1864
|
+
**Made with ❤️ by the Rystem team**
|