Spaces:
Runtime error

File size: 42,143 Bytes
ce06eb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
# 数据指标建模助手 v3 - 系统架构设计文档

**版本**: v3.0  
**创建时间**: 2026-05-15  
**架构师**: 高见远 (Bob)  
**状态**: 待审核

---

# Part A: 系统设计方案

## 1. 实现方案

### 1.1 核心改造难点分析

基于需求文档 `requirements_optimized.md` 和现有代码评估,核心改造难点:

| 难点 | 描述 | 解决方案 |
|------|------|----------|
| **单指标 → 指标集** | 现有架构所有 Agent 输出单个指标,需改造为输出指标集(包含多个指标) | 重新设计数据结构为 `IndicatorSet`;Agent 输入输出改为指标集格式 |
| **文件上传与解析** | 需支持 Excel/CSV 上传、解析元数据、传递给 Requirement Agent | 新增 `utils/file_parser.py` 模块;使用 `pandas` + `openpyxl` 解析 |
| **树形结构展示** | Step 2 需树形复选框展示指标集 | 使用 Streamlit 嵌套布局 + `st.checkbox`;前端状态用 `st.session_state` 管理 |
| **新增 BI 设计 Agent** | 需新增 `BIDesignAgent` 生成可视化方案 | 新增 `agents/bi_design_agent.py`;复用现有 API 调用机制 |
| **批量建模生成** | ModelingAgent 需支持批量生成多个指标方案 | 改造 `ModelingAgent.run()` 支持指标列表输入;使用循环或并行处理 |

### 1.2 框架和库选型

| 组件 | 现有技术栈 | 选型决策 | 理由 |
|------|------------|----------|------|
| **Web 框架** | Streamlit 1.29 | ✅ 保留 | 快速原型、内置组件丰富、适合数据应用 |
| **数据处理** | Pandas | ✅ 保留 + 新增 openpyxl | Pandas 读 CSV;openpyxl 读 Excel |
| **向量数据库** | FAISS | ✅ 保留 | 本地部署,无需额外服务,适合小规模检索 |
| **Embedding** | sentence-transformers | ✅ 保留 | 多语言支持,轻量级 |
| **API 调用** | Requests + DeepSeek API | ✅ 保留 | 简单高效,满足需求 |
| **文件打包** | ZIP (标准库) | ✅ 保留 | 无需额外依赖 |
| **数据验证** | 无 | ✅ 新增 Pydantic | 用于数据结构验证(Indicator, IndicatorSet) |

**结论**:不需要引入新框架,现有栈 + 2 个新库(openpyxl, pydantic)即可满足需求。

### 1.3 架构模式

采用 **分层架构 + Agent 模式**:

```
┌──────────────────────────────────────────────┐
│           Streamlit UI Layer                │
│  - Step 1: 需求输入 + 文件上传           │
│  - Step 2: 指标树形选择                  │
│  - Step 3: 方案展示 + BI 设计 + 下载     │
└──────────────────────────────────────────────┘
                    ↓
┌──────────────────────────────────────────────┐
│         Agent Layer (智能体层)              │
│  - RequirementAgent: 需求理解 → 指标集    │
│  - RecommendationAgent: 推荐指标集         │
│  - ModelingAgent: 批量生成指标方案         │
│  - BIDesignAgent: 生成 BI 设计方案       │
└──────────────────────────────────────────────┘
                    ↓
┌──────────────────────────────────────────────┐
│         RAG Layer (检索增强)               │
│  - EmbeddingModel: 文本向量化             │
│  - VectorStore: 指标检索                  │
└──────────────────────────────────────────────┘
                    ↓
┌──────────────────────────────────────────────┐
│         Utils Layer (工具层)                │
│  - APIClient: API 调用                    │
│  - FileParser: 文件解析 (新增)            │
│  - FileGenerator: 文件生成                │
│  - ZipPackager: 打包下载                 │
│  - SQLValidator: SQL 验证                 │
└──────────────────────────────────────────────┘
```

**设计原则**:
- **模块化**:每层职责清晰,便于独立测试和替换
- **可扩展性**:新增 Agent 或工具不影响现有逻辑
- **向后兼容**:改造时保留现有接口,逐步迁移

---

## 2. 文件列表

### 2.1 完整文件结构(相对路径)

