-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
3196 lines (2679 loc) · 120 KB
/
Copy pathmain.py
File metadata and controls
3196 lines (2679 loc) · 120 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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import logging
import os
import re
import subprocess
import sys
import uuid
from datetime import datetime
from pathlib import Path
from logging.handlers import RotatingFileHandler
from typing import AsyncGenerator, Any, Optional
import shutil
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
from fastapi.staticfiles import StaticFiles
from openai import AsyncOpenAI
from pydantic import BaseModel
import uvicorn
import asyncio
load_dotenv()
# =============================================================================
# SCHEMA STORE - 本地存储管理
# =============================================================================
SCHEMA_STORE_DIR = Path(__file__).parent / "schema_store"
SCHEMA_STORE_DIR.mkdir(exist_ok=True)
class SchemaStore:
"""
管理 UI Schema 的本地存储,支持分片存储和递归生成。
增强功能:
- $ref 引用机制: 骨架中使用引用指向分片
- 上下文压缩: 为 LLM 提供精简的上下文摘要
- 增量加载: 支持按需加载和合并分片
- 依赖追踪: 追踪分片之间的依赖关系
目录结构:
schema_store/
├── {session_id}/
│ ├── session.json # 会话元数据
│ ├── skeleton.json # 主骨架结构 (含 $ref 引用)
│ ├── skeleton_refs.json # 骨架引用版本 (用于增量加载)
│ ├── fragments/ # 分片存储
│ │ ├── {fragment_id}.json
│ │ └── ...
│ ├── context/ # 上下文摘要
│ │ └── summary.json # 压缩的上下文信息
│ └── merged.json # 最终合并结果
"""
def __init__(self, session_id: str):
self.session_id = session_id
self.session_dir = SCHEMA_STORE_DIR / session_id
self.fragments_dir = self.session_dir / "fragments"
self.context_dir = self.session_dir / "context"
self._ensure_dirs()
self._fragment_index: dict[str, dict] = {} # 内存中的分片索引
def _ensure_dirs(self):
"""确保目录存在"""
self.session_dir.mkdir(parents=True, exist_ok=True)
self.fragments_dir.mkdir(exist_ok=True)
self.context_dir.mkdir(exist_ok=True)
def save_session_meta(self, meta: dict):
"""保存会话元数据"""
meta["updated_at"] = datetime.now().isoformat()
with open(self.session_dir / "session.json", "w", encoding="utf-8") as f:
json.dump(meta, f, ensure_ascii=False, indent=2)
def load_session_meta(self) -> dict | None:
"""加载会话元数据"""
path = self.session_dir / "session.json"
if path.exists():
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
return None
def save_skeleton(self, skeleton: dict):
"""保存主骨架"""
with open(self.session_dir / "skeleton.json", "w", encoding="utf-8") as f:
json.dump(skeleton, f, ensure_ascii=False, indent=2)
def load_skeleton(self) -> dict | None:
"""加载主骨架"""
path = self.session_dir / "skeleton.json"
if path.exists():
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
return None
def save_skeleton_with_refs(self, skeleton: dict):
"""
保存带有 $ref 引用的骨架版本
将 $placeholder 转换为 $ref 引用,便于增量加载
"""
skeleton_refs = self._convert_placeholders_to_refs(skeleton)
with open(self.session_dir / "skeleton_refs.json", "w", encoding="utf-8") as f:
json.dump(skeleton_refs, f, ensure_ascii=False, indent=2)
return skeleton_refs
def load_skeleton_with_refs(self) -> dict | None:
"""加载带引用的骨架"""
path = self.session_dir / "skeleton_refs.json"
if path.exists():
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
return None
def _convert_placeholders_to_refs(self, schema: dict) -> dict:
"""将 $placeholder 转换为 $ref 引用"""
if not isinstance(schema, dict):
return schema
result = {}
for key, value in schema.items():
if key == "$placeholder":
# 转换为 $ref 引用
result["$ref"] = f"#/fragments/{value}"
elif key == "children" and isinstance(value, list):
result[key] = [self._convert_placeholders_to_refs(child) if isinstance(child, dict) else child for child in value]
elif isinstance(value, dict):
result[key] = self._convert_placeholders_to_refs(value)
else:
result[key] = value
return result
def save_fragment(self, fragment_id: str, fragment: dict, meta: dict = None):
"""
保存一个 schema 分片
Args:
fragment_id: 分片ID (通常是 placeholder_id)
fragment: 分片内容
meta: 分片元数据 (深度、父节点、依赖等)
"""
# 生成分片摘要用于上下文
summary = self._generate_fragment_summary(fragment)
fragment_data = {
"id": fragment_id,
"content": fragment,
"summary": summary,
"meta": meta or {},
"created_at": datetime.now().isoformat()
}
with open(self.fragments_dir / f"{fragment_id}.json", "w", encoding="utf-8") as f:
json.dump(fragment_data, f, ensure_ascii=False, indent=2)
# 更新内存索引
self._fragment_index[fragment_id] = {
"summary": summary,
"meta": meta or {},
"has_refs": self._has_nested_refs(fragment)
}
# 更新上下文摘要
self._update_context_summary()
def _generate_fragment_summary(self, fragment: dict, max_depth: int = 2) -> dict:
"""
生成分片的结构摘要,用于上下文压缩
只保留类型、关键属性和子组件类型
"""
if not isinstance(fragment, dict):
return {"type": "text", "preview": str(fragment)[:50]}
summary = {
"type": fragment.get("type", "unknown"),
"props_keys": list(fragment.get("props", {}).keys())[:5],
}
children = fragment.get("children", [])
if isinstance(children, str):
summary["children_type"] = "text"
summary["children_preview"] = children[:30] + "..." if len(children) > 30 else children
elif isinstance(children, list):
summary["children_type"] = "array"
summary["children_count"] = len(children)
if max_depth > 0:
summary["children_types"] = [
self._generate_fragment_summary(c, max_depth - 1).get("type", "?")
if isinstance(c, dict) else "text"
for c in children[:5]
]
# 检查是否有嵌套的 placeholder
if self._has_nested_refs(fragment):
summary["has_nested_refs"] = True
return summary
def _has_nested_refs(self, schema: dict) -> bool:
"""检查 schema 中是否有嵌套的 $placeholder 或 $ref"""
if not isinstance(schema, dict):
return False
if "$placeholder" in schema or "$ref" in schema:
return True
for value in schema.values():
if isinstance(value, dict) and self._has_nested_refs(value):
return True
elif isinstance(value, list):
for item in value:
if isinstance(item, dict) and self._has_nested_refs(item):
return True
return False
def _update_context_summary(self):
"""更新上下文摘要文件"""
summary = {
"session_id": self.session_id,
"updated_at": datetime.now().isoformat(),
"fragment_count": len(self._fragment_index),
"fragments": {}
}
for fid, info in self._fragment_index.items():
summary["fragments"][fid] = {
"summary": info["summary"],
"depth": info["meta"].get("depth", 0),
"has_refs": info["has_refs"]
}
with open(self.context_dir / "summary.json", "w", encoding="utf-8") as f:
json.dump(summary, f, ensure_ascii=False, indent=2)
def load_fragment(self, fragment_id: str) -> dict | None:
"""加载一个分片"""
path = self.fragments_dir / f"{fragment_id}.json"
if path.exists():
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
return None
def list_fragments(self) -> list[str]:
"""列出所有分片ID"""
return [f.stem for f in self.fragments_dir.glob("*.json")]
def get_fragments_by_depth(self, depth: int) -> list[dict]:
"""获取指定深度的所有分片"""
fragments = []
for fid in self.list_fragments():
frag = self.load_fragment(fid)
if frag and frag.get("meta", {}).get("depth") == depth:
fragments.append(frag)
return fragments
def save_merged(self, schema: dict):
"""保存最终合并的 schema"""
with open(self.session_dir / "merged.json", "w", encoding="utf-8") as f:
json.dump(schema, f, ensure_ascii=False, indent=2)
def load_merged(self) -> dict | None:
"""加载合并后的 schema"""
path = self.session_dir / "merged.json"
if path.exists():
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
return None
def resolve_refs(self, schema: dict) -> dict:
"""
解析 schema 中的 $ref 引用,返回完整的 schema
支持递归解析嵌套引用
"""
if not isinstance(schema, dict):
return schema
# 如果是 $ref 引用,加载对应分片
if "$ref" in schema:
ref_path = schema["$ref"]
if ref_path.startswith("#/fragments/"):
fragment_id = ref_path.replace("#/fragments/", "")
frag = self.load_fragment(fragment_id)
if frag and frag.get("content"):
# 递归解析分片中的引用
return self.resolve_refs(frag["content"])
return schema
# 递归处理子节点
result = {}
for key, value in schema.items():
if key == "children" and isinstance(value, list):
result[key] = [self.resolve_refs(child) if isinstance(child, dict) else child for child in value]
elif isinstance(value, dict):
result[key] = self.resolve_refs(value)
else:
result[key] = value
return result
def get_context_summary(self, max_fragments: int = 5) -> str:
"""
获取上下文摘要,用于传递给 LLM
只包含最近的几个分片的类型和结构,不包含完整内容
"""
fragments = []
for fid in self.list_fragments()[-max_fragments:]:
frag = self.load_fragment(fid)
if frag and frag.get("content"):
content = frag["content"]
# 只提取类型和顶层结构
summary = self._summarize_schema(content, max_depth=2)
fragments.append(f"- {fid}: {summary}")
return "\n".join(fragments) if fragments else "No fragments yet"
def get_compressed_context(self, max_tokens: int = 2000) -> dict:
"""
获取压缩的上下文信息,用于传递给 LLM
包含骨架结构摘要和已完成分片的类型信息
Args:
max_tokens: 估算的最大 token 数
Returns:
压缩的上下文字典
"""
context = {
"session_id": self.session_id,
"skeleton_structure": None,
"completed_fragments": [],
"pending_refs": []
}
# 加载骨架摘要
skeleton = self.load_skeleton()
if skeleton:
context["skeleton_structure"] = self._summarize_schema(skeleton, max_depth=3)
# 加载分片摘要
context_file = self.context_dir / "summary.json"
if context_file.exists():
with open(context_file, "r", encoding="utf-8") as f:
summary_data = json.load(f)
for fid, info in summary_data.get("fragments", {}).items():
context["completed_fragments"].append({
"id": fid,
"type": info["summary"].get("type"),
"depth": info.get("depth", 0)
})
if info.get("has_refs"):
context["pending_refs"].append(fid)
return context
def _summarize_schema(self, schema: dict, depth: int = 0, max_depth: int = 2) -> str:
"""生成 schema 的简短摘要"""
if depth > max_depth or not isinstance(schema, dict):
return "..."
comp_type = schema.get("type", "unknown")
children = schema.get("children", [])
if isinstance(children, str):
return f"{comp_type}(\"{children[:20]}...\")" if len(children) > 20 else f"{comp_type}(\"{children}\")"
elif isinstance(children, list) and children:
child_types = [c.get("type", "?") if isinstance(c, dict) else "text" for c in children[:3]]
suffix = f"+{len(children)-3}" if len(children) > 3 else ""
return f"{comp_type}[{', '.join(child_types)}{suffix}]"
else:
return comp_type
@classmethod
def list_sessions(cls) -> list[dict]:
"""列出所有会话"""
sessions = []
for session_dir in SCHEMA_STORE_DIR.iterdir():
if session_dir.is_dir():
meta_path = session_dir / "session.json"
if meta_path.exists():
with open(meta_path, "r", encoding="utf-8") as f:
meta = json.load(f)
meta["session_id"] = session_dir.name
sessions.append(meta)
return sorted(sessions, key=lambda x: x.get("updated_at", ""), reverse=True)
@classmethod
def delete_session(cls, session_id: str):
"""删除会话"""
session_dir = SCHEMA_STORE_DIR / session_id
if session_dir.exists():
shutil.rmtree(session_dir)
# =============================================================================
# LOGGING CONFIGURATION
# =============================================================================
LOG_DIR = Path(__file__).parent / "logs"
LOG_DIR.mkdir(exist_ok=True)
# Get log level from environment variable (default: INFO for console, DEBUG for file)
# Options: DEBUG, INFO, WARNING, ERROR
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO").upper()
LOG_LEVEL_NUM = getattr(logging, LOG_LEVEL, logging.INFO)
# Create formatters
detailed_formatter = logging.Formatter(
'%(asctime)s | %(levelname)-8s | %(name)-20s | %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
console_formatter = logging.Formatter(
'%(asctime)s | %(levelname)-8s | %(message)s',
datefmt='%H:%M:%S'
)
# Root logger setup
root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG)
# Console handler (level from env var)
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(LOG_LEVEL_NUM)
console_handler.setFormatter(console_formatter)
root_logger.addHandler(console_handler)
# File handler for all logs (DEBUG level, rotating)
all_log_file = LOG_DIR / "realtimeui.log"
file_handler = RotatingFileHandler(
all_log_file,
maxBytes=10 * 1024 * 1024, # 10MB
backupCount=5,
encoding='utf-8'
)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(detailed_formatter)
root_logger.addHandler(file_handler)
# Separate file for LLM interactions (for analysis)
llm_log_file = LOG_DIR / "llm_calls.log"
llm_handler = RotatingFileHandler(
llm_log_file,
maxBytes=50 * 1024 * 1024, # 50MB (LLM logs can be large)
backupCount=10,
encoding='utf-8'
)
llm_handler.setLevel(logging.DEBUG)
llm_handler.setFormatter(detailed_formatter)
# Create loggers
logger = logging.getLogger("realtimeui")
llm_logger = logging.getLogger("realtimeui.llm")
llm_logger.addHandler(llm_handler)
agent_logger = logging.getLogger("realtimeui.agent")
# Reduce noise from third-party libraries
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING)
logging.getLogger("openai").setLevel(logging.WARNING)
logging.getLogger("uvicorn.access").setLevel(logging.WARNING)
logger.info(f"Log level: {LOG_LEVEL} (console), DEBUG (file)")
logger.info(f"Log files: {LOG_DIR}")
app = FastAPI(title="RealtimeUI API", version="0.1.0")
# Check if running in production mode (serving static files)
FRONTEND_DIR = Path(__file__).parent / "frontend"
DIST_DIR = FRONTEND_DIR / "dist"
IS_PRODUCTION = DIST_DIR.exists() and (DIST_DIR / "index.html").exists()
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:5173", "http://localhost:8000"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
client = AsyncOpenAI(
api_key=os.getenv("OPENAI_API_KEY"),
base_url=os.getenv("OPENAI_BASE_URL"),
)
MODEL = os.getenv("OPENAI_MODEL", "qwen3-max")
# Support multiple models for parallel agents
# Format: comma-separated list of models, e.g., "qwen3-max,qwen-plus,qwen-turbo"
EXPANSION_MODELS = os.getenv("EXPANSION_MODELS", "").split(",") if os.getenv("EXPANSION_MODELS") else []
EXPANSION_MODELS = [m.strip() for m in EXPANSION_MODELS if m.strip()]
# If no expansion models specified, use the main model
if not EXPANSION_MODELS:
EXPANSION_MODELS = [MODEL]
logger.info(f"Main model: {MODEL}")
logger.info(f"Expansion models: {EXPANSION_MODELS}")
COMPONENTS_DIR = Path(__file__).parent / "components"
# =============================================================================
# HIERARCHICAL UI GENERATION (分层生成)
# =============================================================================
# Multi-Agent Architecture:
#
# 1. SkeletonAgent (架构 Agent)
# - Generates high-level structure with $placeholder markers
# - Only creates the skeleton, no actual content
# - Fast, small context window usage
#
# 2. ExpansionAgent (展开 Agent) - Multiple instances run in parallel
# - Each agent expands one placeholder
# - Isolated context per agent
# - Streams results back to orchestrator
#
# 3. Orchestrator (协调器)
# - Manages agent lifecycle
# - Collects results via event queue
# - Merges expanded content into final schema
#
# Benefits:
# - True parallel execution
# - Context isolation per agent
# - Progressive rendering
# - Failure isolation
# =============================================================================
import asyncio
from asyncio import Queue as AsyncQueue
from dataclasses import dataclass
from typing import AsyncGenerator, Any
from abc import ABC, abstractmethod
@dataclass
class AgentEvent:
"""Event emitted by an agent."""
agent_id: str
event_type: str
data: dict
class BaseAgent(ABC):
"""Base class for all agents."""
def __init__(self, agent_id: str, client: AsyncOpenAI, model: str):
self.agent_id = agent_id
self.client = client
self.model = model
@abstractmethod
async def run(self) -> AsyncGenerator[AgentEvent, None]:
"""Run the agent and yield events."""
pass
class SkeletonAgent(BaseAgent):
"""Agent that generates the UI skeleton structure with placeholders."""
SYSTEM_PROMPT = """You are a UI architect agent. Generate a HIGH-LEVEL skeleton structure for complex UIs.
## CRITICAL: Close-First-Then-Fill Principle (先闭合再填充)
You MUST follow this generation order:
1. First output the complete CLOSED structure (all brackets matched)
2. Use $placeholder markers for content that will be filled later
3. NEVER leave brackets unclosed - always complete the structure first
## Your Role
You are the ARCHITECTURE agent. Your job is to:
1. Understand the overall UI requirements
2. Design the high-level structure with COMPLETE, CLOSED JSON
3. Mark complex sections with $placeholder for other agents to expand
## Output Format
Return a COMPLETE, CLOSED JSON object with $placeholder markers:
{{
"type": "ComponentName",
"props": {{ }},
"children": [
{{
"$placeholder": "unique_id",
"$description": "Detailed description for the expansion agent"
}}
]
}}
## Generation Order (IMPORTANT!)
1. First write the opening braces and type
2. Then write props (can be empty {{}})
3. Then write children array with placeholders
4. CLOSE all brackets before moving to next sibling
5. Each placeholder should be a complete, closed object
## Rules
1. Use $placeholder for sections that need detailed content (3+ components)
2. Simple elements (single Text, Button, etc.) can be inline
3. Each $placeholder must have a unique id and clear $description
4. $description should be detailed enough for another agent to implement
5. Keep the skeleton shallow (max 2-3 levels before placeholder)
6. IMPORTANT: For sidebar navigation, ALWAYS use Tabs with orientation="vertical"
## Available Layout Components
- Row: Horizontal container. Props: gap ("sm"|"md"|"lg")
- Col: Vertical container. Props: gap ("sm"|"md"|"lg")
- Card, CardHeader, CardContent, CardFooter: Card sections
- Tabs: Tab container with switchable content. Props: defaultValue (required), orientation ("horizontal"|"vertical")
- TabsList: Container for tab triggers
- TabsTrigger: Clickable tab button. Props: value (required)
- TabsContent: Content panel. Props: value (required)
## CRITICAL: Sidebar Navigation Pattern
For ANY UI with sidebar navigation, you MUST use Tabs with vertical orientation:
{{
"type": "Tabs",
"props": {{"defaultValue": "first_tab", "orientation": "vertical"}},
"children": [
{{"type": "TabsList", "children": [
{{"type": "TabsTrigger", "props": {{"value": "tab1"}}, "children": "Tab 1"}},
{{"type": "TabsTrigger", "props": {{"value": "tab2"}}, "children": "Tab 2"}}
]}},
{{"type": "TabsContent", "props": {{"value": "tab1"}}, "children": [{{"$placeholder": "...", "$description": "..."}}]}},
{{"type": "TabsContent", "props": {{"value": "tab2"}}, "children": [{{"$placeholder": "...", "$description": "..."}}]}}
]
}}
## Example
User: "Create a dashboard with sidebar navigation, stats cards, and data table"
{{
"type": "Tabs",
"props": {{"defaultValue": "overview", "orientation": "vertical"}},
"children": [
{{"type": "TabsList", "children": [
{{"type": "TabsTrigger", "props": {{"value": "overview"}}, "children": "Overview"}},
{{"type": "TabsTrigger", "props": {{"value": "orders"}}, "children": "Orders"}},
{{"type": "TabsTrigger", "props": {{"value": "products"}}, "children": "Products"}}
]}},
{{"type": "TabsContent", "props": {{"value": "overview"}}, "children": [
{{
"$placeholder": "stats_section",
"$description": "Statistics cards showing key metrics: total revenue, total orders, total customers, conversion rate. Each card should have title, value, trend indicator."
}},
{{
"$placeholder": "recent_orders_table",
"$description": "Table showing recent orders with columns: Order ID, Customer, Status (badge), Amount, Date. Show 5 sample rows."
}}
]}},
{{"type": "TabsContent", "props": {{"value": "orders"}}, "children": [
{{
"$placeholder": "orders_content",
"$description": "Full orders management view with search input, filter dropdown, and orders table."
}}
]}},
{{"type": "TabsContent", "props": {{"value": "products"}}, "children": [
{{
"$placeholder": "products_content",
"$description": "Products management view with product grid or table."
}}
]}}
]
}}
Now generate the skeleton for the user's request. Output ONLY the JSON."""
def __init__(self, agent_id: str, client: AsyncOpenAI, model: str, prompt: str):
super().__init__(agent_id, client, model)
self.prompt = prompt
async def run(self) -> AsyncGenerator[AgentEvent, None]:
"""Generate skeleton structure with streaming."""
import time
start_time = time.time()
agent_logger.info(f"SkeletonAgent STARTED | prompt_length={len(self.prompt)}")
yield AgentEvent(self.agent_id, "start", {"message": "SkeletonAgent starting..."})
messages = [
{"role": "system", "content": self.SYSTEM_PROMPT},
{"role": "user", "content": self.prompt}
]
# Log full prompt to LLM
llm_logger.info(f"LLM_REQUEST | agent={self.agent_id} | model={self.model}")
llm_logger.debug(f"LLM_SYSTEM_PROMPT | agent={self.agent_id} | length={len(self.SYSTEM_PROMPT)}")
llm_logger.debug(f"LLM_SYSTEM_PROMPT_CONTENT | agent={self.agent_id} |\n{self.SYSTEM_PROMPT[:2000]}...")
llm_logger.info(f"LLM_USER_PROMPT | agent={self.agent_id} | prompt={self.prompt}")
try:
stream = await self.client.chat.completions.create(
model=self.model,
messages=messages,
temperature=0.7,
stream=True,
)
full_content = ""
token_count = 0
async for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
token = chunk.choices[0].delta.content
full_content += token
token_count += 1
# Log every 50 tokens for progress tracking
if token_count % 50 == 0:
elapsed = time.time() - start_time
agent_logger.debug(f"SkeletonAgent: {token_count} tokens ({elapsed:.1f}s)")
# Try to parse partial JSON
parsed = parse_partial_json(full_content)
yield AgentEvent(self.agent_id, "token", {
"token": token,
"full": full_content,
"parsed": parsed
})
# Final parse
skeleton = parse_partial_json(full_content)
elapsed = time.time() - start_time
# Log complete LLM response
agent_logger.info(f"SkeletonAgent COMPLETED | tokens={token_count} | time={elapsed:.1f}s")
llm_logger.info(f"LLM_RESPONSE | agent={self.agent_id} | tokens={token_count} | time={elapsed:.1f}s")
llm_logger.info(f"LLM_OUTPUT_CONTENT | agent={self.agent_id} |\n{full_content}")
yield AgentEvent(self.agent_id, "complete", {
"skeleton": skeleton,
"raw": full_content
})
except Exception as e:
import traceback
agent_logger.error(f"SkeletonAgent ERROR: {e}")
agent_logger.error(traceback.format_exc())
llm_logger.error(f"LLM_ERROR | agent={self.agent_id} | error={e}")
yield AgentEvent(self.agent_id, "error", {"error": str(e)})
def create_openai_client():
"""Create a new AsyncOpenAI client instance."""
return AsyncOpenAI(
api_key=os.getenv("OPENAI_API_KEY"),
base_url=os.getenv("OPENAI_BASE_URL"),
)
class ExpansionAgent(BaseAgent):
"""Agent that expands a single placeholder into detailed UI components."""
SYSTEM_PROMPT = """You are a UI component expansion agent. Your job is to expand a placeholder into detailed UI components.
## CRITICAL: Close-First-Then-Fill Principle (先闭合再填充)
You MUST follow this generation order:
1. First output the COMPLETE CLOSED structure (all brackets matched)
2. Fill in content values AFTER the structure is complete
3. NEVER leave brackets unclosed - always complete each object/array before starting the next
## Generation Order (IMPORTANT!)
When generating JSON, follow this exact order:
1. Open the root object {{
2. Write "type": "..."
3. Write "props": {{...}} (complete and close it)
4. Write "children": [ and for each child:
a. Open child {{
b. Write all properties
c. Close child }}
d. Add comma if not last
5. Close children ]
6. Close root }}
## Your Role
You are an EXPANSION agent. Another agent has created the overall UI structure and marked a section for you to implement.
## Context
- Overall UI purpose: {overall_purpose}
- Section to expand: {placeholder_id}
- Section description: {placeholder_description}
- Current depth: {current_depth} / Max depth: {max_depth}
- Context summary: {context_summary}
## Output Format
Return ONLY a valid, COMPLETE, CLOSED JSON object (the expanded UI section):
{{
"type": "ComponentName",
"props": {{ }},
"children": [ ]
}}
## Recursive Expansion (IMPORTANT!)
If a section is too complex to fully implement (e.g., a complete sub-page, complex form, detailed dashboard section),
you can use $placeholder markers for further expansion:
{{
"$placeholder": "unique_sub_id",
"$description": "Detailed description of what this sub-section should contain"
}}
Rules for using $placeholder:
1. Only use if the section would require 10+ components to implement fully
2. Give each placeholder a unique, descriptive ID
3. Provide detailed $description for the next agent
4. Current depth is {current_depth}, max is {max_depth}. If depth >= max_depth, do NOT use placeholders.
## Available Components
### Layout
- Col: Vertical container. Props: gap ("sm"|"md"|"lg"), align, justify
- Row: Horizontal container. Props: gap, align, justify, wrap
- Card, CardHeader, CardContent, CardFooter, CardTitle, CardDescription
### Navigation
- Tabs: Tab container. Props: defaultValue (required), orientation ("horizontal"|"vertical")
- TabsList: Container for tab triggers
- TabsTrigger: Tab button. Props: value (required)
- TabsContent: Tab panel. Props: value (required)
### Basic
- Text: Props: as ("p"|"h1"|"h2"|"h3"), variant ("default"|"muted"), size ("sm"|"base"|"lg"|"xl"|"2xl")
- Button: Props: variant ("default"|"outline"|"secondary"|"destructive"|"ghost"), size ("sm"|"default"|"lg")
- Badge: Props: variant ("default"|"secondary"|"destructive"|"success"|"warning")
- Avatar: Props: src, alt, fallback, size ("sm"|"default"|"lg")
- Separator: Props: orientation ("horizontal"|"vertical")
### Form
- Input: Props: placeholder, type ("text"|"email"|"password"|"number")
- Textarea: Props: placeholder, rows
- Select, SelectTrigger, SelectValue, SelectContent, SelectItem
- Checkbox: Props: label, description
- Switch: Props: label, description
- Label: Form label
- Slider: Props: min, max, step
### Feedback
- Alert: Props: variant ("default"|"info"|"success"|"warning"|"destructive"), title
- Progress: Props: value (0-100), showValue, label
### Data
- Table, TableHeader, TableBody, TableRow, TableHead, TableCell
- Statistic: Props: title, value, prefix, suffix, trend ("up"|"down"|"neutral"), trendValue, description
### Charts
- LineChart, BarChart, PieChart, AreaChart: Props: data (array), xKey, yKey, title
Now expand the placeholder into detailed components. Output ONLY the JSON."""
def __init__(self, agent_id: str, client: AsyncOpenAI, model: str,
placeholder: dict, overall_purpose: str,
current_depth: int = 1, max_depth: int = 3,
context_summary: str = ""):
super().__init__(agent_id, client, model)
self.placeholder = placeholder
self.overall_purpose = overall_purpose
self.current_depth = current_depth
self.max_depth = max_depth
self.context_summary = context_summary
# Create a dedicated client for this agent
self.dedicated_client = create_openai_client()
async def run(self) -> AsyncGenerator[AgentEvent, None]:
"""Expand placeholder with streaming."""
import time
placeholder_id = self.placeholder["id"]
start_time = time.time()
agent_logger.info(f"ExpansionAgent STARTED: {placeholder_id} (depth={self.current_depth}/{self.max_depth})")
yield AgentEvent(self.agent_id, "start", {
"placeholder_id": placeholder_id,
"depth": self.current_depth,
"message": f"ExpansionAgent starting for {placeholder_id} (depth {self.current_depth})..."
})
prompt = self.SYSTEM_PROMPT.format(
overall_purpose=self.overall_purpose,
placeholder_id=placeholder_id,
placeholder_description=self.placeholder["description"],
current_depth=self.current_depth,
max_depth=self.max_depth,
context_summary=self.context_summary or "No previous context"
)
messages = [{"role": "user", "content": prompt}]
# Log full LLM request including prompt content
llm_logger.info(f"LLM_REQUEST | agent={self.agent_id} | model={self.model} | placeholder={placeholder_id}")
llm_logger.debug(f"LLM_PROMPT_LENGTH | agent={self.agent_id} | length={len(prompt)}")
llm_logger.info(f"LLM_PROMPT_CONTENT | agent={self.agent_id} | placeholder={placeholder_id} |\n{prompt}")
try:
agent_logger.debug(f"{placeholder_id}: Calling LLM API with model {self.model}")
stream = await self.dedicated_client.chat.completions.create(
model=self.model,
messages=messages,
temperature=0.7,
stream=True,
)
agent_logger.debug(f"{placeholder_id}: LLM stream created successfully")
full_content = ""
token_count = 0
async for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
token = chunk.choices[0].delta.content
full_content += token
token_count += 1
# Log every 50 tokens
if token_count % 50 == 0:
elapsed = time.time() - start_time
agent_logger.debug(f"{placeholder_id}: {token_count} tokens ({elapsed:.1f}s)")
# Try to parse partial JSON
parsed = parse_partial_json(full_content)
yield AgentEvent(self.agent_id, "token", {
"placeholder_id": placeholder_id,
"token": token,
"full": full_content,
"parsed": parsed
})
# Final parse
expanded = parse_partial_json(full_content)
elapsed = time.time() - start_time
agent_logger.info(f"ExpansionAgent COMPLETED: {placeholder_id} | tokens={token_count} | time={elapsed:.1f}s")
# Log complete LLM response content
llm_logger.info(f"LLM_RESPONSE | agent={self.agent_id} | placeholder={placeholder_id} | tokens={token_count} | time={elapsed:.1f}s")
llm_logger.info(f"LLM_OUTPUT_CONTENT | agent={self.agent_id} | placeholder={placeholder_id} |\n{full_content}")
yield AgentEvent(self.agent_id, "complete", {
"placeholder_id": placeholder_id,
"expanded": expanded,
"path": self.placeholder["path"],
"raw": full_content
})
except Exception as e:
import traceback
agent_logger.error(f"ExpansionAgent ERROR: {placeholder_id} - {e}")
agent_logger.error(traceback.format_exc())
llm_logger.error(f"LLM_ERROR | agent={self.agent_id} | placeholder={placeholder_id} | error={e}")
yield AgentEvent(self.agent_id, "error", {
"placeholder_id": placeholder_id,
"error": str(e)
})
class DataBindingAgent(BaseAgent):
"""Agent that binds data to UI components (Select options, Table data, Chart data, etc.)."""
SYSTEM_PROMPT = """You are a Data Binding agent. Your job is to analyze a UI schema and add realistic mock data to components that need it.
## Your Role
You receive a complete UI schema and must:
1. Find all components that need data (Select, Table, Chart, RadioGroup, etc.)
2. Generate realistic mock data based on the UI context
3. Return JSON Patch operations to add the data
## Components That Need Data
### Select / SelectContent
- Add SelectItem children with realistic options
- Example: For a "Status" filter, add options like "All", "Active", "Pending", "Completed"
### Table / TableBody
- Add TableRow children with realistic data
- Match the columns defined in TableHeader
- Generate 5-10 rows of sample data
### Charts (LineChart, BarChart, PieChart, AreaChart)
- Add "data" prop with array of data points
- Include appropriate keys (xKey, yKey values)
### RadioGroup
- Add RadioGroupItem children with value and label
### Checkbox groups
- Set appropriate default checked states
## Context
- Overall UI purpose: {overall_purpose}
- Current schema structure summary: {schema_summary}
## Output Format
Return ONLY a JSON array of patch operations:
[
{{"op": "add", "path": "/children/0/children/1/props/data", "value": [...]}},
{{"op": "replace", "path": "/children/2/children", "value": [...]}}
]
## Rules
1. Generate realistic data that matches the UI context (e.g., e-commerce data for e-commerce UI)
2. Use Chinese text for Chinese UIs, English for English UIs
3. Include 5-10 items for lists/tables
4. For charts, generate 6-12 data points
5. Make data look realistic (varied values, proper formats)
Now analyze the schema and generate data binding patches. Output ONLY the JSON array:"""
def __init__(self, agent_id: str, client: AsyncOpenAI, model: str,
schema: dict, overall_purpose: str):
super().__init__(agent_id, client, model)
self.schema = schema
self.overall_purpose = overall_purpose
self.dedicated_client = create_openai_client()
def _summarize_schema(self, schema: dict, depth: int = 0, max_depth: int = 3) -> str:
"""Create a summary of the schema structure for the prompt."""
if depth > max_depth: