Spaces:
Runtime error

File size: 34,232 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
"""
数据指标建模助手 v3.1 - 需求理解Agent模块

本模块实现了RequirementAgent类,负责理解用户的业务需求并提取业务领域和分析目的。
支持文本输入分析和文件上传解析,能够智能推断业务类型。

主要功能:
1. 分析用户输入的文本描述,理解业务需求
2. 解析上传的文件(Excel、CSV等),提取元数据
3. 根据关键词智能推断业务领域(电商、金融、ToC等)
4. 提取分析目的(用户想要解决的业务问题)
5. 支持文本输入和文件上传两种模式

更新日志 (v3.1):
- 输入:支持文本内容、文件元数据、业务类型
- 输出:只返回 business_domain 和 analysis_purpose(不再生成IndicatorSet)
- 新增文件上传解析功能
- 新增业务类型智能推断

作者: 数据指标建模助手团队
版本: v3.1
日期: 2026
"""

import json
import logging
from typing import Dict, Any, Optional
from pathlib import Path
import sys

# 将项目根目录添加到Python路径,以便导入项目内的其他模块
# 这样做可以避免硬编码路径,使代码更加灵活和可移植
PROJECT_ROOT = Path(__file__).parent.parent
sys.path.insert(0, str(PROJECT_ROOT))

# 导入所需的模块和类
from .base_agent import BaseAgent  # 基础Agent类
from utils.api_client import DeepSeekClient  # DeepSeek API客户端
from utils.file_parser import FileParser, parse_uploaded_file  # 文件解析工具
from config.prompts import get_requirement_agent_prompt  # 提示词模板
from config.settings import DEEPSEEK_API_KEY  # 配置参数
from models.indicator import Indicator  # 指标数据模型
from models.indicator_set import IndicatorSet  # 指标集数据模型


logger = logging.getLogger(__name__)