```
data_metrics_modeler/
├── app.py                           # 主入口 (Streamlit Web 应用) - 改造
├── config/
│   ├── __init__.py
│   ├── settings.py                  # 配置项 - 改造(新增文件上传配置)
│   └── prompts.py                  # Prompt 模板 - 改造(新增 BI 设计 Prompt)
├── models/                         # 新增目录
│   ├── __init__.py
│   ├── indicator.py                # Indicator 数据模型 (Pydantic)
│   └── indicator_set.py           # IndicatorSet 数据模型 (Pydantic)
├── agents/
│   ├── __init__.py
│   ├── base_agent.py               # Agent 基类 - 基本保留
│   ├── requirement_agent.py        # 需求理解 Agent - 改造(输出指标集)
│   ├── recommendation_agent.py     # 推荐 Agent - 改造(树形结构输出)
│   ├── modeling_agent.py          # 建模 Agent - 改造(批量生成)
│   └── bi_design_agent.py        # BI 设计 Agent - 新增
├── rag/
│   ├── __init__.py
│   ├── embedding_model.py          # Embedding 模型 - 保留
│   └── vector_store.py            # 向量库 - 改造(支持指标集检索)
├── utils/
│   ├── __init__.py
│   ├── api_client.py               # API 客户端 - 保留
│   ├── file_parser.py             # 文件解析 - 新增
│   ├── file_generator.py           # 文件生成 - 改造(支持批量)
│   ├── zip_packager.py             # 打包工具 - 保留
│   └── sql_validator.py           # SQL 校验 - 保留
├── data/
│   ├── mock/
│   │   ├── ecommerce_indicators.json      # 电商指标集 - 新增
│   │   ├── public_resource_indicators.json # 公共资源交易指标集 - 新增
│   │   ├── toc_standard_indicators.json   # ToC 标准指标集 - 新增
│   │   ├── retail_indicators.json         # 保留(旧格式)
│   │   ├── ecommerce_indicators_old.json # 重命名(旧格式)
│   │   └── finance_indicators.json       # 保留(旧格式)
│   ├── faiss_index.bin               # FAISS 索引 - 保留
│   └── indicators_metadata.json      # 指标元数据 - 保留(需重建)
├── tests/                          # 新增目录
│   ├── __init__.py
│   ├── test_requirement_agent.py    # 单元测试
│   ├── test_recommendation_agent.py
│   ├── test_modeling_agent.py
│   ├── test_bi_design_agent.py     # 新增
│   ├── test_file_parser.py         # 新增
│   └── test_app.py                # 新增(集成测试)
└── docs/
    ├── requirements_optimized.md   # 需求文档
    └── architecture_design_v3.md  # 本文档
```

### 2.2 文件统计

| 类别 | 数量 | 说明 |
|------|------|------|
| 保留(现有) | 12 个 | app.py, base_agent.py, api_client.py 等 |
| 改造(现有) | 7 个 | requirement_agent.py, recommendation_agent.py 等 |
| 新增 | 10 个 | bi_design_agent.py, file_parser.py, 3个数据模型文件, 4个测试文件, 3个Mock JSON |
| **总计** | **29 个** | 包含所有代码、配置、测试、文档 |

---

## 3. 数据结构和接口

### 3.1 类图(Mermaid)

```mermaid
classDiagram
    %% 数据模型层 (新增)
    class Indicator {
        +str indicator_id
        +str indicator_name
        +str business_meaning
        +str calculation_logic
        +List~str~ dimensions
        +List~str~ metrics
        +List~str~ filters
        +str time_granularity
        +str update_frequency
        +str data_source
        +str usage_scenario
        +validate() bool
        +to_dict() dict
    }
    
    class IndicatorSet {
        +str set_id
        +str set_name
        +str business_domain
        +str analysis_purpose
        +List~Indicator~ indicators
        +add_indicator(Indicator)
        +remove_indicator(str)
        +get_indicator(str) Indicator
        +to_dict() dict
        +from_dict(dict) IndicatorSet
    }
    
    class FileMetadata {
        +str filename
        +int file_size
        +List~str~ columns
        +Dict~str~ dtypes
        +List~dict~ sample_data
        +int row_count
        +to_dict() dict
    }
    
    %% Agent 层
    class BaseAgent {
        <<abstract>>
        +str name
        +bool mock_mode
        +run(Dict) Dict
        +validate_input(Dict, List) bool
        +format_output(Dict) Dict
    }
    
    class RequirementAgent {
        -DeepSeekClient api_client
        +run(Dict) Dict
        -_mock_run(str) Dict
        -_parse_response(str) Dict
        +process_file_metadata(FileMetadata) Dict
    }
    
    class RecommendationAgent {
        -VectorStore vector_store
        -float similarity_threshold
        +run(Dict) Dict
        -_build_search_query(Dict) str
        -_format_recommendations(List) List
    }
    
    class ModelingAgent {
        -DeepSeekClient api_client
        +run(Dict) Dict
        -_mock_run(Dict, List) Dict
        +generate_batch(List~Indicator~) Dict
    }
    
    class BIDesignAgent {
        -DeepSeekClient api_client
        +run(Dict) Dict
        -_mock_run(List~Indicator~) str
        +generate_charts(List~Indicator~) List~dict~
    }
    
    %% RAG 层
    class EmbeddingModel {
        +str model_name
        +encode(List~str~) ndarray
        +encode_single(str) ndarray
    }
    
    class VectorStore {
        -faiss.Index index
        -List~dict~ indicators
        -EmbeddingModel embedding_model
        +build_index(List~dict~)
        +search(str, int) List~Tuple~
        +is_ready() bool
        +save_index()
        +load_index()
    }
    
    %% Utils 层
    class DeepSeekClient {
        -str api_key
        -bool mock_mode
        +call(str, str) str
        -_mock_response(str) str
        -_real_api_call(str, str) str
    }
    
    class FileParser {
        +parse_file(file) FileMetadata
        +parse_excel(file) FileMetadata
        +parse_csv(file) FileMetadata
        -_extract_metadata(DataFrame) FileMetadata
        -_detect_encoding(file) str
    }
    
    class FileGenerator {
        -Path output_dir
        +generate_all(Dict, str, str, Dict, str) Dict
        +generate_indicator_set(IndicatorSet) Dict
    }
    
    class SQLValidator {
        +validate(str) Dict
    }
    
    class ZipPackager {
        +package(Dict) str
    }
    
    %% 关系
    BaseAgent <|-- RequirementAgent
    BaseAgent <|-- RecommendationAgent
    BaseAgent <|-- ModelingAgent
    BaseAgent <|-- BIDesignAgent
    
    IndicatorSet "1" *-- "many" Indicator
    
    RequirementAgent --> DeepSeekClient
    RequirementAgent --> FileParser : uses
    RequirementAgent --> IndicatorSet : creates
    
    RecommendationAgent --> VectorStore
    RecommendationAgent --> IndicatorSet : recommends
    
    ModelingAgent --> DeepSeekClient
    ModelingAgent --> IndicatorSet : processes
    
    BIDesignAgent --> DeepSeekClient
    BIDesignAgent --> IndicatorSet : processes
    
    VectorStore --> EmbeddingModel
    
    FileGenerator --> IndicatorSet : generates files for
```

