Spaces:
Runtime error
Runtime error
File size: 43,260 Bytes
ce06eb4 23d3d12 ce06eb4 23d3d12 d3f2aa9 23d3d12 d3f2aa9 23d3d12 d3f2aa9 23d3d12 d3f2aa9 23d3d12 d3f2aa9 23d3d12 d3f2aa9 23d3d12 d3f2aa9 23d3d12 d6c1d4c 23d3d12 d6c1d4c 23d3d12 d6c1d4c d3f2aa9 23d3d12 d6c1d4c 23d3d12 d6c1d4c 23d3d12 d6c1d4c d3f2aa9 d6c1d4c d3f2aa9 23d3d12 d3f2aa9 d6c1d4c 23d3d12 d6c1d4c d3f2aa9 d6c1d4c d3f2aa9 d6c1d4c d3f2aa9 23d3d12 d3f2aa9 d6c1d4c d3f2aa9 d6c1d4c d3f2aa9 d6c1d4c d3f2aa9 d6c1d4c d3f2aa9 d6c1d4c d3f2aa9 d6c1d4c 1419496 d6c1d4c 1419496 d6c1d4c d3f2aa9 d6c1d4c d3f2aa9 d6c1d4c 23d3d12 ce06eb4 23d3d12 ce06eb4 23d3d12 ce06eb4 23d3d12 d6c1d4c ce06eb4 867599c 23d3d12 666608f 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 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 | """
数据指标建模助手 v3.0 - 建模生成Agent模块
本模块实现了ModelingAgent类,负责为指标生成建模产物。
支持批量处理多个指标,可选并行处理以提高效率。
主要功能:
1. 为指标生成SQL查询语句
2. 生成Markdown格式的指标定义文档
3. 生成表结构JSON(用于数据建模)
4. 支持批量处理和并行处理
5. 支持模拟模式和真实API模式
更新日志 (v3.0):
- 输入:IndicatorSet + selected_indicators(选中的指标ID列表)
- 输出:indicator_set(更新后) + schemes(每个指标的建模产物列表)
- 新增批量处理支持
- 新增并行处理支持(可选)
作者: 数据指标建模助手团队
版本: v3.0
日期: 2024
"""
import json
import logging
import re
from datetime import datetime
from typing import Dict, Any, List, Optional
from pathlib import Path
import sys
from concurrent.futures import ThreadPoolExecutor, as_completed # 用于并行处理
# 将项目根目录添加到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 config.prompts import get_modeling_agent_prompt # 提示词模板(单个指标)
from config.prompts import get_modeling_agent_prompt_batch # 提示词模板(批量处理)
from config.settings import ( # 配置参数
DEEPSEEK_API_KEY,
MAX_PARALLEL_WORKERS # 并行处理的最大工作线程数
)
from models.indicator import Indicator # 指标数据模型
from models.indicator_set import IndicatorSet # 指标集数据模型
logger = logging.getLogger(__name__)
class ModelingAgent(BaseAgent):
"""
建模生成Agent,负责生成指标的建模产物(SQL、文档、表结构)
本Agent是数据指标建模助手的核心组件之一,主要职责是根据指标定义,
自动生成SQL查询、指标定义文档和表结构,加速数据建模流程。
更新说明 (v3.0):
- 输入参数:
* indicator_set (IndicatorSet): 指标集(来自RequirementAgent)
* selected_indicators (List[str]): 选中的指标ID列表
- 输出结果:
* indicator_set (IndicatorSet): 更新后的指标集
* schemes (List[dict]): 建模产物列表,每个元素包含:
- indicator_id (str): 指标ID
- indicator_name (str): 指标名称
- markdown (str): Markdown格式的指标定义文档
- sql (str): SQL查询语句
- table_structure (dict): 表结构定义
属性:
api_key (str): DeepSeek API密钥
api_client (DeepSeekClient): API客户端实例
"""
def __init__(
self,
api_key: Optional[str] = None
):
"""
初始化建模生成Agent
构造方法,设置Agent的运行参数并初始化所需的组件。
参数:
api_key (Optional[str]): DeepSeek API密钥
- 如果提供,使用提供的密钥
- 如果为None,使用配置文件中的DEEPSEEK_API_KEY
返回:
无
示例:
>>> # 使用API模式
>>> agent = ModelingAgent(api_key="your-api-key")
"""
# 调用父类构造方法,设置Agent名称
super().__init__(name="ModelingAgent")
# 使用提供的参数或回退到配置文件中的设置
self.api_key = api_key or DEEPSEEK_API_KEY
# 初始化API客户端
self.api_client = None
if self.api_key:
# 初始化DeepSeek API客户端
self.api_client = DeepSeekClient(api_key=self.api_key)
else:
logger.warning("No API key provided. Some features may be unavailable.")
logger.info("ModelingAgent initialized")
def run(self, input_data: Dict[str, Any]) -> Dict[str, Any]:
"""
为所有选中的指标生成建模产物
这是Agent的主入口方法,协调整个建模生成流程:
1. 验证输入数据的有效性
2. 解析指标集(支持dict和IndicatorSet对象)
3. 获取选中的指标ID列表
4. 根据运行模式选择执行路径(模拟/真实)
5. 返回结构化的结果
参数:
input_data (Dict[str, Any]): 输入数据字典,包含:
- indicator_set (IndicatorSet 或 dict): 指标集
- selected_indicators (List[str]): 选中的指标ID列表
返回:
Dict[str, Any]: 包含执行结果的字典:
- status (str): "success" 表示成功,"error" 表示失败
- data (dict, 当status="success"时): 包含:
* indicator_set (IndicatorSet): 更新后的指标集
* schemes (List[dict]): 建模产物列表
- 每个元素包含indicator_id、indicator_name、markdown、sql、table_structure
- error (str, 当status="error"时): 错误描述
示例:
>>> result = agent.run({
... "indicator_set": indicator_set,
... "selected_indicators": ["ind_001", "ind_002"]
... })
>>> if result["status"] == "success":
... schemes = result["data"]["schemes"]
... for scheme in schemes:
... print(f"指标: {scheme['indicator_name']}")
... print(f"SQL长度: {len(scheme['sql'])}")
"""
try:
# 步骤1:验证输入数据
if not self._validate_input(input_data):
return {
"status": "error",
"error": "Invalid input: 'indicator_set' and 'selected_indicators' are required"
}
# 步骤2:解析indicator_set
# 支持两种输入格式:IndicatorSet对象 或 字典
indicator_set = input_data.get("indicator_set")
if isinstance(indicator_set, dict):
indicator_set = IndicatorSet.from_dict(indicator_set)
# 步骤3:获取选中的指标ID列表
selected_indicators = input_data.get("selected_indicators", [])
logger.info(f"Generating schemes for {len(selected_indicators)} indicators...")
# 调用真实模式:使用DeepSeek API生成建模产物
result = self._real_run(indicator_set, selected_indicators)
return {
"status": "success",
"data": result
}
except Exception as e:
logger.error(f"Error in ModelingAgent.run: {e}")
return {
"status": "error",
"error": str(e)
}
def _validate_input(self, input_data: Dict[str, Any]) -> bool:
"""
验证输入数据的有效性
检查输入字典是否包含必需的字段,以及字段值是否符合要求。
参数:
input_data (Dict[str, Any]): 需要验证的输入数据
返回:
bool:
- True: 输入数据有效
- False: 输入数据无效(缺少必需字段或选中指标列表为空)
"""
if not input_data:
return False
indicator_set = input_data.get("indicator_set")
if not indicator_set:
return False
selected_indicators = input_data.get("selected_indicators", [])
if not selected_indicators:
return False # 必须至少选中一个指标
return True
"""
模拟执行:生成预设的建模产物
在模拟模式下,为选中的指标生成预设的SQL、Markdown文档和表结构。
用于开发测试阶段,不依赖外部API,响应速度快。
参数:
indicator_set (IndicatorSet): 指标集
selected_indicators (List[str]): 选中的指标ID列表
返回:
Dict[str, Any]: 包含指标集和建模产物的字典
"""
logger.info("Using mock mode for modeling generation (batch)")
schemes = []
# 为每个选中的指标生成建模产物
for ind_id in selected_indicators:
# 在指标集中查找对应的指标
ind = indicator_set.get_indicator(ind_id)
if not ind:
# 如果找不到指标,记录警告并跳过
logger.warning(f"Indicator {ind_id} not found in set, skipping...")
continue
# 生成SQL查询语句
sql = self._generate_sql(ind)
# 生成Markdown格式的指标定义文档
markdown = self._generate_markdown(ind)
# 生成表结构定义
table_structure = self._generate_table_structure(ind)
# 将建模产物添加到结果列表
schemes.append({
"indicator_id": ind.indicator_id,
"indicator_name": ind.indicator_name,
"markdown": markdown,
"sql": sql,
"table_structure": table_structure
})
logger.info(f"Generated {len(schemes)} schemes")
return {
"indicator_set": indicator_set,
"schemes": schemes
}
def _real_run(
self,
indicator_set: IndicatorSet,
selected_indicators: List[str]
) -> Dict[str, Any]:
"""
真实执行:使用DeepSeek API生成建模产物(批量处理优化 v3.1)
在真实模式下,调用DeepSeek API智能生成建模产物。
v3.1 优化:使用批量处理 prompt,一次性为所有选中指标生成方案(1次API调用)
参数:
indicator_set (IndicatorSet): 指标集
selected_indicators (List[str]): 选中的指标ID列表
返回:
Dict[str, Any]: 包含指标集和建模产物的字典
"""
logger.info("Using real API for modeling generation (BATCH v3.1)")
try:
# 使用批量处理 prompt(1次API调用代替N次)
schemes = self._generate_batch_schemes(indicator_set, selected_indicators)
logger.info(f"Generated {len(schemes)} schemes (batch mode)")
return {
"indicator_set": indicator_set,
"schemes": schemes
}
except Exception as e:
logger.error(f"Batch processing failed, falling back to sequential: {e}")
# 降级到顺序处理
return self._sequential_run(indicator_set, selected_indicators)
def _generate_scheme_for_indicator(
self,
indicator: Indicator,
indicator_set: IndicatorSet
) -> Dict[str, Any]:
"""
为单个指标生成建模产物(SQL、Markdown、表结构)
这是真实模式下的核心方法,调用DeepSeek API生成指定指标的
SQL查询、指标定义文档和表结构定义。
参数:
indicator (Indicator): 需要生成建模产物的指标
indicator_set (IndicatorSet): 父指标集(用于上下文)
返回:
Dict[str, Any]: 生成的建模产物
异常:
如果API调用失败,异常会向上传播,由调用方处理
"""
logger.info(f"Generating scheme for: {indicator.indicator_name}")
# 步骤1:构建提示词(prompt)
# 只传入当前指标,减少 token 消耗
prompt = get_modeling_agent_prompt(
indicator_json=json.dumps(indicator.to_dict(), ensure_ascii=False, indent=2)
)
# 步骤2:调用DeepSeek API
response = self.api_client.call(
system_message="你是一个数据指标建模专家,擅长生成SQL、指标定义文档和表结构。",
prompt=prompt
)
# 确保response是字符串
if isinstance(response, dict):
logger.warning(f"API returned a dict, converting to string: {response}")
response_text = json.dumps(response, ensure_ascii=False)
else:
response_text = str(response)
# 调试:记录API返回内容(前500字符)
logger.info(f"API response for {indicator.indicator_name} (first 500 chars): {response_text[:500]}")
logger.info(f"API response length: {len(response_text)}")
# 步骤3:解析API响应
return self._parse_response(response_text, indicator)
@staticmethod
def _parse_json_with_fallback(json_str: str, response_text: str) -> Dict[str, Any]:
"""
使用多种策略解析JSON,从LLM输出中提取结构化数据
解析策略(按优先级尝试):
1. json5.loads() - 最宽容(支持注释、尾随逗号、单引号等)
2. 如果json5失败且是截断错误,立即尝试修复并重新用json5解析
3. 尝试直接解析 response_text(可能json_str提取有误)
4. json.loads() - 标准JSON解析
5. 修复常见错误后重试
6. 返回原始文本作为markdown降级
参数:
json_str (str): 提取的JSON字符串
response_text (str): 原始响应文本(用于降级和备用解析)
返回:
Dict[str, Any]: 解析后的字典,如果所有策略都失败则返回降级结果
"""
# 策略1:使用 json5 解析(最宽容)
try:
import json5
result = json5.loads(json_str)
logger.info("✅ JSON5解析成功")
return result
except Exception as e:
logger.warning(f"⚠️ JSON5解析失败: {e}")
# 关键改进:如果json5失败是因为截断,立即尝试修复
if "Unexpected end of input" in str(e) or "Unterminated string" in str(e):
logger.warning("⚠️ 检测到JSON截断或未终止字符串,尝试修复...")
# 尝试修复 json_str
repaired = ModelingAgent._truncate_and_close_json(json_str)
if repaired:
try:
result = json5.loads(repaired)
logger.info("✅ JSON5解析成功(修复json_str后)")
return result
except Exception as e2:
logger.warning(f"⚠️ 修复后JSON5仍无法解析: {e2}")
# 也尝试修复整个 response_text
repaired_full = ModelingAgent._truncate_and_close_json(response_text)
if repaired_full:
try:
# 尝试从修复后的全文提取JSON
if "```json" in repaired_full:
test_json = repaired_full.split("```json")[1].split("```")[0].strip()
elif "```" in repaired_full:
test_json = repaired_full.split("```")[1].split("```")[0].strip()
else:
test_json = repaired_full.strip()
result = json5.loads(test_json)
logger.info("✅ JSON5解析成功(修复response_text后)")
return result
except Exception as e3:
logger.warning(f"⚠️ 修复后全文JSON5仍无法解析: {e3}")
# 策略2:尝试直接解析 response_text(可能之前的json_str提取有误)
try:
import json5
result = json5.loads(response_text)
logger.info("✅ 直接解析response_text成功(JSON5)")
return result
except:
pass
# 策略3:标准 json.loads()
try:
result = json.loads(json_str)
logger.info("✅ 标准JSON解析成功")
return result
except json.JSONDecodeError as e:
logger.warning(f"⚠️ 标准JSON解析失败: {e}")
# 策略4:修复常见错误后重试
repaired = ModelingAgent._repair_json(json_str, e)
if repaired and repaired != json_str.strip():
try:
result = json.loads(repaired)
logger.info("✅ 修复后JSON解析成功")
return result
except:
logger.warning("⚠️ 修复后仍无法解析JSON")
# 策略5:降级 - 返回原始文本作为markdown
logger.error("❌ 所有JSON解析策略均失败,返回原始文本")
return {
"markdown": response_text,
"sql": "",
"table_structure": []
}
@staticmethod
def _repair_json(json_str: str, error: Optional[Exception] = None) -> Optional[str]:
"""
修复LLM输出中常见的JSON错误(增强版)
支持的修复:
1. 未终止的字符串 - 在错误位置添加引号
2. 意外的输入结束 - 截断到最后一个完整对象
3. 尾随逗号 - 移除对象/数组末尾的逗号
4. 缺失的逗号 - 在字段之间添加缺失的逗号
5. 缺失的括号 - 自动补全
6. 单引号 - 转换为双引号
参数:
json_str (str): 包含错误的JSON字符串
error (Optional[Exception]): 解析错误对象(可选)
返回:
Optional[str]: 修复后的JSON字符串,如果无法修复则返回None
"""
if not json_str or not isinstance(json_str, str):
return None
repaired = json_str.strip()
# 修复0:如果是 "Unexpected end of input" 或类似截断错误
if error and ("Unexpected end of input" in str(error) or "Unterminated string" in str(error)):
logger.warning("⚠️ 检测到JSON输入意外结束,尝试截断修复...")
# 策略:找到最后一个完整的对象/数组,截断并关闭
truncated = ModelingAgent._truncate_and_close_json(repaired)
if truncated:
return truncated
# 修复1:缺失的逗号(在 "value" 后面缺少逗号,如 "value""key" 或 "value"{)
# 在引号关闭后如果跟着另一个引号或{,添加逗号
repaired = re.sub(r'("\s*)\"\s*"', r'\1", "', repaired) # "value""key" -> "value", "key"
repaired = re.sub(r'("\s*)\}\s*"', r'\1}, "', repaired) # "value"}"key" -> "value"}, "key"
repaired = re.sub(r'("\s*)\]\s*"', r'\1"], "', repaired) # "value"]"key" -> "value"], "key"
# 修复2:未终止的字符串
if error and hasattr(error, 'pos') and error.pos:
pos = error.pos
if pos < len(repaired):
# 在错误位置添加引号
repaired = repaired[:pos] + '"'
# 修复3:尾随逗号(在 } 或 ] 前)
repaired = re.sub(r',\s*([}\]])', r'\1', repaired)
# 修复4:缺失的闭合括号
repaired = ModelingAgent._balance_brackets(repaired)
# 修复5:将单引号键名转换为双引号
repaired = re.sub(r"([{,]\s*)'([^']*)'\s*:", r'\1"\2":', repaired)
# 修复6:移除注释(JSON不支持注释,但LLM可能会加)
repaired = re.sub(r'//[^\n]*', '', repaired)
repaired = re.sub(r'/\*.*?\*/', '', repaired, flags=re.DOTALL)
return repaired if repaired != json_str.strip() else repaired
@staticmethod
def _truncate_and_close_json(json_str: str) -> Optional[str]:
"""
截断不完整的JSON并正确关闭所有括号
用于处理 "Unexpected end of input" 错误
找到最后一个完整的JSON对象/数组,然后正确关闭
参数:
json_str (str): 可能不完整的JSON字符串
返回:
Optional[str]: 修复后的完整JSON字符串
"""
if not json_str:
return None
# 清理可能的markdown代码块标记
cleaned = json_str.strip()
if cleaned.startswith("```"):
cleaned = re.sub(r'^```(json)?\n?', '', cleaned)
if cleaned.endswith("```"):
cleaned = cleaned.rsplit("```", 1)[0]
cleaned = cleaned.strip()
# 策略1:尝试找到 "schemes": [ 并提取完整的数组元素
schemes_match = re.search(r'"schemes"\s*:\s*\[', cleaned)
if schemes_match:
# 找到 schemes 数组的开始位置
array_start = schemes_match.end()
# 尝试解析数组中完整的对象
complete_objects = []
pos = array_start
while pos < len(cleaned):
# 查找对象的开始
obj_start = cleaned.find('{', pos)
if obj_start == -1:
break
# 尝试提取这个对象
obj_str = ModelingAgent._extract_complete_object(cleaned, obj_start)
if obj_str:
try:
# 验证这个是完整的JSON对象
obj = json.loads(obj_str)
complete_objects.append(obj_str)
pos = obj_start + len(obj_str)
except:
# 这个对象不完整,停止
break
else:
break
# 重构JSON - 从零构建,避免不完整的前缀
if complete_objects:
schemes_str = ',\n'.join(complete_objects)
repaired = '{\n "schemes": [\n' + schemes_str + '\n ]\n}'
logger.info(f"✅ 截断修复:保留了 {len(complete_objects)} 个完整方案")
return repaired
# 策略2:通用方法 - 从后往前找到最后一个完整的 } 或 ]
# 需要正确处理字符串内的括号
last_complete = -1
in_string = False
escape_char = False
for i, char in enumerate(cleaned):
if escape_char:
escape_char = False
continue
if char == '\\':
escape_char = True
continue
if char == '"' and not in_string:
in_string = True
continue
if in_string:
if char == '"':
in_string = False
continue
if char in '}':
last_complete = i
elif char in ']':
last_complete = i
if last_complete != -1:
truncated = cleaned[:last_complete + 1]
# 平衡括号
repaired = ModelingAgent._balance_brackets(truncated)
logger.info("✅ 通用截断修复完成")
return repaired
return None
@staticmethod
def _extract_complete_object(json_str: str, start_pos: int) -> Optional[str]:
"""
从指定位置提取一个完整的JSON对象
参数:
json_str (str): JSON字符串
start_pos (int): 对象开始位置({ 的位置)
返回:
Optional[str]: 完整的JSON对象字符串(包含 {}),如果无法提取则返回None
"""
if start_pos >= len(json_str) or json_str[start_pos] != '{':
return None
depth = 0
in_string = False
escape_char = False
for i in range(start_pos, len(json_str)):
char = json_str[i]
if escape_char:
escape_char = False
continue
if char == '\\':
escape_char = True
continue
if char == '"' and not in_string:
in_string = True
continue
if in_string:
if char == '"':
in_string = False
continue
if char == '{':
depth += 1
elif char == '}':
depth -= 1
if depth == 0:
# 找到完整的对象
return json_str[start_pos:i+1]
# 没有找到完整的对象
return None
@staticmethod
def _balance_brackets(json_str: str) -> str:
"""
平衡JSON字符串中的括号
参数:
json_str (str): 可能缺少闭合括号的JSON字符串
返回:
str: 括号平衡的JSON字符串
"""
if not json_str:
return json_str
# 计算未闭合的括号
stack = []
in_string = False
escape_char = False
for i, char in enumerate(json_str):
if escape_char:
escape_char = False
continue
if char == '\\':
escape_char = True
continue
if char == '"' and not in_string:
in_string = True
continue
if in_string:
if char == '"':
in_string = False
continue
if char in '{[':
stack.append(char)
elif char in '}]':
if stack:
stack.pop()
# 添加缺失的闭合括号
while stack:
opening = stack.pop()
if opening == '{':
json_str += '}'
elif opening == '[':
json_str += ']'
return json_str
def _parse_response(self, response_text: str, indicator: Indicator) -> Dict[str, Any]:
"""
解析API响应,提取建模产物
DeepSeek API返回的是文本格式,可能包含JSON代码块。
此方法负责从响应中提取JSON,并格式化为标准的建模产物结构。
参数:
response_text (str): API返回的原始文本
indicator (Indicator): 对应的指标(用于降级)
返回:
Dict[str, Any]: 解析后的建模产物
降级策略:
如果响应不是有效JSON,将整个响应作为Markdown处理
"""
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 = self._parse_json_with_fallback(json_str, response_text)
# 步骤3:提取字段(处理单指标和批处理两种格式)
if "schemes" in result:
# 批处理格式:提取第一个方案
scheme = result["schemes"][0] if result["schemes"] else {}
else:
# 单指标格式:直接使用解析结果
scheme = result
# 步骤4:提取SQL(如果从markdown中提取)
sql = scheme.get("sql", "")
if isinstance(sql, dict):
logger.warning(f"SQL field is a dict, converting to string: {sql}")
sql = str(sql)
markdown = scheme.get("markdown", "")
if isinstance(markdown, dict):
logger.warning(f"Markdown field is a dict, converting to string: {markdown}")
markdown = str(markdown)
# 如果sql字段为空,尝试从markdown中提取SQL代码块
if not sql and markdown:
import re
# 查找 ```sql ... ``` 代码块
sql_match = re.search(r'```sql\n(.*?)\n```', markdown, re.DOTALL)
if sql_match:
sql = sql_match.group(1).strip()
else:
# 查找 ``` ... ``` 代码块(无语言标识)
sql_match = re.search(r'```\n(.*?)\n```', markdown, re.DOTALL)
if sql_match:
sql = sql_match.group(1).strip()
# 步骤5:处理table_structure格式(确保是列表)
table_structure = scheme.get("table_structure", [])
if isinstance(table_structure, dict):
table_structure = [table_structure] # 转换为列表
return {
"indicator_id": scheme.get("indicator_id", indicator.indicator_id),
"indicator_name": scheme.get("indicator_name", indicator.indicator_name),
"markdown": markdown,
"sql": sql,
"table_structure": table_structure
}
except json.JSONDecodeError:
# JSON解析失败:将整个响应作为Markdown处理
logger.warning(f"Failed to parse JSON from API response for {indicator.indicator_name}")
# 尝试从响应中提取SQL
import re
sql = ""
sql_match = re.search(r'```sql\n(.*?)\n```', response_text, re.DOTALL)
if sql_match:
sql = sql_match.group(1).strip()
return {
"indicator_id": indicator.indicator_id,
"indicator_name": indicator.indicator_name,
"markdown": response_text, # 使用整个响应作为Markdown
"sql": sql,
"table_structure": []
}
def generate_batch(
self,
indicators: List[Indicator]
) -> Dict[str, Any]:
"""
便捷方法:为指标列表生成建模产物
创建一个临时的IndicatorSet,然后调用run()方法。
适用于直接传入指标列表的场景。
参数:
indicators (List[Indicator]): 指标列表
返回:
Dict[str, Any]: 与run()方法相同的输出
"""
# 创建临时指标集
temp_set = IndicatorSet(
set_id="temp_set",
set_name="临时指标集",
business_domain="通用",
analysis_purpose="批量生成",
indicators=indicators
)
# 调用run()方法
return self.run({
"indicator_set": temp_set,
"selected_indicators": [ind.indicator_id for ind in indicators]
})
def _generate_sql(self, indicator: Indicator) -> str:
"""
为指标生成模拟SQL查询语句
根据指标的定义(计算逻辑、维度、过滤条件等),
生成对应的SQL查询语句。
参数:
indicator (Indicator): 指标对象
返回:
str: 生成的SQL查询语句
"""
indicator_name = indicator.indicator_name
calculation_logic = indicator.calculation_logic
dimensions = indicator.dimensions
filters = indicator.filters
time_granularity = indicator.time_granularity
# 构建维度字符串(用逗号分隔)
dim_str = ", ".join(dimensions) if dimensions else "date"
# 构建WHERE子句
where_clause = ""
if filters:
where_clause = f"WHERE {' AND '.join(filters)}"
# 构建时间过滤条件(如果在维度中包含date)
time_filter = ""
if "date" in dim_str.lower():
time_filter = "AND date >= '{{start_date}}' AND date <= '{{end_date}}'"
# 生成完整的SQL查询
sql = f"""-- {indicator_name} 查询SQL
SELECT
{dim_str},
{calculation_logic} as metric_value
FROM {indicator.data_source or 'fact_table'}
{where_clause} {time_filter}
GROUP BY {dim_str}
ORDER BY {dim_str};
"""
return sql
def _generate_markdown(self, indicator: Indicator) -> str:
"""
为指标生成模拟Markdown格式的指标定义文档
生成一个完整的指标定义文档,包含指标概述、计算逻辑、
数据来源、维度与度量、使用场景等章节。
参数:
indicator (Indicator): 指标对象
返回:
str: 生成的Markdown文档
"""
# 使用chr(10)表示换行符,避免在f-string中使用\n
md = f"""# {indicator.indicator_name}
## 1. 指标概述
**指标ID**: {indicator.indicator_id}
**指标名称**: {indicator.indicator_name}
**业务含义**: {indicator.business_meaning}
**指标类型**: {'核心KPI' if 'GMV' in indicator.indicator_name or 'DAU' in indicator.indicator_name else '过程指标'}
---
## 2. 计算逻辑
**计算逻辑描述**: {indicator.calculation_logic}
**时间粒度**: {indicator.time_granularity}
**更新频率**: {indicator.update_frequency}
### SQL 逻辑
```sql
{indicator.calculation_logic}
```
---
## 3. 数据来源
**主表**: {indicator.data_source or 'fact_business'}
**关联表**: 无
**过滤条件**: {', '.join(indicator.filters) if indicator.filters else '无'}
---
## 4. 维度与度量
### 维度
{chr(10).join(['- ' + dim for dim in indicator.dimensions]) if indicator.dimensions else '- 无'}
### 度量
{chr(10).join(['- ' + metric for metric in indicator.metrics]) if indicator.metrics else '- 无'}
---
## 5. 使用场景
{indicator.usage_scenario or '通用业务分析'}
---
## 6. 备注
- 本指标由 AI 自动生成,请在使用前进行验证
- 如有疑问,请联系数据团队
---
**生成时间**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
**生成者**: 指标建模助手 v3.0
"""
return md
def _generate_table_structure(self, indicator: Indicator) -> List[Dict[str, Any]]:
"""
为指标生成模拟的表结构定义
根据指标的维度、度量等信息,生成对应的表结构定义。
用于数据建模和表设计。
参数:
indicator (Indicator): 指标对象
返回:
List[Dict[str, Any]]: 表结构定义列表
每个元素是一个字典,包含表名、列定义、索引等
"""
columns = []
# 添加维度列
for dim in indicator.dimensions:
# 根据维度名称推断数据类型
col_type = "DATE" if "date" in dim.lower() else "STRING"
is_partition = "date" in dim.lower() # 日期维度通常作为分区键
col = {
"name": dim,
"type": col_type,
"description": f"{dim} 维度"
}
if is_partition:
col["is_partition_key"] = True
columns.append(col)
# 添加度量列
for metric in indicator.metrics:
# 根据度量名称推断数据类型
col_type = "FLOAT" if any(kw in metric.lower() for kw in ["amount", "rate", "count", "value"]) else "STRING"
columns.append({
"name": metric,
"type": col_type,
"description": f"{metric} 度量"
})
# 添加计算值列(存储计算后的指标值)
columns.append({
"name": "metric_value",
"type": "FLOAT",
"description": "指标计算值"
})
# 构建完整的表结构定义
table_structure = [{
"table_name": f"dw_{indicator.indicator_name.replace(' ', '_').lower()}",
"table_type": "事实表",
"description": f"{indicator.indicator_name} 指标表",
"columns": columns,
"indexes": [
{
"columns": [indicator.dimensions[0]] if indicator.dimensions else ["date"],
"type": "partition"
}
]
}]
return table_structure
def _generate_batch_schemes(
self,
indicator_set: IndicatorSet,
selected_indicators: List[str]
) -> List[Dict[str, Any]]:
"""
批量生成建模产物(1次API调用代替N次)
参数:
indicator_set (IndicatorSet): 指标集
selected_indicators (List[str]): 选中的指标ID列表
返回:
List[Dict[str, Any]]: 建模产物列表
"""
logger.info(f"Batch generating schemes for {len(selected_indicators)} indicators...")
# 步骤1:构建批量处理提示词
prompt = get_modeling_agent_prompt_batch(
indicator_set_json=json.dumps(indicator_set.to_dict(), ensure_ascii=False, indent=2),
selected_indicators=selected_indicators
)
# 步骤2:调用DeepSeek API(1次调用)
response = self.api_client.call(
system_message="你是一个数据指标建模专家,擅长批量生成SQL、指标定义文档和表结构。",
prompt=prompt
)
# 确保response是字符串
if isinstance(response, dict):
logger.warning(f"API returned a dict, converting to string: {response}")
response_text = json.dumps(response, ensure_ascii=False)
else:
response_text = str(response)
logger.info(f"Batch API response length: {len(response_text)}")
# 步骤3:解析批量响应
return self._parse_batch_response(response_text, indicator_set, selected_indicators)
def _parse_batch_response(
self,
response_text: str,
indicator_set: IndicatorSet,
selected_indicators: List[str]
) -> List[Dict[str, Any]]:
"""
解析批量处理的API响应,提取所有指标的建模产物
参数:
response_text (str): API返回的原始文本
indicator_set (IndicatorSet): 指标集(用于降级)
selected_indicators (List[str]): 选中的指标ID列表(用于降级)
返回:
List[Dict[str, Any]]: 建模产物列表
"""
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 = self._parse_json_with_fallback(json_str, response_text)
# 步骤3:提取schemes列表
schemes = result.get("schemes", [])
# 步骤4:验证并格式化每个scheme
formatted_schemes = []
for scheme in schemes:
# 提取字段
indicator_id = scheme.get("indicator_id", "")
indicator_name = scheme.get("indicator_name", "")
markdown = scheme.get("markdown", "")
sql = scheme.get("sql", "")
table_structure = scheme.get("table_structure", [])
# 确保table_structure是列表
if isinstance(table_structure, dict):
table_structure = [table_structure]
formatted_schemes.append({
"indicator_id": indicator_id,
"indicator_name": indicator_name,
"markdown": markdown,
"sql": sql,
"table_structure": table_structure
})
logger.info(f"✅ 从批量响应中解析出 {len(formatted_schemes)} 个方案")
# 如果没有解析出任何方案,抛出异常触发降级到顺序处理
if len(formatted_schemes) == 0:
raise ValueError("批量解析未返回任何方案,降级到顺序处理")
return formatted_schemes
except Exception as e:
logger.error(f"❌ 解析批量响应失败: {e}")
logger.error(f"响应文本 (前500字符): {response_text[:500]}")
# 关键修复:抛出异常,触发降级到顺序处理
# 不再返回降级结果,而是让 _real_run 捕获异常并回退
raise ValueError(f"批量解析失败,降级到顺序处理: {e}")
def _sequential_run(
self,
indicator_set: IndicatorSet,
selected_indicators: List[str]
) -> Dict[str, Any]:
"""
顺序处理模式(降级方案):逐个为指标生成建模产物
参数:
indicator_set (IndicatorSet): 指标集
selected_indicators (List[str]): 选中的指标ID列表
返回:
Dict[str, Any]: 包含指标集和建模产物的字典
"""
logger.info("Using sequential processing (fallback)...")
schemes = []
for ind_id in selected_indicators:
ind = indicator_set.get_indicator(ind_id)
if not ind:
continue
# 生成单个指标的建模产物
scheme = self._generate_scheme_for_indicator(ind, indicator_set)
schemes.append(scheme)
logger.info(f"Generated {len(schemes)} schemes (sequential mode)")
return {
"indicator_set": indicator_set,
"schemes": schemes
}
|