class RequirementAgent(BaseAgent):
    """
    需求理解Agent,负责理解用户需求并提取业务领域和分析目的
    
    本Agent是数据指标建模助手的核心组件之一,主要职责是分析用户的自然语言描述
    或上传的文件,提取业务领域(business_domain)和分析目的(analysis_purpose)。
    
    更新说明 (v3.1):
    - 输入参数:
        * user_input (str): 用户的文本描述
        * file_metadata (dict, 可选): 解析后的文件元数据
        * business_type (str, 可选): 用户指定的业务类型
    - 输出结果(简化):
        * business_domain (str): 推断的业务领域
        * analysis_purpose (str): 分析目的
    
    属性:
        api_key (str): DeepSeek API密钥
        api_client (DeepSeekClient): API客户端实例
        file_parser (FileParser): 文件解析器实例
    """
    
    def __init__(
        self,
        api_key: Optional[str] = None
    ):
        """
        初始化需求理解Agent
        
        构造方法,设置Agent的运行参数并初始化所需的组件。
        始终使用真实API调用,需要有效API密钥。
        
        参数:
            api_key (Optional[str]): DeepSeek API密钥
                - 如果提供,使用提供的密钥
                - 如果为None,使用配置文件中的DEEPSEEK_API_KEY
        
        返回:
            无
            
        异常:
            ValueError: 当未提供有效API密钥时抛出
            
        示例:
            >>> # 使用配置文件中的API Key
            >>> agent = RequirementAgent()
            
            >>> # 使用提供的API Key
            >>> agent = RequirementAgent(api_key="sk-...")
        """
        # 调用父类构造方法,设置Agent名称
        super().__init__(name="RequirementAgent")
        
        # 使用提供的参数或回退到配置文件中的设置
        # 这种机制允许灵活的配置方式:代码参数 > 配置文件 > 默认值
        # API key is required for real mode
        self.api_key = api_key or DEEPSEEK_API_KEY
        
        if not self.api_key:
            raise ValueError("API key is required for RequirementAgent")
        
        # Initialize API client
        self.api_client = DeepSeekClient(api_key=self.api_key)
        
        # Initialize file parser
        self.file_parser = FileParser()
        
        logger.info("RequirementAgent initialized")
    
    def run(self, input_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        分析用户输入和可选的文件,提取业务领域和分析目的
        
        这是Agent的主入口方法,协调需求理解的完整流程:
        1. 验证输入数据的有效性
        2. 提取用户输入、文件元数据、业务类型
        3. 根据运行模式选择执行路径(模拟/真实)
        4. 返回结构化的结果
        
        参数:
            input_data (Dict[str, Any]): 输入数据字典,包含:
                - user_input (str): 用户的文本描述(必需)
                - file_metadata (dict, 可选): 解析后的文件元数据
                - business_type (str, 可选): 用户指定的业务类型
                    可选值:电商、金融、公共资源交易、ToC业务、ToB业务等
                
        返回:
            Dict[str, Any]: 包含执行结果的字典:
                - status (str): "success" 表示成功,"error" 表示失败
                - data (dict, 当status="success"时): 包含:
                    * business_domain (str): 推断的业务领域
                    * analysis_purpose (str): 分析目的
                - error (str, 当status="error"时): 错误描述
        
        异常:
            方法内部捕获所有异常,不会向外抛出
            异常信息会记录在日志中,并返回error状态
            
        示例:
            >>> result = agent.run({
            ...     "user_input": "我想看每天的订单金额和GMV",
            ...     "business_type": "电商"
            ... })
            >>> if result["status"] == "success":
            ...     domain = result["data"]["business_domain"]
            ...     purpose = result["data"]["analysis_purpose"]
            ...     print(f"业务领域: {domain}, 分析目的: {purpose}")
        """
        try:
            # 步骤1:验证输入数据
            # 确保输入包含必需的字段,避免后续处理时出现KeyError
            if not self._validate_input(input_data):
                return {
                    "status": "error",
                    "error": "Invalid input: 'user_input' is required"
                }
            
            # 步骤2:提取输入参数(使用安全的get方法提供默认值)
            user_input = input_data.get("user_input", "")
            file_metadata = input_data.get("file_metadata", None)
            business_type = input_data.get("business_type", "")
            
            # 记录输入信息(便于调试和监控)
            logger.info(f"Processing requirement: {user_input[:50]}...")
            if file_metadata:
                logger.info(f"File metadata provided: {file_metadata.get('filename')}")
            if business_type:
                logger.info(f"Business type: {business_type}")
            
            # Always use real API
            result = self._real_run(user_input, file_metadata, business_type)
            
            # 步骤4:返回成功结果
            return {
                "status": "success",
                "data": result
            }
        
        except Exception as e:
            # 捕获所有异常,记录详细错误信息
            # 这样做可以避免程序崩溃,同时提供有用的调试信息
            logger.error(f"Error in RequirementAgent.run: {e}")
            return {
                "status": "error",
                "error": str(e)
            }
    
    def _validate_input(self, input_data: Dict[str, Any]) -> bool:
        """
        验证输入数据的有效性
        
        检查输入字典是否包含必需的字段,以及字段值是否符合要求。
        这是一个内部验证方法,在run()方法开始时被调用。
        
        参数:
            input_data (Dict[str, Any]): 需要验证的输入数据
            
        返回:
            bool: 
                - True: 输入数据有效
                - False: 输入数据无效(缺少user_input或为空)
        
        示例:
            >>> agent._validate_input({"user_input": "分析销售数据"})
            True
            
            >>> agent._validate_input({})
            False
            
            >>> agent._validate_input({"user_input": "   "})
            False
        """
        # 检查输入字典是否存在
        if not input_data:
            return False
        
        # 获取user_input并去除首尾空格
        user_input = input_data.get("user_input", "").strip()
        
        # 用户文本输入是必需的(即使上传了文件,也需要文本描述作为补充)
        # 这样做是为了确保用户提供了明确的业务需求描述
        if not user_input:
            return False
        
        return True
    
    def _real_run(
        self,
        user_input: str,
        file_metadata: Optional[Dict] = None,
        business_type: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        真实执行:使用DeepSeek API理解需求并提取业务领域和分析目的
        
        在真实模式下,此方法调用DeepSeek API进行智能分析。
        能够理解复杂的自然语言描述,提取业务领域和分析目的。
        
        参数:
            user_input (str): 用户的文本描述
            file_metadata (Optional[Dict]): 解析后的文件元数据
            business_type (Optional[str]): 用户指定的业务类型
            
        返回:
            Dict[str, Any]: API生成的结果,包含business_domain和analysis_purpose
            
        异常:
            Exception: 当API调用失败时,会记录错误并重新抛出异常
            
        注意:
            任何错误都会导致异常被重新抛出
        """
        logger.info("Using real API for requirement understanding")
        try:
            # 步骤1:构建提示词(prompt)
            # 将用户输入、文件元数据、业务类型整合到提示词模板中
            prompt = get_requirement_agent_prompt(
                user_input=user_input,
                # 将文件元数据转换为格式化的JSON字符串
                file_metadata=json.dumps(file_metadata, ensure_ascii=False, indent=2) if file_metadata else "",
                business_type=business_type or ""
            )
            
            # 步骤2:调用DeepSeek API
            # system_message设置AI的角色和行为
            # prompt包含具体的任务和数据
            response_text = self.api_client.call(
                system_message="你是一个专业的数据指标需求理解专家,擅长从业务需求中提取指标集。",
                prompt=prompt
            )
            
            # 步骤3:解析API响应
            # 将API返回的文本内容转换为结构化的指标集
            # 注意:错误处理由调用方(run方法)负责
            
            # 调试:记录API响应(前1000字符)
            logger.info(f"API response (first 1000 chars): {response_text[:1000]}")
            
            result = self._parse_response(response_text)
            return result
        
        except Exception as e:
            # API调用失败时的降级策略
            # 记录错误并返回模拟结果,确保系统继续可用
            raise  # Re-raise the exception, no fallback
    
    def _parse_response(self, response_text: str) -> Dict[str, Any]:
        """
        解析API响应文本,提取业务领域和分析目的
        
        DeepSeek API返回的是文本格式,可能包含JSON代码块。
        此方法负责从响应中提取JSON,并提取business_domain和analysis_purpose。
        
        参数:
            response_text (str): API返回的原始文本
            
        返回:
            Dict[str, Any]: 解析后的结果,包含:
                - business_domain (str): 业务领域
                - analysis_purpose (str): 分析目的
            
        异常:
            json.JSONDecodeError: 当响应不是有效JSON时
            Exception: 其他解析错误
            
        示例响应格式:
            ```json
            {
                "business_domain": "电商",
                "analysis_purpose": "分析销售业绩,监控核心指标"
            }
            ```
        """
        try:
            # 步骤1:从响应文本中提取JSON字符串
            if "```json" in response_text:
                json_str = response_text.split("```json")[1].split("```")[0].strip()
            elif "```" in response_text:
                json_str = response_text.split("```")[1].split("```")[0].strip()
            else:
                json_str = response_text.strip()
            
            # 步骤2:解析JSON字符串
            result = json.loads(json_str)
            
            # 步骤3:提取business_domain和analysis_purpose
            business_domain = result.get("business_domain", "通用")
            analysis_purpose = result.get("analysis_purpose", "分析业务指标,支持数据驱动决策")
            
            # 验证字段
            if not business_domain:
                business_domain = "通用"
            if not analysis_purpose:
                analysis_purpose = "分析业务指标,支持数据驱动决策"
            
            logger.info(f"Parsed response: business_domain={business_domain}, analysis_purpose={analysis_purpose[:50]}...")
            
            return {
                "business_domain": business_domain,
                "analysis_purpose": analysis_purpose
            }
        
        except json.JSONDecodeError as e:
            logger.error(f"Failed to parse JSON from response: {e}")
            logger.error(f"Response text (first 1000 chars): {response_text[:1000]}")
            raise ValueError(f"API 返回的不是有效 JSON。响应内容:{response_text[:200]}")
        
        except Exception as e:
            logger.error(f"Error parsing response: {e}")
            logger.error(f"Response text (first 1000 chars): {response_text[:1000]}")
            raise
    
    def process_file_metadata(self, uploaded_file) -> Dict[str, Any]:
        """
        处理上传的文件并提取元数据
        
        这是提供给UI层调用的接口,用于处理用户上传的文件。
        支持Excel、CSV等格式,提取文件名、列名、数据类型等信息。
        
        参数:
            uploaded_file: Streamlit UploadedFile对象
                包含文件内容和元数据
                
        返回:
            Dict[str, Any]: 包含处理结果的字典:
                - status (str): "success" 或 "error"
                - data (FileMetadata, 当status="success"时): 文件元数据字典
                - error (str, 当status="error"时): 错误描述
        
        异常:
            方法内部捕获所有异常,不会向外抛出
            
        示例:
            >>> result = agent.process_file_metadata(uploaded_file)
            >>> if result["status"] == "success":
            ...     metadata = result["data"]
            ...     print(f"文件包含 {metadata['row_count']} 行数据")
        """
        logger.info(f"Processing uploaded file: {uploaded_file.name}")
        
        try:
            # 调用文件解析器处理上传的文件
            # parse_file方法会读取文件内容,提取元数据
            metadata = self.file_parser.parse_file(uploaded_file)
            
            logger.info(f"File parsed successfully: {metadata.filename} ({metadata.row_count} rows)")
            
            return {
                "status": "success",
                "data": metadata.to_dict()
            }
        
        except ValueError as ve:
            # 文件类型不支持:返回清晰的错误信息
            logger.error(f"Unsupported file type: {ve}")
            return {
                "status": "error",
                "error": str(ve)
            }
        
        except Exception as e:
            # 其他错误:记录详细错误信息
            logger.error(f"Error processing file: {e}")
            return {
                "status": "error",
                "error": f"文件解析失败:{str(e)}"
            }
    
    def _infer_business_domain(self, user_input: str, business_type: Optional[str] = None) -> str:
        """
        从用户输入和业务类型推断业务领域
        
        基于关键词匹配规则,智能推断用户所处的业务领域。
        如果用户明确指定了业务类型,则优先使用。
        
        参数:
            user_input (str): 用户的文本描述
            business_type (Optional[str]): 用户明确指定的业务类型
                如果提供,直接返回,不进行推断
                
        返回:
            str: 推断的业务领域,可选值:
                - "电商": 包含订单、GMV、商品等关键词
                - "金融": 包含贷款、风控、支付等关键词
                - "公共资源交易": 包含交易、招标、投标等关键词
                - "ToC业务": 包含用户、流量、活跃等关键词
                - "ToB业务": 包含企业、供应链、生产等关键词
                - "医疗健康": 包含医疗、健康、患者等关键词
                - "教育培训": 包含教育、培训、学习等关键词
                - "通用": 无法匹配任何特定领域
        
        示例:
            >>> agent._infer_business_domain("我想看GMV趋势", None)
            '电商'
            
            >>> agent._infer_business_domain("分析数据", "金融")
            '金融'
        """
        # 优先使用用户明确指定的业务类型
        if business_type:
            return business_type
        
        # 将用户输入转换为小写,便于关键词匹配
        input_lower = user_input.lower()
        
        # 按优先级依次匹配关键词
        # 注意:匹配顺序会影响结果,更具体的关键词应该放在前面
        if any(kw in input_lower for kw in ["电商", "订单", "gmv", "商品", "购物"]):
            return "电商"
        elif any(kw in input_lower for kw in ["金融", "贷款", "风控", "支付", "投资"]):
            return "金融"
        elif any(kw in input_lower for kw in ["公共资源", "交易", "招标", "投标"]):
            return "公共资源交易"
        elif any(kw in input_lower for kw in ["用户", "流量", "活跃", "内容", "社交"]):
            return "ToC业务"
        elif any(kw in input_lower for kw in ["企业", "供应链", "生产", "管理"]):
            return "ToB业务"
        elif any(kw in input_lower for kw in ["医疗", "健康", "患者", "医院"]):
            return "医疗健康"
        elif any(kw in input_lower for kw in ["教育", "培训", "学习", "课程"]):
            return "教育培训"
        else:
            # 无法匹配时,返回通用类型
            return "通用"
    
    def _infer_analysis_purpose(self, user_input: str) -> str:
        """
        从用户输入推断分析目的
        
        根据用户输入中的关键词,推断用户的分析目的。
        用于丰富指标集的元数据,帮助后续Agent生成更合适的内容。
        
        参数:
            user_input (str): 用户的文本描述
            
        返回:
            str: 推断的分析目的,可选值:
                - "分析数据趋势,发现变化规律": 包含"趋势"、"变化"等词
                - "对比不同维度,发现差异": 包含"对比"、"比较"等词
                - "监控核心指标,及时发现异常": 包含"监控"、"预警"等词
                - "优化业务流程,提升关键指标": 包含"优化"、"提升"等词
                - "深入分析业务,发现洞察": 包含"分析"、"了解"等词
                - "全面分析业务指标,支持数据驱动决策": 默认选项
        
        示例:
            >>> agent._infer_analysis_purpose("我想看销售趋势")
            '分析数据趋势,发现变化规律'
        """
        input_lower = user_input.lower()
        
        # 按关键词匹配分析目的
        if "趋势" in input_lower or "变化" in input_lower:
            return "分析数据趋势,发现变化规律"
        elif "对比" in input_lower or "比较" in input_lower:
            return "对比不同维度,发现差异"
        elif "监控" in input_lower or "预警" in input_lower:
            return "监控核心指标,及时发现异常"
        elif "优化" in input_lower or "提升" in input_lower:
            return "优化业务流程,提升关键指标"
        elif "分析" in input_lower or "了解" in input_lower:
            return "深入分析业务,发现洞察"
        else:
            # 默认分析目的
            return "全面分析业务指标,支持数据驱动决策"
    
    def _generate_set_name(self, user_input: str, business_domain: str) -> str:
        """
        根据用户输入和业务领域生成指标集名称
        
        生成简洁、有意义的指标集名称,便于用户识别和管理。
        
        参数:
            user_input (str): 用户的文本描述
            business_domain (str): 业务领域
            
        返回:
            str: 生成的指标集名称
                格式:"{业务领域}{关键词}分析指标集" 或 "{业务领域}标准指标集"
        
        示例:
            >>> agent._generate_set_name("我想看订单和GMV", "电商")
            '电商订单、GMV分析指标集'
            
            >>> agent._generate_set_name("分析数据", "金融")
            '金融标准指标集'
        """
        # 从用户输入中提取关键短语
        key_phrases = []
        
        # 根据常见业务关键词生成短语
        if "订单" in user_input:
            key_phrases.append("订单")
        if "用户" in user_input or "流量" in user_input:
            key_phrases.append("用户")
        if "销售" in user_input or "gmv" in user_input.lower():
            key_phrases.append("销售")
        if "转化" in user_input:
            key_phrases.append("转化")
        
        # 根据是否有关键词生成不同的名称
        if key_phrases:
            # 格式:"{业务领域}{关键词}分析指标集"
            return f"{business_domain}{'、'.join(key_phrases)}分析指标集"
        else:
            # 无关键词时使用默认名称
            return f"{business_domain}标准指标集"
    
    def _generate_indicators(
        self,
        user_input: str,
        business_domain: str,
        file_metadata: Optional[Dict] = None
    ) -> list[Indicator]:
        """
        根据关键词和业务领域生成模拟指标
        
        在模拟模式下,根据用户输入中的关键词和推断的业务领域,
        生成预设的指标列表。用于快速测试和演示。
        
        参数:
            user_input (str): 用户的文本描述
            business_domain (str): 业务领域
            file_metadata (Optional[Dict]): 解析后的文件元数据
                如果提供,会根据文件列名生成额外的指标
                
        返回:
            list[Indicator]: 生成的指标对象列表
        
        示例:
            >>> indicators = agent._generate_indicators("我想看GMV", "电商", None)
            >>> len(indicators)
            3  # 返回电商领域的3个预设指标
        """
        indicators = []
        input_lower = user_input.lower()
        
        # 根据业务领域选择对应的指标模板
        # 每个业务领域都有预设的指标集
        if business_domain == "电商":
            indicators = self._generate_ecommerce_indicators()
        elif business_domain == "金融":
            indicators = self._generate_finance_indicators()
        elif business_domain == "公共资源交易":
            indicators = self._generate_public_resource_indicators()
        elif business_domain == "ToC业务":
            indicators = self._generate_toc_indicators()
        else:
            # 通用业务领域:根据用户输出来生成指标
            indicators = self._generate_generic_indicators(user_input)
        
        # 如果提供了文件元数据,根据文件列名生成额外的指标
        # 这样可以模拟从上传文件中提取指标的场景
        if file_metadata and file_metadata.get("columns"):
            file_indicators = self._generate_indicators_from_file(file_metadata)
            indicators.extend(file_indicators)
        
        return indicators
    
    def _generate_ecommerce_indicators(self) -> list[Indicator]:
        """
        生成电商领域常用指标
        
        返回电商业务的核心指标集,包括GMV、订单量、客单价等。
        这些指标覆盖了电商业务的主要分析场景。
        
        返回:
            list[Indicator]: 电商指标列表
        """
        return [
            Indicator(
                indicator_id="ind_ec_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="监控销售业绩,分析销售趋势,评估营销活动效果"
            ),
            Indicator(
                indicator_id="ind_ec_002",
                indicator_name="订单量",
                business_meaning="每日成功支付的订单总数,反映交易频次和用户购买行为",
                calculation_logic="COUNT(DISTINCT order_id) WHERE payment_status='paid'",
                dimensions=["date", "category", "channel"],
                metrics=["order_id"],
                filters=["payment_status='paid'"],
                time_granularity="日",
                update_frequency="实时",
                data_source="fact_order",
                usage_scenario="分析订单趋势,预测销量,优化库存"
            ),
            Indicator(
                indicator_id="ind_ec_003",
                indicator_name="客单价",
                business_meaning="平均每个订单的交易金额,反映用户消费能力和平台定位",
                calculation_logic="SUM(order_amount) / COUNT(DISTINCT order_id) WHERE payment_status='paid'",
                dimensions=["date", "category", "user_level"],
                metrics=["order_amount", "order_id"],
                filters=["payment_status='paid'"],
                time_granularity="日",
                update_frequency="每天",
                data_source="fact_order",
                usage_scenario="分析用户消费习惯,制定营销策略,优化商品定价"
            )
        ]
    
    def _generate_finance_indicators(self) -> list[Indicator]:
        """
        生成金融领域常用指标
        
        返回金融业务的核心指标,包括贷款余额等。
        
        返回:
            list[Indicator]: 金融指标列表
        """
        return [
            Indicator(
                indicator_id="ind_fin_001",
                indicator_name="贷款余额",
                business_meaning="统计时刻所有未结清贷款的总金额,反映业务规模",
                calculation_logic="SUM(loan_amount) WHERE loan_status='active'",
                dimensions=["date", "product_type", "risk_level"],
                metrics=["loan_amount"],
                filters=["loan_status='active'"],
                time_granularity="日",
                update_frequency="每天",
                data_source="fact_loan",
                usage_scenario="监控业务规模,评估风险敞口"
            )
        ]
    
    def _generate_public_resource_indicators(self) -> list[Indicator]:
        """
        生成公共资源交易领域常用指标
        
        返回公共资源交易的核心指标,包括交易总额等。
        
        返回:
            list[Indicator]: 公共资源交易指标列表
        """
        return [
            Indicator(
                indicator_id="ind_pr_001",
                indicator_name="交易总额",
                business_meaning="统计周期内所有成交项目的总金额,反映公共资源交易市场总体规模",
                calculation_logic="SUM(transaction_amount) WHERE status='completed'",
                dimensions=["date", "resource_type", "region"],
                metrics=["transaction_amount"],
                filters=["status='completed'"],
                time_granularity="日",
                update_frequency="每天",
                data_source="fact_transaction",
                usage_scenario="监控市场交易规模,分析市场趋势,评估政策效果"
            )
        ]
    
    def _generate_toc_indicators(self) -> list[Indicator]:
        """
        生成ToC业务领域常用指标
        
        返回面向消费者的互联网业务核心指标,包括DAU、新增用户等。
        
        返回:
            list[Indicator]: ToC业务指标列表
        """
        return [
            Indicator(
                indicator_id="ind_toc_001",
                indicator_name="DAU(日活跃用户数)",
                business_meaning="每日至少访问一次的独立用户数,反映产品用户规模和粘性",
                calculation_logic="COUNT(DISTINCT user_id) WHERE event_type='app_open'",
                dimensions=["date", "channel", "os_type"],
                metrics=["user_id"],
                filters=["event_type='app_open'"],
                time_granularity="日",
                update_frequency="实时",
                data_source="fact_user_event",
                usage_scenario="监控用户规模变化,评估产品健康度,分析渠道效果"
            ),
            Indicator(
                indicator_id="ind_toc_002",
                indicator_name="新增用户数",
                business_meaning="每日首次注册或访问的新用户数,反映产品获客能力",
                calculation_logic="COUNT(DISTINCT user_id) WHERE is_new_user=1",
                dimensions=["date", "channel", "campaign"],
                metrics=["user_id"],
                filters=["is_new_user=1"],
                time_granularity="日",
                update_frequency="实时",
                data_source="fact_user_event, dim_user",
                usage_scenario="评估获客效果,优化营销策略,分析渠道质量"
            )
        ]
    
    def _generate_generic_indicators(self, user_input: str) -> list[Indicator]:
        """
        根据用户输入生成通用指标
        
        当无法匹配特定业务领域时,生成通用的业务指标。
        
        参数:
            user_input (str): 用户的文本描述
            
        返回:
            list[Indicator]: 通用指标列表
        """
        indicators = []
        
        # 添加一个通用指标
        # 注意:这是一个占位符,实际应用中应该根据用户输入智能生成
        indicators.append(
            Indicator(
                indicator_id="ind_generic_001",
                indicator_name="通用业务指标",
                business_meaning=f"根据用户输入「{user_input}」分析得出的业务指标",
                calculation_logic="根据具体需求确定计算逻辑",
                dimensions=["date"],
                metrics=["value"],
                filters=[],
                time_granularity="日",
                update_frequency="每天",
                data_source="fact_business",
                usage_scenario="通用业务分析"
            )
        )
        
        return indicators
    
    def _generate_indicators_from_file(self, file_metadata: Dict) -> list[Indicator]:
        """
        根据文件结构生成指标
        
        分析上传文件的列名和数据类型,智能生成相应的指标。
        这是一个高级功能,当前版本仅提供占位符实现。
        
        参数:
            file_metadata (Dict): 解析后的文件元数据
                包含列名、数据类型、样本数据等
                
        返回:
            list[Indicator]: 根据文件生成的指标列表
            
        待实现:
            - 根据列名推断指标类型(计数、求和、平均值等)
            - 根据数据类型推荐合适的图表类型
            - 自动生成计算逻辑
        """
        indicators = []
        columns = file_metadata.get("columns", [])
        
        # TODO: 实现基于文件列名的智能指标生成
        # 这是一个复杂的任务,需要理解列名的语义
        # 例如:"订单金额" -> 求和指标,"用户ID" -> 去重计数指标
        
        # 当前版本:返回空列表(不生成指标)
        # 避免生成低质量的指标误导用户
        
        return indicators