### 3.2 核心数据结构定义

#### Indicator (单个指标)

```python
# models/indicator.py
from pydantic import BaseModel, Field
from typing import List, Optional

class Indicator(BaseModel):
    """单个指标的数据模型 (Pydantic)"""
    
    indicator_id: str = Field(..., description="指标唯一 ID")
    indicator_name: str = Field(..., description="指标名称")
    business_meaning: str = Field(..., description="业务含义")
    calculation_logic: str = Field(..., description="计算逻辑 (SQL)")
    
    dimensions: List[str] = Field(default_factory=list, description="维度列表")
    metrics: List[str] = Field(default_factory=list, description="度量列表")
    filters: List[str] = Field(default_factory=list, description="过滤条件")
    
    time_granularity: str = Field(default="日", description="时间粒度")
    update_frequency: str = Field(default="每天", description="更新频率")
    
    data_source: Optional[str] = Field(default=None, description="数据来源表")
    usage_scenario: Optional[str] = Field(default=None, description="使用场景")
    
    class Config:
        json_schema_extra = {
            "example": {
                "indicator_id": "ind_001",
                "indicator_name": "GMV",
                "business_meaning": "商品交易总额",
                "calculation_logic": "SUM(order_amount) WHERE payment_status='paid'",
                "dimensions": ["date", "category", "channel"],
                "metrics": ["order_amount"],
                "filters": ["payment_status='paid'"],
                "time_granularity": "日",
                "update_frequency": "实时",
                "data_source": "fact_order",
                "usage_scenario": "监控销售业绩,分析销售趋势"
            }
        }
```

#### IndicatorSet (指标集)

```python
# models/indicator_set.py
from pydantic import BaseModel, Field
from typing import List, Optional
from .indicator import Indicator

class IndicatorSet(BaseModel):
    """指标集的数据模型 (Pydantic)"""
    
    set_id: str = Field(..., description="指标集唯一 ID")
    set_name: str = Field(..., description="指标集名称")
    business_domain: str = Field(..., description="业务领域(如:电商、金融)")
    analysis_purpose: Optional[str] = Field(default=None, description="分析目的")
    
    indicators: List[Indicator] = Field(..., description="指标列表")
    
    class Config:
        json_schema_extra = {
            "example": {
                "set_id": "set_ecommerce_001",
                "set_name": "电商标准指标集",
                "business_domain": "电商",
                "analysis_purpose": "电商业务全景分析",
                "indicators": [
                    {
                        "indicator_id": "ind_001",
                        "indicator_name": "GMV",
                        "business_meaning": "商品交易总额",
                        "calculation_logic": "SUM(order_amount) WHERE payment_status='paid'",
                        "dimensions": ["date", "category"],
                        "metrics": ["order_amount"],
                        "filters": ["payment_status='paid'"],
                        "time_granularity": "日",
                        "update_frequency": "实时"
                    }
                ]
            }
        }
```

#### FileMetadata (文件元数据)

```python
# utils/file_parser.py
class FileMetadata:
    """上传文件的元数据(非 Pydantic,简单数据类)"""
    
    def __init__(self, filename, file_size, columns, dtypes, sample_data, row_count):
        self.filename = filename
        self.file_size = file_size  # bytes
        self.columns = columns  # List[str]
        self.dtypes = dtypes  # Dict[str, str]
        self.sample_data = sample_data  # List[dict] (前5行)
        self.row_count = row_count  # int
    
    def to_dict(self):
        return {
            "filename": self.filename,
            "file_size": self.file_size,
            "columns": self.columns,
            "dtypes": self.dtypes,
            "sample_data": self.sample_data,
            "row_count": self.row_count
        }
```

### 3.3 关键接口定义

#### RequirementAgent

```python
class RequirementAgent(BaseAgent):
    def run(self, input_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        Input:
        {
            "user_input": str,              # 用户文字输入
            "file_metadata": FileMetadata,  # 上传文件的元数据(可选)
            "business_type": str            # 业务类型(可选:"电商"|"金融"|...)
        }
        
        Output:
        {
            "status": "success",
            "data": {
                "indicator_set": IndicatorSet,  # 生成的指标集
                "business_domain": str,         # 业务领域
                "analysis_purpose": str         # 分析目的
            }
        }
        """
```

#### RecommendationAgent

```python
class RecommendationAgent(BaseAgent):
    def run(self, input_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        Input:
        {
            "indicator_set": IndicatorSet,  # 用户需求理解结果
            "top_k": int                   # 推荐数量(默认 5)
        }
        
        Output:
        {
            "status": "success",
            "data": {
                "indicator_set_name": str,    # 指标集名称
                "total_count": int,           # 指标总数
                "categories": [               # 分类树形结构
                    {
                        "category_name": str,
                        "indicators": [Indicator]
                    }
                ],
                "new_indicator_needed": bool
            }
        }
        """
```

