-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb_chat.py
More file actions
executable file
·581 lines (510 loc) · 18.8 KB
/
Copy pathweb_chat.py
File metadata and controls
executable file
·581 lines (510 loc) · 18.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
#!/usr/bin/env python3
"""
Flask Web Chat Application with Context Branching
A simple web interface demonstrating the Context Branching SDK.
Provides REST API endpoints and a basic HTML interface.
Usage:
python web_chat.py [--port PORT] [--storage-path PATH]
API Endpoints:
POST /api/workspace/create - Create new workspace
GET /api/workspace/<id>/messages - Get current context
POST /api/workspace/<id>/message - Add message
POST /api/workspace/<id>/checkpoint - Create checkpoint
POST /api/workspace/<id>/branch - Create branch
POST /api/workspace/<id>/switch - Switch branch
GET /api/workspace/<id>/branches - List branches
GET /api/workspace/<id>/checkpoints - List checkpoints
"""
import sys
from pathlib import Path
# Add parent directory to path to import SDK
sys.path.insert(0, str(Path(__file__).parent.parent))
from sdk import ContextBranchingSDK, Message
from flask import Flask, request, jsonify, render_template_string
from datetime import datetime
import argparse
# Import LLM utilities
try:
from app.llm_utils import create_llm_from_env
llm_client = create_llm_from_env()
LLM_AVAILABLE = llm_client is not None
except ImportError:
llm_client = None
LLM_AVAILABLE = False
app = Flask(__name__)
sdk = None # Will be initialized in main()
# HTML Template for the chat interface
HTML_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
<title>Context Branching Chat</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 1200px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
}
h1 {
color: #333;
border-bottom: 3px solid #2196F3;
padding-bottom: 10px;
}
.container {
display: flex;
gap: 20px;
}
.chat-panel {
flex: 2;
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.sidebar {
flex: 1;
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.messages {
height: 400px;
overflow-y: auto;
border: 1px solid #ddd;
padding: 15px;
margin-bottom: 20px;
background: #fafafa;
border-radius: 4px;
}
.message {
margin-bottom: 15px;
padding: 10px;
border-radius: 6px;
}
.user-message {
background-color: #E3F2FD;
border-left: 4px solid #2196F3;
}
.assistant-message {
background-color: #F1F8E9;
border-left: 4px solid #4CAF50;
}
.input-area {
display: flex;
gap: 10px;
}
input[type="text"] {
flex: 1;
padding: 12px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 14px;
}
button {
padding: 12px 24px;
background-color: #2196F3;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
font-weight: 600;
}
button:hover {
background-color: #1976D2;
}
.branch-button {
background-color: #4CAF50;
margin: 5px;
padding: 8px 16px;
font-size: 13px;
}
.branch-button:hover {
background-color: #45a049;
}
.current-branch {
background-color: #FF9800;
color: white;
padding: 8px 16px;
border-radius: 4px;
display: inline-block;
margin-bottom: 10px;
font-weight: bold;
}
.control-panel {
margin-top: 20px;
padding: 15px;
background: #f9f9f9;
border-radius: 4px;
border: 1px solid #ddd;
}
.control-panel input {
margin-right: 10px;
margin-bottom: 10px;
}
.branch-list, .checkpoint-list {
margin-top: 15px;
}
.branch-item, .checkpoint-item {
padding: 10px;
margin: 5px 0;
background: #f9f9f9;
border-radius: 4px;
border-left: 3px solid #2196F3;
}
.stats {
background: #E3F2FD;
padding: 15px;
border-radius: 4px;
margin-bottom: 15px;
}
.stats-item {
margin: 5px 0;
font-size: 14px;
}
</style>
</head>
<body>
<h1>🌿 Context Branching Chat Demo</h1>
<div class="container">
<div class="chat-panel">
<div class="current-branch">Current Branch: <span id="current-branch">main</span></div>
<div class="messages" id="messages"></div>
<div class="input-area">
<input type="text" id="message-input" placeholder="Type a message..." />
<button onclick="sendMessage()">Send</button>
</div>
<div class="control-panel">
<h3>Branch Controls</h3>
<input type="text" id="checkpoint-name" placeholder="Checkpoint name" />
<button onclick="createCheckpoint()">Create Checkpoint</button>
<br/>
<input type="text" id="branch-name" placeholder="Branch name" />
<button onclick="createBranch()">Create Branch</button>
</div>
</div>
<div class="sidebar">
<div class="stats" id="stats">
<h3>Workspace Stats</h3>
<div class="stats-item">Branches: <span id="stat-branches">1</span></div>
<div class="stats-item">Checkpoints: <span id="stat-checkpoints">0</span></div>
<div class="stats-item">Messages: <span id="stat-messages">0</span></div>
</div>
<h3>Branches</h3>
<div class="branch-list" id="branches"></div>
<h3>Checkpoints</h3>
<div class="checkpoint-list" id="checkpoints"></div>
</div>
</div>
<script>
const sessionId = 'web_' + Date.now();
// Initialize workspace
fetch('/api/workspace/create', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({session_id: sessionId})
});
function sendMessage() {
const input = document.getElementById('message-input');
const message = input.value.trim();
if (!message) return;
// Display user message immediately
addMessageToUI('user', message);
input.value = '';
// Send to server and get LLM response
fetch(`/api/workspace/${sessionId}/message`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({role: 'user', content: message, get_response: true})
})
.then(response => response.json())
.then(data => {
if (data.response) {
// Real LLM response
addMessageToUI('assistant', data.response);
} else if (data.llm === false) {
// Demo mode fallback
const demoResponse = `[Demo Mode] Received: "${message.substring(0, 50)}..."\n(Set API key for real responses)`;
addMessageToUI('assistant', demoResponse);
fetch(`/api/workspace/${sessionId}/message`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({role: 'assistant', content: demoResponse})
});
}
updateUI();
})
.catch(error => {
console.error('Error:', error);
addMessageToUI('system', 'Error sending message');
});
}
function addMessageToUI(role, content) {
const messagesDiv = document.getElementById('messages');
const messageDiv = document.createElement('div');
messageDiv.className = `message ${role}-message`;
messageDiv.innerHTML = `<strong>${role}:</strong> ${content}`;
messagesDiv.appendChild(messageDiv);
messagesDiv.scrollTop = messagesDiv.scrollHeight;
}
function createCheckpoint() {
const name = document.getElementById('checkpoint-name').value.trim();
if (!name) {
alert('Please enter a checkpoint name');
return;
}
fetch(`/api/workspace/${sessionId}/checkpoint`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({name: name})
})
.then(response => response.json())
.then(data => {
alert(`Checkpoint created: ${data.checkpoint_id.substring(0, 8)}...`);
document.getElementById('checkpoint-name').value = '';
updateUI();
});
}
function createBranch() {
const name = document.getElementById('branch-name').value.trim();
if (!name) {
alert('Please enter a branch name');
return;
}
fetch(`/api/workspace/${sessionId}/branch`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({name: name})
})
.then(response => response.json())
.then(data => {
if (data.error) {
alert(data.error);
} else {
document.getElementById('branch-name').value = '';
switchBranch(name);
}
});
}
function switchBranch(branchName) {
fetch(`/api/workspace/${sessionId}/switch`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({branch: branchName})
})
.then(response => response.json())
.then(data => {
document.getElementById('current-branch').textContent = branchName;
updateUI();
});
}
function updateUI() {
// Update stats
fetch(`/api/workspace/${sessionId}/stats`)
.then(response => response.json())
.then(stats => {
document.getElementById('stat-branches').textContent = stats.total_branches;
document.getElementById('stat-checkpoints').textContent = stats.total_checkpoints;
document.getElementById('stat-messages').textContent = stats.total_messages;
});
// Update branches list
fetch(`/api/workspace/${sessionId}/branches`)
.then(response => response.json())
.then(branches => {
const branchesDiv = document.getElementById('branches');
branchesDiv.innerHTML = '';
branches.forEach(branch => {
const div = document.createElement('div');
div.className = 'branch-item';
div.innerHTML = `
<strong>${branch.name}</strong><br/>
Messages: ${branch.message_count}
<button class="branch-button" onclick="switchBranch('${branch.name}')">Switch</button>
`;
branchesDiv.appendChild(div);
});
});
// Update checkpoints list
fetch(`/api/workspace/${sessionId}/checkpoints`)
.then(response => response.json())
.then(checkpoints => {
const checkpointsDiv = document.getElementById('checkpoints');
checkpointsDiv.innerHTML = '';
checkpoints.forEach(cp => {
const div = document.createElement('div');
div.className = 'checkpoint-item';
div.innerHTML = `
<strong>${cp.name}</strong><br/>
ID: ${cp.id}...<br/>
Messages: ${cp.message_count}
`;
checkpointsDiv.appendChild(div);
});
});
}
// Allow Enter key to send message
document.getElementById('message-input').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
sendMessage();
}
});
// Update UI on load
setTimeout(updateUI, 500);
</script>
</body>
</html>
"""
@app.route('/')
def index():
"""Serve the main chat interface."""
return render_template_string(HTML_TEMPLATE)
@app.route('/api/workspace/create', methods=['POST'])
def create_workspace():
"""Create a new workspace."""
data = request.json
session_id = data.get('session_id')
if not session_id:
return jsonify({"error": "session_id required"}), 400
workspace = sdk.create_workspace(session_id)
return jsonify({"session_id": session_id, "status": "created"})
@app.route('/api/workspace/<session_id>/message', methods=['POST'])
def add_message(session_id):
"""Add a message to the workspace."""
data = request.json
role = data.get('role', 'user')
content = data.get('content', '')
get_llm_response = data.get('get_response', False)
try:
workspace = sdk.load_workspace(session_id)
if role == 'user' and get_llm_response and llm_client:
# Get LLM response
try:
response = llm_client.chat_with_workspace(workspace, content)
return jsonify({"status": "ok", "response": response, "llm": True})
except Exception as e:
# Fallback to manual mode if LLM fails
workspace.add_message(Message(role=role, content=content))
return jsonify({"status": "ok", "error": str(e), "llm": False})
else:
# Just add the message without LLM response
workspace.add_message(Message(role=role, content=content))
return jsonify({"status": "ok", "llm": LLM_AVAILABLE})
except Exception as e:
return jsonify({"error": str(e)}), 400
@app.route('/api/workspace/<session_id>/messages', methods=['GET'])
def get_messages(session_id):
"""Get current context messages."""
try:
workspace = sdk.load_workspace(session_id)
context = workspace.get_current_context()
return jsonify({
"messages": [
{"role": msg.role, "content": msg.content}
for msg in context
]
})
except Exception as e:
return jsonify({"error": str(e)}), 400
@app.route('/api/workspace/<session_id>/checkpoint', methods=['POST'])
def create_checkpoint(session_id):
"""Create a checkpoint."""
data = request.json
name = data.get('name', 'checkpoint')
try:
workspace = sdk.load_workspace(session_id)
checkpoint_id = workspace.create_checkpoint(name)
return jsonify({"checkpoint_id": checkpoint_id})
except Exception as e:
return jsonify({"error": str(e)}), 400
@app.route('/api/workspace/<session_id>/branch', methods=['POST'])
def create_branch(session_id):
"""Create a new branch."""
data = request.json
name = data.get('name')
try:
workspace = sdk.load_workspace(session_id)
# Get most recent checkpoint
checkpoints = workspace.list_checkpoints()
if not checkpoints:
return jsonify({"error": "No checkpoints available. Create a checkpoint first."}), 400
checkpoint_id = checkpoints[-1]['full_id']
workspace.create_branch(checkpoint_id, name)
return jsonify({"status": "ok", "branch": name})
except Exception as e:
return jsonify({"error": str(e)}), 400
@app.route('/api/workspace/<session_id>/switch', methods=['POST'])
def switch_branch(session_id):
"""Switch to a branch."""
data = request.json
branch = data.get('branch')
try:
workspace = sdk.load_workspace(session_id)
workspace.switch_branch(branch)
return jsonify({"status": "ok", "current_branch": branch})
except Exception as e:
return jsonify({"error": str(e)}), 400
@app.route('/api/workspace/<session_id>/branches', methods=['GET'])
def list_branches(session_id):
"""List all branches."""
try:
workspace = sdk.load_workspace(session_id)
branches = workspace.list_branches()
return jsonify(branches)
except Exception as e:
return jsonify({"error": str(e)}), 400
@app.route('/api/workspace/<session_id>/checkpoints', methods=['GET'])
def list_checkpoints(session_id):
"""List all checkpoints."""
try:
workspace = sdk.load_workspace(session_id)
checkpoints = workspace.list_checkpoints()
return jsonify(checkpoints)
except Exception as e:
return jsonify({"error": str(e)}), 400
@app.route('/api/workspace/<session_id>/stats', methods=['GET'])
def get_stats(session_id):
"""Get workspace statistics."""
try:
workspace = sdk.load_workspace(session_id)
stats = workspace.get_statistics()
return jsonify(stats)
except Exception as e:
return jsonify({"error": str(e)}), 400
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(description="Web Chat App with Context Branching")
parser.add_argument(
"--port",
type=int,
default=5050,
help="Port to run server on (default: 5000)"
)
parser.add_argument(
"--storage-path",
default="./app_data",
help="Storage path (default: ./app_data)"
)
parser.add_argument(
"--debug",
action="store_true",
help="Run in debug mode"
)
args = parser.parse_args()
# Initialize SDK globally
global sdk
sdk = ContextBranchingSDK(
storage_backend="file",
storage_path=args.storage_path
)
print(f"\n🌿 Context Branching Web Chat")
print(f"=" * 50)
print(f"Server running on http://localhost:{args.port}")
print(f"Storage path: {args.storage_path}")
print(f"=" * 50)
print()
app.run(host='0.0.0.0', port=args.port, debug=args.debug)
if __name__ == "__main__":
main()