aigroup-econ-mcp 0.4.0__py3-none-any.whl → 0.4.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,13 @@
1
1
  """
2
- 文件解析模块
3
- 支持CSV和JSON格式文件的智能解析和数据转换
2
+ 文件解析与输入处理模块
3
+ 整合了文件解析、数据转换和输入处理功能
4
4
  """
5
5
 
6
6
  import json
7
7
  import csv
8
- from typing import Dict, List, Any, Union, Tuple, Optional
8
+ from typing import Dict, List, Any, Union, Tuple, Optional, Callable
9
9
  from pathlib import Path
10
+ from functools import wraps
10
11
  import io
11
12
  import base64
12
13
 
@@ -540,6 +541,204 @@ class FileParser:
540
541
  return recommendations
541
542
 
542
543
 
544
+ # ============================================================================
545
+ # 文件输入处理组件
546
+ # ============================================================================
547
+
548
+ class FileInputHandler:
549
+ """
550
+ 文件输入处理组件
551
+
552
+ 使用组件模式,为任何工具函数添加文件输入支持
553
+ """
554
+
555
+ @staticmethod
556
+ def process_input(
557
+ file_content: Optional[str],
558
+ file_format: str,
559
+ tool_type: str,
560
+ data_params: Dict[str, Any]
561
+ ) -> Dict[str, Any]:
562
+ """
563
+ 处理文件输入并转换为工具参数
564
+
565
+ Args:
566
+ file_content: 文件内容
567
+ file_format: 文件格式
568
+ tool_type: 工具类型
569
+ data_params: 当前数据参数
570
+
571
+ Returns:
572
+ 更新后的参数字典
573
+ """
574
+ # 如果没有文件输入,直接返回原参数
575
+ if file_content is None:
576
+ return data_params
577
+
578
+ # 解析文件
579
+ parsed = FileParser.parse_file_content(file_content, file_format)
580
+
581
+ # 转换为工具格式
582
+ converted = FileParser.convert_to_tool_format(parsed, tool_type)
583
+
584
+ # 合并参数(文件数据优先)
585
+ result = {**data_params, **converted}
586
+
587
+ return result
588
+
589
+ @staticmethod
590
+ def with_file_support(tool_type: str):
591
+ """
592
+ 装饰器:为工具函数添加文件输入支持
593
+
594
+ Args:
595
+ tool_type: 工具类型(single_var, multi_var_dict, regression, panel等)
596
+
597
+ Returns:
598
+ 装饰后的函数
599
+
600
+ 使用示例:
601
+ @FileInputHandler.with_file_support('regression')
602
+ async def my_regression_tool(y_data, x_data, file_content=None, file_format='auto'):
603
+ # 函数会自动处理file_content并填充y_data和x_data
604
+ pass
605
+ """
606
+ def decorator(func: Callable) -> Callable:
607
+ @wraps(func)
608
+ async def wrapper(*args, **kwargs):
609
+ # 提取文件相关参数
610
+ file_content = kwargs.get('file_content')
611
+ file_format = kwargs.get('file_format', 'auto')
612
+
613
+ if file_content is not None:
614
+ # 处理文件输入
615
+ processed = FileInputHandler.process_input(
616
+ file_content=file_content,
617
+ file_format=file_format,
618
+ tool_type=tool_type,
619
+ data_params=kwargs
620
+ )
621
+
622
+ # 更新kwargs
623
+ kwargs.update(processed)
624
+
625
+ # 调用原函数
626
+ return await func(*args, **kwargs)
627
+
628
+ return wrapper
629
+ return decorator
630
+
631
+
632
+ class FileInputMixin:
633
+ """
634
+ 文件输入混入类
635
+
636
+ 为类提供文件输入处理能力
637
+ """
638
+
639
+ def parse_file_input(
640
+ self,
641
+ file_content: Optional[str],
642
+ file_format: str = "auto"
643
+ ) -> Optional[Dict[str, Any]]:
644
+ """解析文件输入"""
645
+ if file_content is None:
646
+ return None
647
+ return FileParser.parse_file_content(file_content, file_format)
648
+
649
+ def convert_for_tool(
650
+ self,
651
+ parsed_data: Dict[str, Any],
652
+ tool_type: str
653
+ ) -> Dict[str, Any]:
654
+ """转换为工具格式"""
655
+ return FileParser.convert_to_tool_format(parsed_data, tool_type)
656
+
657
+ def get_recommendations(
658
+ self,
659
+ parsed_data: Dict[str, Any]
660
+ ) -> Dict[str, Any]:
661
+ """获取工具推荐"""
662
+ return FileParser.auto_detect_tool_params(parsed_data)
663
+
664
+
665
+ class UnifiedFileInput:
666
+ """
667
+ 统一文件输入接口
668
+
669
+ 所有工具通过此类统一处理文件输入
670
+ """
671
+
672
+ @staticmethod
673
+ async def handle(
674
+ ctx: Any,
675
+ file_content: Optional[str],
676
+ file_format: str,
677
+ tool_type: str,
678
+ original_params: Dict[str, Any]
679
+ ) -> Dict[str, Any]:
680
+ """
681
+ 统一处理文件输入
682
+
683
+ Args:
684
+ ctx: MCP上下文
685
+ file_content: 文件内容
686
+ file_format: 文件格式
687
+ tool_type: 工具类型
688
+ original_params: 原始参数
689
+
690
+ Returns:
691
+ 处理后的参数
692
+ """
693
+ if file_content is None:
694
+ return original_params
695
+
696
+ try:
697
+ # 记录日志
698
+ await ctx.info("检测到文件输入,开始解析...")
699
+
700
+ # 解析文件
701
+ parsed = FileParser.parse_file_content(file_content, file_format)
702
+
703
+ # 记录解析结果
704
+ await ctx.info(
705
+ f"文件解析成功:{parsed['n_variables']}个变量,"
706
+ f"{parsed['n_observations']}个观测,"
707
+ f"数据类型={parsed['data_type']}"
708
+ )
709
+
710
+ # 转换为工具格式
711
+ converted = FileParser.convert_to_tool_format(parsed, tool_type)
712
+
713
+ # 合并参数
714
+ result = {**original_params}
715
+ result.update(converted)
716
+
717
+ # 记录转换结果
718
+ if tool_type == 'regression':
719
+ await ctx.info(
720
+ f"数据已转换:因变量={converted.get('y_variable')},"
721
+ f"自变量={converted.get('feature_names')}"
722
+ )
723
+ elif tool_type == 'panel':
724
+ await ctx.info(
725
+ f"面板数据已识别:{len(set(converted.get('entity_ids', [])))}个实体,"
726
+ f"{len(set(converted.get('time_periods', [])))}个时间点"
727
+ )
728
+ else:
729
+ await ctx.info(f"数据已转换为{tool_type}格式")
730
+
731
+ return result
732
+
733
+ except Exception as e:
734
+ await ctx.error(f"文件解析失败: {str(e)}")
735
+ raise ValueError(f"文件解析失败: {str(e)}")
736
+
737
+
738
+ # ============================================================================
739
+ # 便捷函数和参数定义
740
+ # ============================================================================
741
+
543
742
  def parse_file_input(
544
743
  file_content: Optional[str] = None,
545
744
  file_format: str = "auto"
@@ -557,4 +756,74 @@ def parse_file_input(
557
756
  if file_content is None:
558
757
  return None
559
758
 
560
- return FileParser.parse_file_content(file_content, file_format)
759
+ return FileParser.parse_file_content(file_content, file_format)
760
+
761
+
762
+ async def process_file_for_tool(
763
+ ctx: Any,
764
+ file_content: Optional[str],
765
+ file_format: str,
766
+ tool_type: str,
767
+ **kwargs
768
+ ) -> Dict[str, Any]:
769
+ """
770
+ 为工具处理文件输入的便捷函数
771
+
772
+ 使用示例:
773
+ params = await process_file_for_tool(
774
+ ctx=ctx,
775
+ file_
776
+ content=file_content,
777
+ file_format=file_format,
778
+ tool_type='regression',
779
+ y_data=y_data,
780
+ x_data=x_data,
781
+ feature_names=feature_names
782
+ )
783
+ # params 现在包含处理后的所有参数
784
+ """
785
+ return await UnifiedFileInput.handle(
786
+ ctx=ctx,
787
+ file_content=file_content,
788
+ file_format=file_format,
789
+ tool_type=tool_type,
790
+ original_params=kwargs
791
+ )
792
+
793
+
794
+ def create_file_params(
795
+ description: str = "CSV或JSON文件内容"
796
+ ) -> Dict[str, Any]:
797
+ """
798
+ 创建标准的文件输入参数定义
799
+
800
+ Args:
801
+ description: 参数描述
802
+
803
+ Returns:
804
+ 参数定义字典,可直接用于Field()
805
+ """
806
+ return {
807
+ "file_content": {
808
+ "default": None,
809
+ "description": f"""{description}
810
+
811
+ 📁 支持格式:
812
+ - CSV: 带表头的列数据,自动检测分隔符
813
+ - JSON: {{"变量名": [数据], ...}} 或 [{{"变量1": 值, ...}}, ...]
814
+
815
+ 💡 使用方式:
816
+ - 提供文件内容字符串(可以是base64编码)
817
+ - 系统会自动解析并识别变量
818
+ - 优先使用file_content,如果提供则忽略其他数据参数"""
819
+ },
820
+ "file_format": {
821
+ "default": "auto",
822
+ "description": """文件格式
823
+
824
+ 可选值:
825
+ - "auto": 自动检测(默认)
826
+ - "csv": CSV格式
827
+ - "json": JSON格式"""
828
+ }
829
+ }