#### ModelingAgent

```python
class ModelingAgent(BaseAgent):
    def run(self, input_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        Input:
        {
            "indicator_set": IndicatorSet,     # 用户确认的指标集
            "selected_indicators": List[str]   # 用户选中的指标 ID 列表
        }
        
        Output:
        {
            "status": "success",
            "data": {
                "indicator_set": IndicatorSet,     # 包含完整方案的指标集
                "schemes": [                       # 每个指标的方案
                    {
                        "indicator_id": str,
                        "markdown": str,           # 指标定义文档
                        "sql": str,               # 查询 SQL
                        "table_structure": dict    # 表结构
                    }
                ]
            }
        }
        """
```

#### BIDesignAgent

```python
class BIDesignAgent(BaseAgent):
    def run(self, input_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        Input:
        {
            "indicator_set": IndicatorSet,     # 指标集
            "schemes": List[dict]             # 指标方案列表
        }
        
        Output:
        {
            "status": "success",
            "data": {
                "bi_design": {
                    "charts": [               # 推荐图表列表
                        {
                            "chart_type": str,        # 图表类型
                            "title": str,             # 图表标题
                            "indicators": List[str],  # 使用指标
                            "calculation_logic": str, # 计算逻辑
                            "data_source": str,       # 数据来源
                            "usage_scenario": str,    # 使用场景
                            "markdown_diagram": str   # Markdown 示意图
                        }
                    ],
                    "markdown": str           # 完整 BI 设计文档(Markdown)
                }
            }
        }
        """
```

#### FileParser

```python
class FileParser:
    def parse_file(self, uploaded_file) -> FileMetadata:
        """
        Parse uploaded Excel/CSV file and extract metadata.
        
        Input: Streamlit UploadedFile object
        Output: FileMetadata object
        
        Raises:
            ValueError: If file format is unsupported
            UnicodeDecodeError: If CSV encoding cannot be detected
        """
    
    def parse_excel(self, file) -> FileMetadata:
        """Parse Excel file (.xlsx, .xls)"""
    
    def parse_csv(self, file) -> FileMetadata:
        """Parse CSV file with encoding detection"""
    
    def _extract_metadata(self, df: pd.DataFrame) -> FileMetadata:
        """
        Extract metadata from DataFrame.
        
        Output FileMetadata fields:
        - filename: 文件名
        - columns: 字段名列表
        - dtypes: 数据类型字典
        - sample_data: 前 5 行样例数据
        - row_count: 总行数
        """
```

---

## 4. 程序调用流程

### 4.1 完整流程时序图(Mermaid)

```mermaid
sequenceDiagram
    actor User as 用户
    participant UI as Streamlit UI
    participant RA as RequirementAgent
    participant FP as FileParser
    participant RecA as RecommendationAgent
    participant VS as VectorStore
    participant MA as ModelingAgent
    participant BIDA as BIDesignAgent
    participant FG as FileGenerator
    participant ZP as ZipPackager
    
    %% Step 1: 需求输入
    User ->> UI: Step 1 - 输入需求
    note over User,UI: 方式1: 文字描述<br/>方式2: 上传文件<br/>方式3: 选择业务类型
    
    alt 用户上传文件
        User ->> UI: 上传 Excel/CSV
        UI ->> FP: parse_file(uploaded_file)
        FP ->> FP: 解析文件
        FP -->> UI: FileMetadata
    end
    
    User ->> UI: 点击"生成指标方案"
    UI ->> RA: run({user_input, file_metadata, business_type})
    
    alt Mock 模式
        RA ->> RA: _mock_run()
        RA -->> UI: IndicatorSet (Mock)
    else Real 模式
        RA ->> RA: 调用 DeepSeek API
        RA -->> UI: IndicatorSet
    end
    
    UI ->> UI: 保存 indicator_set 到 session_state
    UI ->> UI: 跳转到 Step 2
    
    %% Step 2: 指标推荐与选择
    UI ->> RecA: run({indicator_set})
    
    RecA ->> VS: search(query, k)
    VS -->> RecA: search_results
    
    RecA ->> RecA: _format_recommendations()
    RecA -->> UI: 树形结构推荐指标集
    
    UI ->> UI: 渲染树形复选框
    
    User ->> UI: 选择指标(至少1个)
    User ->> UI: 点击"确认并生成完整方案"
    
    UI ->> UI: 保存 selected_indicators
    
    %% Step 3: 建模生成 + BI 设计
    par 并行生成
        UI ->> MA: run({indicator_set, selected_indicators})
        UI ->> BIDA: run({indicator_set, schemes})
    end
    
    alt Mock 模式 - ModelingAgent
        MA ->> MA: _mock_run()
        MA -->> UI: schemes (批量)
    else Real 模式 - ModelingAgent
        MA ->> MA: 调用 DeepSeek API(批量)
        MA -->> UI: schemes
    end
    
    alt Mock 模式 - BIDesignAgent
        BIDA ->> BIDA: _mock_run()
        BIDA -->> UI: bi_design
    else Real 模式 - BIDesignAgent
        BIDA ->> BIDA: 调用 DeepSeek API
        BIDA -->> UI: bi_design
    end
    
    UI ->> UI: 展示指标方案 + BI 设计
    
    %% 下载
    User ->> UI: 点击"下载完整方案包"
    UI ->> FG: generate_all(indicator_set, schemes, bi_design)
    FG ->> FG: 生成 .md, .sql, .json
    FG -->> UI: files dict
    
    UI ->> ZP: package(files)
    ZP -->> UI: zip_path
    
    UI ->> User: 下载 .zip 文件
    
    note over User,UI: 可选单独下载:<br/>- 指标方案 (.md)<br/>- BI 设计 (.md)<br/>- 数据字典 (.xlsx)
```

### 4.2 关键子流程

#### 流程 1: Step 1 - 需求理解与文件解析

```mermaid
sequenceDiagram
    User ->> UI: 输入需求/上传文件
    
    alt 上传文件
        UI ->> FileParser: parse_file(file)
        FileParser ->> FileParser: detect file type
        
        alt Excel 文件
            FileParser ->> FileParser: pd.read_excel()
        else CSV 文件
            FileParser ->> FileParser: detect encoding
            FileParser ->> FileParser: pd.read_csv()
        end
        
        FileParser ->> FileParser: extract metadata
        FileParser -->> UI: FileMetadata
    end
    
    UI ->> RequirementAgent: run({input, metadata, business_type})
    RequirementAgent ->> RequirementAgent: format prompt
    
    alt Mock 模式
        RequirementAgent ->> RequirementAgent: keyword matching
        RequirementAgent -->> UI: IndicatorSet (mock)
    else Real 模式
        RequirementAgent ->> DeepSeek API: call(prompt)
        DeepSeek API -->> RequirementAgent: response
        RequirementAgent ->> RequirementAgent: parse JSON
        RequirementAgent -->> UI: IndicatorSet
    end
```

#### 流程 2: Step 2 - 指标推荐(树形结构)

```mermaid
sequenceDiagram
    UI ->> RecommendationAgent: run({indicator_set})
    
    RecommendationAgent ->> RecommendationAgent: build search query
    
    alt RAG 可用
        RecommendationAgent ->> VectorStore: search(query, k=10)
        VectorStore -->> RecommendationAgent: results
        
        RecommendationAgent ->> RecommendationAgent: format as tree structure
        RecommendationAgent -->> UI: categories + indicators
    else RAG 不可用或结果为空
        RecommendationAgent ->> RecommendationAgent: AI 生成兜底
        RecommendationAgent -->> UI: generated indicator set
    end
    
    UI ->> UI: render tree checkboxes
    
    User ->> UI: select indicators (≥1)
    UI ->> UI: update session_state
```

#### 流程 3: Step 3 - 批量建模 + BI 设计

```mermaid
sequenceDiagram
    par 并行处理
        UI ->> ModelingAgent: run({selected_indicators})
        UI ->> BIDesignAgent: run({indicator_set})
    end
    
    ModelingAgent ->> ModelingAgent: for each indicator:
    ModelingAgent ->> ModelingAgent: generate SQL
    ModelingAgent ->> ModelingAgent: generate Markdown
    ModelingAgent ->> ModelingAgent: generate table structure
    ModelingAgent -->> UI: schemes[]
    
    BIDesignAgent ->> BIDesignAgent: analyze indicators
    BIDesignAgent ->> BIDesignAgent: recommend charts
    BIDesignAgent ->> BIDesignAgent: generate Markdown diagrams
    BIDesignAgent -->> UI: bi_design{}
    
    UI ->> UI: display schemes + bi_design
```

---

## 5. 待明确事项

### 5.1 业务逻辑问题

| 问题 | 描述 | 建议方案 |
|------|------|----------|
| **指标集去重逻辑** | 如果用户多次生成指标集,如何处理重复指标? | 根据 `indicator_name` 去重,保留最新的 |
| **文件解析失败兜底** | 如果文件解析失败,是否继续使用用户输入的文字描述? | 是,提示用户文件解析失败,但继续使用文字描述生成 |
| **BI 设计生成失败兜底** | 如果 BIDesignAgent 失败,是否影响整个流程? | 否,跳过 BI 设计,仅展示指标方案,并提示用户"BI 设计生成失败,可点击重新生成" |

### 5.2 技术实现问题

| 问题 | 描述 | 建议方案 |
|------|------|----------|
| **批量生成性能** | 如果用户选择 30+ 个指标,批量生成可能很慢 | 使用 `concurrent.futures` 并行生成,设置超时时间(60秒) |
| **向量库更新** | 用户生成的指标集是否需要加入向量库? | Phase 1 不加入(避免污染);Phase 2 增加"保存到指标库"功能 |
| **Mock 数据维护** | 3 个 Mock 指标集是否需要更多? | 先完成 3 个,后续根据用户反馈增加 |

### 5.3 用户体验问题

| 问题 | 描述 | 建议方案 |
|------|------|----------|
| **加载动画设计** | 批量生成时,如何展示进度? | 使用 `st.progress_bar` 显示进度;分步骤显示(如 "正在生成第 3/12 个指标...") |
| **错误提示语言** | 错误信息应该对用户友好 | 所有错误信息使用中文,避免技术术语 |
| **移动端适配** | 是否需要支持移动端? | Phase 1 仅支持桌面端;移动端适配作为 Phase 2 |

---

# Part B: 任务分解

## 6. 依赖包列表

### 6.1 核心依赖

```
# Web 框架
streamlit==1.29.0          # Web 框架

# 数据处理
pandas==2.1.4              # 数据处理
openpyxl==3.1.2            # Excel 文件解析

# 向量检索
faiss-cpu==1.7.4           # 向量数据库 (CPU 版本)
sentence-transformers==2.2.2  # Embedding 模型

# API 调用
requests==2.31.0           # HTTP 请求 (API 调用)

# 数据验证
pydantic==2.5.0            # 数据验证 (Indicator, IndicatorSet)

# 工具库
python-dotenv==1.0.0       # 环境变量管理
numpy==1.26.2               # 数值计算 (FAISS 依赖)
```

### 6.2 开发依赖

```
# 测试
pytest==7.4.3              # 单元测试
pytest-cov==4.1.0          # 测试覆盖率

# 代码质量
black==23.12.0             # 代码格式化
flake8==6.1.0              # 代码风格检查
mypy==1.8.0                # 类型检查 (可选)
```

---

## 7. 任务列表(按依赖顺序)

### **T01: 项目基础设施**

- **Task ID**: T01
- **Task Name**: 项目基础设施搭建
- **Source Files**: 
  - `config/settings.py` (改造)
  - `config/prompts.py` (改造)
  - `data/mock/ecommerce_indicators.json` (新增)
  - `data/mock/public_resource_indicators.json` (新增)
  - `data/mock/toc_standard_indicators.json` (新增)
- **Dependencies**: 无
- **Priority**: P0
- **详细说明**:
  1. 更新 `config/settings.py`,新增以下配置项:
     - `MAX_FILE_SIZE = 10 * 1024 * 1024` (10MB)
     - `ALLOWED_FILE_TYPES = [".xlsx", ".xls", ".csv"]`
     - `MAX_FILE_ROWS = 1000`
  2. 更新 `config/prompts.py`,新增 `BI_DESIGN_AGENT_PROMPT` 模板
  3. 创建 3 个 Mock 指标集 JSON 文件:
     - `data/mock/ecommerce_indicators.json` (12个指标)
     - `data/mock/public_resource_indicators.json` (20个指标)
     - `data/mock/toc_standard_indicators.json` (15个指标)
  4. 安装新增依赖包:`pip install openpyxl pydantic`
- **验收标准**:
  - [ ] `config/settings.py` 包含新增配置项
  - [ ] `config/prompts.py` 包含 `BI_DESIGN_AGENT_PROMPT`
  - [ ] 3 个 Mock JSON 文件可以被正确读取和解析
  - [ ] 新增依赖包安装成功

---

### **T02: 数据层(类型定义 + 文件解析)**

- **Task ID**: T02
- **Task Name**: 数据层实现(模型定义 + 文件解析)
- **Source Files**:
  - `models/indicator.py` (新增)
  - `models/indicator_set.py` (新增)
  - `utils/file_parser.py` (新增)
  - `tests/test_file_parser.py` (新增)
- **Dependencies**: T01
- **Priority**: P0
- **详细说明**:
  1. 创建 `models/indicator.py`,定义 `Indicator` 数据模型(Pydantic)
  2. 创建 `models/indicator_set.py`,定义 `IndicatorSet` 数据模型(Pydantic)
  3. 创建 `utils/file_parser.py`,实现 `FileParser` 类:
     - `parse_file()`: 自动检测文件类型(Excel 或 CSV)
     - `parse_excel()`: 使用 `pandas.read_excel()` 解析
     - `parse_csv()`: 使用 `pandas.read_csv()` 解析,自动检测编码(UTF-8, GBK, GB2312)
     - `_extract_metadata()`: 提取字段名、数据类型、样例数据、行数
  4. 编写单元测试 `tests/test_file_parser.py`
- **验收标准**:
  - [ ] `Indicator` 和 `IndicatorSet` 模型定义完整,类型检查通过
  - [ ] `FileParser.parse_file()` 可以正确解析 Excel 和 CSV 文件
  - [ ] 编码检测正确(UTF-8, GBK)
  - [ ] 单元测试通过(覆盖率 ≥ 80%)

---

### **T03: 核心 Agent 改造(需求理解 + 推荐)**

- **Task ID**: T03
- **Task Name**: 改造 RequirementAgent 和 RecommendationAgent
- **Source Files**:
  - `agents/requirement_agent.py` (改造)
  - `agents/recommendation_agent.py` (改造)
  - `rag/vector_store.py` (改造)
  - `tests/test_requirement_agent.py` (更新)
  - `tests/test_recommendation_agent.py` (更新)
- **Dependencies**: T01, T02
- **Priority**: P0
- **详细说明**:
  1. 改造 `agents/requirement_agent.py`:
     - 修改 `run()` 方法,输入增加 `file_metadata` 和 `business_type`
     - 输出从单个指标改为 `IndicatorSet`(使用 Pydantic 模型)
     - Mock 模式:根据关键词返回预定义的 `IndicatorSet`(从 `data/mock/*.json` 读取)
     - 新增 `_parse_file_metadata()` 方法,处理文件上传场景
  2. 改造 `agents/recommendation_agent.py`:
     - 修改 `run()` 方法,输出改为树形结构(包含 `categories` 和 `indicators`)
     - 确保至少返回 1 个推荐指标(如果 RAG 检索结果为空,使用 AI 生成兜底)
     - 修改 `VectorStore.search()` 调用,增加 `k=10`(返回更多结果用于构建树形结构)
  3. 改造 `rag/vector_store.py`:
     - 修改 `build_index()`,支持从 `IndicatorSet` 提取文本用于 Embedding
     - 修改 `search()`,返回结果包含 `category` 字段(用于树形展示)
  4. 更新单元测试
- **验收标准**:
  - [ ] `RequirementAgent.run()` 返回 `IndicatorSet` 格式
  - [ ] Mock 模式可以根据关键词返回正确的指标集
  - [ ] `RecommendationAgent.run()` 返回树形结构(categories + indicators)
  - [ ] 如果 RAG 检索失败,自动使用 AI 生成兜底
  - [ ] 单元测试通过

---

### **T04: 建模 Agent 和 BI 设计 Agent**

- **Task ID**: T04
- **Task Name**: 实现 ModelingAgent 批量生成和 BIDesignAgent
- **Source Files**:
  - `agents/modeling_agent.py` (改造)
  - `agents/bi_design_agent.py` (新增)
  - `utils/file_generator.py` (改造)
  - `tests/test_modeling_agent.py` (更新)
  - `tests/test_bi_design_agent.py` (新增)
- **Dependencies**: T01, T03
- **Priority**: P1
- **详细说明**:
  1. 改造 `agents/modeling_agent.py`:
     - 修改 `run()` 方法,输入改为 `indicator_set` 和 `selected_indicators`
     - 支持批量生成多个指标的建模方案(循环或并行)
     - Mock 模式:为每个指标生成预设的 SQL、Markdown、表结构
  2. 新增 `agents/bi_design_agent.py`:
     - 创建 `BIDesignAgent` 类,继承 `BaseAgent`
     - 实现 `run()` 方法,根据选中的指标生成 BI 图表设计
     - Mock 模式:返回预定义的图表设计(Markdown 格式,包含 ASCII 图表示意图)
     - Real 模式:调用 DeepSeek API,传入 Prompt(包含指标列表)
  3. 改造 `utils/file_generator.py`:
     - 修改 `generate_all()` 方法,支持批量生成多个指标的文件
     - 新增 `generate_indicator_set()` 方法,生成指标集的文档
  4. 编写单元测试
- **验收标准**:
  - [ ] `ModelingAgent.run()` 可以批量生成多个指标的方案
  - [ ] `BIDesignAgent.run()` 可以生成 BI 设计文档(Markdown)
  - [ ] Mock 模式可以正确生成预设的 BI 设计
  - [ ] `FileGenerator.generate_all()` 可以正确处理指标集
  - [ ] 单元测试通过

---

### **T05: 前端 UI 改造和集成**

- **Task ID**: T05
- **Task Name**: 改造 Streamlit 前端 UI(Step 1-3)
- **Source Files**:
  - `app.py` (改造)
  - `utils/zip_packager.py` (保留)
  - `utils/sql_validator.py` (保留)
  - `tests/test_app.py` (新增)
- **Dependencies**: T01, T03, T04
- **Priority**: P1
- **详细说明**:
  1. **Step 1 改造**:
     - 新增文字描述输入框 (`st.text_area`)
     - 新增文件上传组件 (`st.file_uploader("上传数据标准/规范", type=["xlsx", "xls", "csv"])`)
     - 新增业务类型下拉选择 (`st.selectbox(["电商", "金融", "制造业", "公共资源交易", "ToC互联网"])`)
     - 示例需求快捷填入按钮("电商指标集"、"公共资源交易"、"ToC标准指标")
     - 调用 `FileParser.parse_file()` 解析上传的文件
     - 调用 `RequirementAgent.run()` 生成指标集
  2. **Step 2 改造**:
     - 调用 `RecommendationAgent.run()` 获取推荐指标集
     - 实现树形结构展示(递归渲染 categories 和 indicators)
     - 使用 `st.checkbox()` 实现多选(每个指标一个复选框)
     - 实现全选/全不选按钮
     - 显示已选择指标数量(`st.info(f"已选择 {count} 个指标")`)
     - 禁用"确认并生成"按钮(如果未选择任何指标)
  3. **Step 3 改造**:
     - 分 Tab 展示:指标方案 | BI 设计(`st.tabs(["📋 指标方案", "📊 BI设计"])`)
     - 指标方案:列表形式,每个指标一个 `st.expander()`,展示完整定义
     - BI 设计:Markdown 渲染,展示图表设计(包含 ASCII 示意图)
     - 下载功能:单独下载(.md, .sql, .json)| 打包下载 (.zip)
  4. 更新 `st.session_state`,支持存储:
     - `indicator_set`: IndicatorSet
     - `selected_indicators`: List[Indicator]
     - `schemes`: List[dict]
     - `bi_design`: dict
  5. 编写集成测试 `tests/test_app.py`
- **验收标准**:
  - [ ] Step 1 可以正确输入需求、上传文件、选择业务类型
  - [ ] 文件上传成功后,可以正确解析并传递给 RequirementAgent
  - [ ] Step 2 可以正确展示树形结构,支持多选
  - [ ] 至少选择 1 个指标才能进入 Step 3
  - [ ] Step 3 可以正确展示指标方案和 BI 设计
  - [ ] 下载功能正常工作(单独下载 + 打包下载)
  - [ ] 集成测试通过

---

## 8. 共享知识(跨文件约定)

### 8.1 数据格式约定

| 约定项 | 说明 |
|--------|------|
| **API 响应格式** | 所有 Agent 返回 `{"status": "success", "data": {...}}` 或 `{"status": "error", "message": "...", "details": {...}}` |
| **Mock 数据格式** | 存放在 `data/mock/` 目录;文件名格式:`{business_domain}_indicators.json`;JSON 结构必须符合 `IndicatorSet` 格式 |
| **文件上传约定** | 临时文件存储在 `temp/uploads/{session_id}/` 目录;文件大小限制:≤ 10MB;行数限制:≤ 1000 行(可在 `config/settings.py` 中调整);支持格式:`.xlsx`, `.xls`, `.csv` |

### 8.2 Session State 约定

| Key | 类型 | 说明 |
|-----|------|------|
| `st.session_state.step` | int | 当前步骤 (1, 2, 3) |
| `st.session_state.indicator_set` | IndicatorSet | 需求理解结果(指标集) |
| `st.session_state.selected_indicators` | List[Indicator] | 用户选中的指标列表 |
| `st.session_state.schemes` | List[dict] | 建模方案列表 |
| `st.session_state.bi_design` | dict | BI 设计文档 |
| `st.session_state.vector_store` | VectorStore | 向量库实例 |
| `st.session_state.mock_mode` | bool | Mock 模式开关 |
| `st.session_state.api_key` | str | DeepSeek API Key |

### 8.3 错误处理约定

| 约定项 | 说明 |
|--------|------|
| **错误提示** | 使用 `st.error()` 显示错误信息;错误信息包含:原因 + 解决建议 + 操作按钮 |
| **日志记录** | 使用 `logging` 模块,级别:INFO, WARNING, ERROR;日志格式:`f"{self.name}: {message}"` |
| **异常处理** | 所有 Agent 的 `run()` 方法使用 `try-except` 捕获异常,返回统一错误格式 |

### 8.4 命名约定

| 类型 | 约定 | 示例 |
|------|------|------|
| **Python 类** | PascalCase | `RequirementAgent`, `FileParser` |
| **Python 方法/函数** | snake_case | `run()`, `parse_file()` |
| **Python 变量** | snake_case | `indicator_set`, `file_metadata` |
| **常量** | UPPER_SNAKE_CASE | `MAX_FILE_SIZE`, `ALLOWED_FILE_TYPES` |
| **JSON 字段** | snake_case | `indicator_id`, `business_meaning` |
| **测试方法** | `test_{function}_{scenario}` | `test_run_with_valid_input`, `test_parse_file_with_invalid_format` |

---

## 9. 任务依赖关系图

### 9.1 任务依赖关系(Mermaid)

```mermaid
graph TD
    T01[T01: 项目基础设施]
    T02[T02: 数据层]
    T03[T03: 核心 Agent 改造]
    T04[T04: 建模 Agent + BI Agent]
    T05[T05: 前端 UI 改造]
    
    T01 --> T02
    T01 --> T03
    T02 --> T03
    T01 --> T04
    T03 --> T04
    T01 --> T05
    T03 --> T05
    T04 --> T05
    
    style T01 fill:#ff9999,stroke:#333,stroke-width:2px
    style T02 fill:#99ccff,stroke:#333,stroke-width:2px
    style T03 fill:#99ccff,stroke:#333,stroke-width:2px
    style T04 fill:#99ff99,stroke:#333,stroke-width:2px
    style T05 fill:#ffcc99,stroke:#333,stroke-width:2px
```

### 9.2 关键路径

**关键路径**: T01 → T03 → T05

- T01 必须最先完成(基础设施,所有任务依赖)
- T02 和 T03 可以并行(都依赖 T01,但 T02 是数据层,T03 是 Agent 改造)
- T04 依赖 T03 完成(需要改造后的 RequirementAgent 和 RecommendationAgent)
- T05 是最后一步,依赖 T03 和 T04 完成

**可并行任务**:
- T02 和 T03 可以部分并行(T02 的模型定义完成后,T03 可以开始改造 Agent)
- T04 的 BIDesignAgent 实现可以与 T03 的测试并行

---

## 10. 总结

本文档完成了数据指标建模助手 v3.0 的系统架构设计,包括:

✅ **Part A: 系统设计方案**
1. 实现方案:分层架构 + Agent 模式,保留现有框架,增量式改造
2. 文件列表:29 个文件(新增 10 个,改造 7 个,保留 12 个)
3. 数据结构和接口:使用 Pydantic 定义 Indicator 和 IndicatorSet 模型,明确 4 个 Agent 的接口
4. 程序调用流程:使用 Mermaid 时序图展示完整流程和关键子流程
5. 待明确事项:列出需要后续确认的业务逻辑、技术实现、用户体验问题

✅ **Part B: 任务分解**
6. 依赖包列表:列出所有需要的第三方库及版本
7. 任务列表:5 个任务,按依赖关系排序,每个任务包含详细说明书
8. 共享知识:定义跨文件的约定和规范(数据格式、Session State、错误处理、命名)
9. 任务依赖图:使用 Mermaid 展示任务依赖关系

**下一步**:
1. 审核本文档(团队内部评审)
2. 确认任务优先级和时间安排
3. 启动 T01 任务(项目基础设施搭建)

---

**文档版本历史**:

| 版本 | 日期 | 修改内容 | 作者 |
|------|------|----------|------|
| v1.0 | 2026-05-15 | 初始架构设计,支持指标集、文件上传、BI 设计 | 高见远 (Bob) |

---

**End of Document**