@roll-agent/octopus-agent 0.0.11 → 0.1.1
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.
- package/README.md +18 -1
- package/SKILL.md +76 -35
- package/package.json +1 -1
- package/pyproject.toml +1 -1
- package/references/env.yaml +4 -0
- package/src/octopus_skill/_version.py +1 -1
- package/src/octopus_skill/agent.py +4267 -1108
- package/src/octopus_skill/config.py +22 -25
- package/src/octopus_skill/exporter.py +66 -0
- package/src/octopus_skill/llm_result_renderer.py +101 -0
- package/src/octopus_skill/llm_sql_generator.py +72 -7
- package/src/octopus_skill/mcp_client.py +4 -4
- package/src/octopus_skill/octopus_run.py +287 -293
- package/src/octopus_skill/prompt_builder.py +444 -81
- package/src/octopus_skill/question_analyzer.py +399 -0
- package/src/octopus_skill/result_renderer.py +38 -14
- package/src/octopus_skill/schema_context_retriever.py +759 -35
- package/src/octopus_skill/sql_generator.py +2120 -763
- package/src/octopus_skill/entity_binding.py +0 -523
- package/src/octopus_skill/entity_dictionary.py +0 -59
- package/src/octopus_skill/entity_resolver.py +0 -446
|
@@ -2,43 +2,26 @@ from __future__ import annotations
|
|
|
2
2
|
|
|
3
3
|
import json
|
|
4
4
|
import re
|
|
5
|
-
from typing import Any
|
|
5
|
+
from typing import Any, Literal
|
|
6
6
|
|
|
7
7
|
from .schema_context_retriever import SchemaContext
|
|
8
8
|
from .sql_generator import normalize_text_filters_to_like
|
|
9
9
|
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
所有默认过滤(软删除、有效性等)必须使用 schemaContext.tableDefaults 给出的条件。
|
|
26
|
-
所有业务指标口径必须使用 schemaContext.metrics 的 definition、aggregation、filters;所有状态枚举、状态映射必须使用 schemaContext.enums,不得自行推断状态值。
|
|
27
|
-
岗位总数、岗位数、职位总数、职位数只表示岗位记录数量,不等于在招岗位数;用户只说“总数”“查询总数”“统计总数”且未提在招/已发布/已上架时,按全部岗位记录计数,不要默认加 status=在招 过滤,SELECT 别名必须使用用户原词(例如 AS 总数),禁止写成 AS 在招岗位数。
|
|
28
|
-
除非用户明确说在招、已发布、已上架等状态词,或 schemaContext.metrics 的指标定义明确要求状态过滤,否则不要默认加岗位状态过滤,也不要把输出别名写成在招/已发布。
|
|
29
|
-
用户明确说在招、已发布、已上架、未发布、已下架等状态词时,必须从 schemaContext.enums 找到对应字段和值并用于 WHERE;例如枚举 label 命中“已发布/已上架/在招”时,只能使用该 label 对应的枚举值,不得把未发布、已下架等其他状态一起放入 IN。
|
|
30
|
-
只有用户明确要求多个状态(例如“岗位状态包括已发布、已下架、未发布”)时,才允许使用这些状态对应枚举值组成 IN。
|
|
31
|
-
字段语义、时间字段选择、地点层级、实体口径等都必须遵循 schemaContext.glossary 的说明。
|
|
32
|
-
如果 schemaContext 没有明确给出所需的表、字段、JOIN、枚举或指标口径,不要猜测;返回 {"sql":"","tables":[],"placeholders":[],"usedColumns":[],"usedJoins":[],"metricRefs":[]}。
|
|
33
|
-
业务查询必须一次生成完整 SQL,不要先查单表列表找 ID,也不要要求外部先提供 ID;需要按名称过滤时直接 JOIN 对应表并使用 name/job_name LIKE。
|
|
34
|
-
如果输入提供了 resolvedEntities,这些是已校正的真实实体(口语、简称、别名、错字已归一到标准名);必须使用 resolvedEntities 中的标准名称或 id 作为过滤条件,并通过 schemaContext.joins / schemaContext.examples 关联到对应业务表,不要再用用户原始口语词做 LIKE,也不要自行猜测实体所属的表或层级。
|
|
35
|
-
resolvedEntities 给出的 table/column/id 表示该实体在主数据表中的位置;若主数据表与业务事实表之间存在关联表,必须按 schemaContext.joins 给出的关联路径连接。
|
|
36
|
-
resolvedEntities.location 可能同时给出 province、city、region 多个层级;必须按其中最细粒度过滤(有 region 用 region,没有才退到 city,再退到 province)。
|
|
37
|
-
resolvedEntities 中给出的每一个实体都必须在 WHERE 中体现为过滤条件,一个都不能省略。
|
|
38
|
-
用户问题包含时间范围时,SQL 的 WHERE 必须直接包含对应时间字段过滤;时间字段按 schemaContext.glossary 的说明选择。
|
|
39
|
-
必须包含 LIMIT,且 LIMIT 不超过 500。
|
|
40
|
-
不要使用 WITH;低版本 MySQL 不支持公共表表达式,请使用 JOIN 或派生表。
|
|
41
|
-
只输出 JSON,不输出解释文本、拒绝文本或 Markdown。"""
|
|
11
|
+
InstructionStage = Literal["before", "during", "after"]
|
|
12
|
+
|
|
13
|
+
INSTRUCTION_STAGE_PREFIX: dict[InstructionStage, str] = {
|
|
14
|
+
"before": "【生成前】",
|
|
15
|
+
"during": "【生成中】",
|
|
16
|
+
"after": "【执行后】",
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
NL2SQL_SYSTEM_PROMPT = """你是丸子Agent(Octopus Agent)的海绵数据 SQL 专家,一名专业 MySQL SQL 专家。
|
|
21
|
+
你必须以 SQL 专家的标准生成 SQL:输出前逐句自检,确保 SQL 整体可以直接执行,没有任何 SQL 语法错误,也没有 SQL 写法问题(如括号/引号不闭合、SELECT 与 GROUP BY 不一致、聚合函数误用、JOIN 缺少等值键、别名冲突、字段/表拼写错误等)。
|
|
22
|
+
业务规则的唯一来源是 payload 中的 mandatoryAgentInstructions 与 schemaContext.policy;必须逐条遵守,不得使用训练记忆中的业务口径替代 schema 要求。
|
|
23
|
+
生成 SQL 前必须严格按 schemaContext.readOrder 顺序阅读 schemaContext 各段内容,再组合 SELECT、JOIN、WHERE、LIMIT。
|
|
24
|
+
只输出 JSON,结构见 outputSchema。返回 JSON 中的 sql 字段必须直接以 SELECT 开头;不要为了状态枚举单独返回 clarification。用户明确提出状态筛选时把状态条件写入 WHERE;用户未提出状态筛选或 schemaContext 缺少枚举时不要追问,首次查询保持宽泛,并把相关状态字段及中文含义加入 SELECT 结果。"""
|
|
42
25
|
|
|
43
26
|
|
|
44
27
|
def build_nl2sql_prompt(
|
|
@@ -47,32 +30,22 @@ def build_nl2sql_prompt(
|
|
|
47
30
|
schema_context: SchemaContext,
|
|
48
31
|
default_limit: int,
|
|
49
32
|
max_limit: int,
|
|
50
|
-
|
|
33
|
+
confirmed_query_plan: dict[str, Any] | None = None,
|
|
51
34
|
) -> str:
|
|
52
|
-
payload =
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
"
|
|
65
|
-
|
|
66
|
-
"tables": ["table_name"],
|
|
67
|
-
"placeholders": [],
|
|
68
|
-
"usedColumns": ["table.column"],
|
|
69
|
-
"usedJoins": ["left_table.left_column = right_table.right_column"],
|
|
70
|
-
"metricRefs": ["schemaContext.metrics.name"],
|
|
71
|
-
},
|
|
72
|
-
}
|
|
73
|
-
if resolved_entities:
|
|
74
|
-
payload["resolvedEntities"] = resolved_entities
|
|
75
|
-
return json.dumps(payload, ensure_ascii=False, indent=2)
|
|
35
|
+
payload = _base_sql_prompt_payload(
|
|
36
|
+
question=question,
|
|
37
|
+
schema_context=schema_context,
|
|
38
|
+
default_limit=default_limit,
|
|
39
|
+
max_limit=max_limit,
|
|
40
|
+
confirmed_query_plan=confirmed_query_plan,
|
|
41
|
+
)
|
|
42
|
+
compact = confirmed_query_plan is not None
|
|
43
|
+
return json.dumps(
|
|
44
|
+
payload,
|
|
45
|
+
ensure_ascii=False,
|
|
46
|
+
indent=None if compact else 2,
|
|
47
|
+
separators=(",", ":") if compact else (", ", ": "),
|
|
48
|
+
)
|
|
76
49
|
|
|
77
50
|
|
|
78
51
|
def build_sql_repair_prompt(
|
|
@@ -83,35 +56,425 @@ def build_sql_repair_prompt(
|
|
|
83
56
|
schema_context: SchemaContext,
|
|
84
57
|
default_limit: int,
|
|
85
58
|
max_limit: int,
|
|
86
|
-
|
|
59
|
+
confirmed_query_plan: dict[str, Any] | None = None,
|
|
87
60
|
) -> str:
|
|
88
|
-
payload =
|
|
89
|
-
|
|
61
|
+
payload = _base_sql_prompt_payload(
|
|
62
|
+
question=question,
|
|
63
|
+
schema_context=schema_context,
|
|
64
|
+
default_limit=default_limit,
|
|
65
|
+
max_limit=max_limit,
|
|
66
|
+
confirmed_query_plan=confirmed_query_plan,
|
|
67
|
+
task="repair_sql",
|
|
68
|
+
original_sql=original_sql,
|
|
69
|
+
validation_error=validation_error,
|
|
70
|
+
)
|
|
71
|
+
compact = confirmed_query_plan is not None
|
|
72
|
+
return json.dumps(
|
|
73
|
+
payload,
|
|
74
|
+
ensure_ascii=False,
|
|
75
|
+
indent=None if compact else 2,
|
|
76
|
+
separators=(",", ":") if compact else (", ", ": "),
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def build_sql_expert_review_prompt(
|
|
81
|
+
*,
|
|
82
|
+
question: str,
|
|
83
|
+
sql: str,
|
|
84
|
+
schema_context: SchemaContext,
|
|
85
|
+
default_limit: int,
|
|
86
|
+
max_limit: int,
|
|
87
|
+
confirmed_query_plan: dict[str, Any] | None = None,
|
|
88
|
+
) -> str:
|
|
89
|
+
payload = _base_sql_prompt_payload(
|
|
90
|
+
question=question,
|
|
91
|
+
schema_context=schema_context,
|
|
92
|
+
default_limit=default_limit,
|
|
93
|
+
max_limit=max_limit,
|
|
94
|
+
confirmed_query_plan=confirmed_query_plan,
|
|
95
|
+
task="review_sql_executability",
|
|
96
|
+
original_sql=sql,
|
|
97
|
+
)
|
|
98
|
+
payload["reviewInstruction"] = (
|
|
99
|
+
"你是专业 MySQL SQL 专家,只检查 SQL 写法是否整体可执行,不改变业务口径。"
|
|
100
|
+
"重点检查:聚合函数是否误写在 WHERE/JOIN ON;GROUP BY/HAVING 是否合法;"
|
|
101
|
+
"子查询和派生表别名是否完整;外层引用的派生表字段是否存在;"
|
|
102
|
+
"SELECT 中非聚合字段与 GROUP BY 是否兼容;MySQL 低版本不支持 WITH。"
|
|
103
|
+
"如果 SQL 可执行,返回 executable=true 且 repairedSql 为空;"
|
|
104
|
+
"如果不可执行,返回 executable=false、issues,并在不改变业务口径和 schema 字段的前提下给出 repairedSql。"
|
|
105
|
+
)
|
|
106
|
+
payload["reviewOutputSchema"] = {
|
|
107
|
+
"executable": True,
|
|
108
|
+
"issues": [{"code": "ISSUE_CODE", "message": "中文问题说明", "repairHint": "中文修复建议"}],
|
|
109
|
+
"repairedSql": "SELECT ... LIMIT 50 或空字符串",
|
|
110
|
+
}
|
|
111
|
+
compact = confirmed_query_plan is not None
|
|
112
|
+
return json.dumps(
|
|
113
|
+
payload,
|
|
114
|
+
ensure_ascii=False,
|
|
115
|
+
indent=None if compact else 2,
|
|
116
|
+
separators=(",", ":") if compact else (", ", ": "),
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _base_sql_prompt_payload(
|
|
121
|
+
*,
|
|
122
|
+
question: str,
|
|
123
|
+
schema_context: SchemaContext,
|
|
124
|
+
default_limit: int,
|
|
125
|
+
max_limit: int,
|
|
126
|
+
confirmed_query_plan: dict[str, Any] | None = None,
|
|
127
|
+
task: str | None = None,
|
|
128
|
+
original_sql: str | None = None,
|
|
129
|
+
validation_error: dict[str, Any] | None = None,
|
|
130
|
+
) -> dict[str, Any]:
|
|
131
|
+
compact = confirmed_query_plan is not None
|
|
132
|
+
instruction_lines = _agent_instruction_lines(schema_context)
|
|
133
|
+
payload: dict[str, Any] = {
|
|
134
|
+
"mandatoryAgentInstructions": instruction_lines,
|
|
135
|
+
"instruction": (
|
|
136
|
+
"生成或修复 SQL 前必须先完整阅读 mandatoryAgentInstructions,"
|
|
137
|
+
"再按 schemaContext.readOrder 阅读 schemaContext;"
|
|
138
|
+
"WHERE/SELECT/JOIN/LIMIT/字段别名/澄清策略均以 mandatoryAgentInstructions 与 schemaContext 为准。"
|
|
139
|
+
"涉及业务口径的查询必须优先使用 schemaContext.concepts、metrics、examples 或 exampleJoinPatterns;"
|
|
140
|
+
"schemaContext 未提供对应口径时,不要凭训练记忆或字段名猜测 SQL。"
|
|
141
|
+
"涉及时间范围时,如果命中的 schemaContext.concepts 或 metrics 提供 timeRangeField,"
|
|
142
|
+
"必须使用该字段生成 WHERE 时间过滤,不要改用关联维表的同名时间字段。"
|
|
143
|
+
"JOIN ... ON 只能写 schemaContext.relations / joins / exampleJoinPatterns 中提供的等值关联键;"
|
|
144
|
+
"禁止凭字段名相似或训练记忆新增 schema 未定义 JOIN。"
|
|
145
|
+
"涉及“最多/最高/最大/排名/排行”等聚合极值诉求时,必须优先按聚合指标倒序排序,"
|
|
146
|
+
"再按时间等次要维度排序。"
|
|
147
|
+
"你必须作为专业 MySQL SQL 专家自检 SQL 整体可执行性:聚合函数不能写在 WHERE/JOIN ON,"
|
|
148
|
+
"聚合筛选必须放 HAVING 或先在子查询聚合后外层过滤;派生表字段和别名必须真实存在;"
|
|
149
|
+
"MySQL 低版本不支持 WITH。"
|
|
150
|
+
"不要把查询动作、状态变化、时间词或范围词当作名称筛选;"
|
|
151
|
+
"只有用户明确说“名称包含/岗位名称是/叫做/简称为”时,才允许对 name/title/job_name 写 LIKE。"
|
|
152
|
+
if not compact
|
|
153
|
+
else
|
|
154
|
+
"生成或修复 SQL 前必须先完整阅读 mandatoryAgentInstructions,"
|
|
155
|
+
"再按 schemaContext.readOrder 阅读 schemaContext;"
|
|
156
|
+
"confirmedQueryPlan 提供实体、筛选与输出字段,schemaContext 提供表结构、JOIN 与 policy。"
|
|
157
|
+
"涉及业务口径的查询必须优先使用 schemaContext.concepts、metrics、examples 或 exampleJoinPatterns;"
|
|
158
|
+
"schemaContext 未提供对应口径时,不要凭训练记忆或字段名猜测 SQL。"
|
|
159
|
+
"涉及时间范围时,如果命中的 schemaContext.concepts 或 metrics 提供 timeRangeField,"
|
|
160
|
+
"必须使用该字段生成 WHERE 时间过滤,不要改用关联维表的同名时间字段。"
|
|
161
|
+
"JOIN ... ON 只能写 schemaContext.relations / joins / exampleJoinPatterns 中提供的等值关联键;"
|
|
162
|
+
"禁止凭字段名相似或训练记忆新增 schema 未定义 JOIN。"
|
|
163
|
+
"涉及“最多/最高/最大/排名/排行”等聚合极值诉求时,必须优先按聚合指标倒序排序,"
|
|
164
|
+
"再按时间等次要维度排序。"
|
|
165
|
+
"你必须作为专业 MySQL SQL 专家自检 SQL 整体可执行性:聚合函数不能写在 WHERE/JOIN ON,"
|
|
166
|
+
"聚合筛选必须放 HAVING 或先在子查询聚合后外层过滤;派生表字段和别名必须真实存在;"
|
|
167
|
+
"MySQL 低版本不支持 WITH。"
|
|
168
|
+
"JOIN ... ON 只能写 schema relations / joins 中的等值关联键(如 a.id = b.x_id);"
|
|
169
|
+
"confirmedQueryPlan.filters 里的 LIKE/IN 筛选必须写在 WHERE,禁止写在 JOIN ON;"
|
|
170
|
+
"同一 logicalGroup 且 logicalOperator=OR 的筛选必须用 OR 连接,并用括号包裹;"
|
|
171
|
+
"confirmedQueryPlan.fields 中 required=true 的字段必须出现在 SELECT 中;"
|
|
172
|
+
"不要把查询动作、状态变化、时间词或范围词当作名称筛选。"
|
|
173
|
+
),
|
|
90
174
|
"question": question,
|
|
91
|
-
"originalSql": original_sql,
|
|
92
|
-
"validationError": validation_error,
|
|
93
175
|
"limits": {"defaultLimit": default_limit, "maxLimit": max_limit},
|
|
94
|
-
"schemaContext":
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
"
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
176
|
+
"schemaContext": _schema_context_payload(schema_context, compact=compact),
|
|
177
|
+
"outputSchema": _sql_output_schema(default_limit, question),
|
|
178
|
+
}
|
|
179
|
+
if task:
|
|
180
|
+
payload["task"] = task
|
|
181
|
+
if task == "repair_sql":
|
|
182
|
+
payload["originalSql"] = original_sql or ""
|
|
183
|
+
payload["validationError"] = validation_error or {}
|
|
184
|
+
elif task == "review_sql_executability":
|
|
185
|
+
payload["sqlToReview"] = original_sql or ""
|
|
186
|
+
if confirmed_query_plan:
|
|
187
|
+
payload["confirmedQueryPlan"] = _compact_query_plan_for_sql(confirmed_query_plan)
|
|
188
|
+
return payload
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def instruction_text(item: dict[str, Any]) -> str:
|
|
192
|
+
return str(item.get("text") or item.get("instruction") or item.get("content") or "").strip()
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def filter_agent_instructions_by_stage(
|
|
196
|
+
instructions: list[dict[str, Any]],
|
|
197
|
+
stage: InstructionStage,
|
|
198
|
+
) -> list[str]:
|
|
199
|
+
prefix = INSTRUCTION_STAGE_PREFIX[stage]
|
|
200
|
+
texts: list[str] = []
|
|
201
|
+
for item in instructions:
|
|
202
|
+
if not isinstance(item, dict):
|
|
203
|
+
continue
|
|
204
|
+
text = instruction_text(item)
|
|
205
|
+
if text.startswith(prefix):
|
|
206
|
+
texts.append(text)
|
|
207
|
+
return texts
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def format_numbered_instruction_lines(texts: list[str]) -> list[str]:
|
|
211
|
+
return [f"{index}. {text}" for index, text in enumerate(texts, start=1)]
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _agent_instruction_lines(
|
|
215
|
+
schema_context: SchemaContext,
|
|
216
|
+
*,
|
|
217
|
+
stage: InstructionStage = "during",
|
|
218
|
+
) -> list[str]:
|
|
219
|
+
texts = filter_agent_instructions_by_stage(schema_context.agent_instructions, stage)
|
|
220
|
+
return format_numbered_instruction_lines(texts)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _filtered_agent_instruction_items(
|
|
224
|
+
instructions: list[dict[str, Any]],
|
|
225
|
+
*,
|
|
226
|
+
stage: InstructionStage,
|
|
227
|
+
) -> list[dict[str, Any]]:
|
|
228
|
+
prefix = INSTRUCTION_STAGE_PREFIX[stage]
|
|
229
|
+
items: list[dict[str, Any]] = []
|
|
230
|
+
for item in instructions:
|
|
231
|
+
if not isinstance(item, dict):
|
|
232
|
+
continue
|
|
233
|
+
text = instruction_text(item)
|
|
234
|
+
if text.startswith(prefix):
|
|
235
|
+
items.append({"text": text})
|
|
236
|
+
return items
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _compact_query_plan_for_sql(query_plan: dict[str, Any]) -> dict[str, Any]:
|
|
240
|
+
compact: dict[str, Any] = {}
|
|
241
|
+
question = query_plan.get("question")
|
|
242
|
+
if isinstance(question, str) and question.strip():
|
|
243
|
+
compact["question"] = question.strip()
|
|
244
|
+
entities = [
|
|
245
|
+
{
|
|
246
|
+
key: entity[key]
|
|
247
|
+
for key in ("label", "type", "value", "source", "logicalGroup", "logicalOperator")
|
|
248
|
+
if key in entity
|
|
249
|
+
}
|
|
250
|
+
for entity in query_plan.get("entities", [])
|
|
251
|
+
if isinstance(entity, dict)
|
|
252
|
+
]
|
|
253
|
+
if entities:
|
|
254
|
+
compact["entities"] = entities
|
|
255
|
+
plan_filters = query_plan.get("_sqlFilters")
|
|
256
|
+
if not isinstance(plan_filters, list):
|
|
257
|
+
plan_filters = query_plan.get("filters", [])
|
|
258
|
+
filters = [
|
|
259
|
+
{
|
|
260
|
+
key: item[key]
|
|
261
|
+
for key in ("field", "operator", "value", "description", "source", "logicalGroup", "logicalOperator")
|
|
262
|
+
if key in item
|
|
263
|
+
}
|
|
264
|
+
for item in plan_filters
|
|
265
|
+
if isinstance(item, dict)
|
|
266
|
+
]
|
|
267
|
+
if filters:
|
|
268
|
+
compact["filters"] = filters
|
|
269
|
+
fields = [
|
|
270
|
+
{key: item[key] for key in ("table", "field", "description", "source", "required") if key in item}
|
|
271
|
+
for item in query_plan.get("fields", [])
|
|
272
|
+
if isinstance(item, dict)
|
|
273
|
+
]
|
|
274
|
+
if fields:
|
|
275
|
+
compact["fields"] = fields
|
|
276
|
+
tables = [
|
|
277
|
+
{key: item[key] for key in ("name", "description") if key in item}
|
|
278
|
+
for item in query_plan.get("tables", [])
|
|
279
|
+
if isinstance(item, dict) and item.get("name")
|
|
280
|
+
]
|
|
281
|
+
if tables:
|
|
282
|
+
compact["tables"] = tables
|
|
283
|
+
return compact
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _schema_context_payload(schema_context: SchemaContext, *, compact: bool = False) -> dict[str, Any]:
|
|
287
|
+
selected_tables = {
|
|
288
|
+
str(table.get("tableName") or table.get("name") or "")
|
|
289
|
+
for table in schema_context.tables
|
|
290
|
+
if isinstance(table, dict)
|
|
291
|
+
}
|
|
292
|
+
selected_tables.discard("")
|
|
293
|
+
relations = schema_context.relations
|
|
294
|
+
policy = schema_context.policy
|
|
295
|
+
if compact:
|
|
296
|
+
relations = _slim_relations(relations, selected_tables)
|
|
297
|
+
policy = _slim_policy(policy, selected_tables)
|
|
298
|
+
payload: dict[str, Any] = {
|
|
299
|
+
"readOrder": _schema_read_order(compact=compact),
|
|
300
|
+
"policy": policy,
|
|
301
|
+
"schema": {"tables": schema_context.tables},
|
|
302
|
+
"joins": schema_context.manual_joins,
|
|
303
|
+
"relations": relations,
|
|
304
|
+
"defaultFilters": schema_context.default_filters,
|
|
305
|
+
"enums": schema_context.enums,
|
|
306
|
+
"businessTerms": schema_context.business_terms,
|
|
307
|
+
"concepts": schema_context.concepts,
|
|
308
|
+
"metrics": schema_context.metrics,
|
|
309
|
+
"exampleJoinPatterns": schema_context.example_join_patterns,
|
|
310
|
+
"exampleGuidance": schema_context.example_guidance,
|
|
311
|
+
"structureHints": schema_context.structure_hints,
|
|
312
|
+
"examples": _business_examples(schema_context.examples),
|
|
313
|
+
}
|
|
314
|
+
if not compact:
|
|
315
|
+
payload["agentInstructions"] = _filtered_agent_instruction_items(
|
|
316
|
+
schema_context.agent_instructions,
|
|
317
|
+
stage="during",
|
|
318
|
+
)
|
|
319
|
+
payload["glossary"] = schema_context.glossary_terms
|
|
320
|
+
payload["tables"] = schema_context.tables
|
|
321
|
+
if compact:
|
|
322
|
+
if not payload["businessTerms"]:
|
|
323
|
+
payload.pop("businessTerms", None)
|
|
324
|
+
if not payload["metrics"]:
|
|
325
|
+
payload.pop("metrics", None)
|
|
326
|
+
if not payload["exampleJoinPatterns"]:
|
|
327
|
+
payload.pop("exampleJoinPatterns", None)
|
|
328
|
+
if not payload.get("exampleGuidance"):
|
|
329
|
+
payload.pop("exampleGuidance", None)
|
|
330
|
+
if not payload.get("structureHints"):
|
|
331
|
+
payload.pop("structureHints", None)
|
|
332
|
+
if not payload["examples"]:
|
|
333
|
+
payload.pop("examples", None)
|
|
334
|
+
if not payload["enums"]:
|
|
335
|
+
payload.pop("enums", None)
|
|
336
|
+
if not payload["defaultFilters"]:
|
|
337
|
+
payload.pop("defaultFilters", None)
|
|
338
|
+
if not payload["joins"]:
|
|
339
|
+
payload.pop("joins", None)
|
|
340
|
+
else:
|
|
341
|
+
if not payload.get("glossary"):
|
|
342
|
+
payload.pop("glossary", None)
|
|
343
|
+
if not payload["businessTerms"]:
|
|
344
|
+
payload.pop("businessTerms", None)
|
|
345
|
+
if not payload["metrics"]:
|
|
346
|
+
payload.pop("metrics", None)
|
|
347
|
+
if not payload["exampleJoinPatterns"]:
|
|
348
|
+
payload.pop("exampleJoinPatterns", None)
|
|
349
|
+
if not payload.get("exampleGuidance"):
|
|
350
|
+
payload.pop("exampleGuidance", None)
|
|
351
|
+
if not payload.get("structureHints"):
|
|
352
|
+
payload.pop("structureHints", None)
|
|
353
|
+
if not payload["examples"]:
|
|
354
|
+
payload.pop("examples", None)
|
|
355
|
+
if not payload["enums"]:
|
|
356
|
+
payload.pop("enums", None)
|
|
357
|
+
if not payload["defaultFilters"]:
|
|
358
|
+
payload.pop("defaultFilters", None)
|
|
359
|
+
return payload
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def _slim_relations(
|
|
363
|
+
relations: list[dict[str, Any]],
|
|
364
|
+
selected_tables: set[str],
|
|
365
|
+
) -> list[dict[str, Any]]:
|
|
366
|
+
slim: list[dict[str, Any]] = []
|
|
367
|
+
for relation in relations:
|
|
368
|
+
if not isinstance(relation, dict):
|
|
369
|
+
continue
|
|
370
|
+
left_table, right_table = _relation_endpoint_tables(relation)
|
|
371
|
+
if left_table not in selected_tables or right_table not in selected_tables:
|
|
372
|
+
continue
|
|
373
|
+
from_ref, to_ref = _relation_from_to_refs(relation)
|
|
374
|
+
if not from_ref or not to_ref:
|
|
375
|
+
continue
|
|
376
|
+
item: dict[str, Any] = {"from": from_ref, "to": to_ref}
|
|
377
|
+
join_type = relation.get("joinType")
|
|
378
|
+
if isinstance(join_type, str) and join_type.strip():
|
|
379
|
+
item["joinType"] = join_type.strip()
|
|
380
|
+
required_filters = relation.get("requiredFilters")
|
|
381
|
+
if isinstance(required_filters, list) and required_filters:
|
|
382
|
+
item["requiredFilters"] = [str(value) for value in required_filters if str(value).strip()]
|
|
383
|
+
slim.append(item)
|
|
384
|
+
return slim
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def _slim_policy(
|
|
388
|
+
policy_items: list[dict[str, Any]],
|
|
389
|
+
selected_tables: set[str],
|
|
390
|
+
) -> list[dict[str, Any]]:
|
|
391
|
+
if not policy_items:
|
|
392
|
+
return []
|
|
393
|
+
merged: dict[str, Any] = {}
|
|
394
|
+
for item in policy_items:
|
|
395
|
+
if not isinstance(item, dict):
|
|
396
|
+
continue
|
|
397
|
+
for key, value in item.items():
|
|
398
|
+
if key in {"requiredScopes", "scopePlaceholders", "source"}:
|
|
399
|
+
continue
|
|
400
|
+
if key == "fieldBlacklist" and isinstance(value, list):
|
|
401
|
+
filtered = [
|
|
402
|
+
{
|
|
403
|
+
"table": entry.get("table"),
|
|
404
|
+
"columns": entry.get("columns"),
|
|
405
|
+
}
|
|
406
|
+
for entry in value
|
|
407
|
+
if isinstance(entry, dict)
|
|
408
|
+
and str(entry.get("table") or "") in selected_tables
|
|
409
|
+
and isinstance(entry.get("columns"), list)
|
|
410
|
+
]
|
|
411
|
+
if filtered:
|
|
412
|
+
merged["fieldBlacklist"] = filtered
|
|
413
|
+
elif key == "sqlRules" and value:
|
|
414
|
+
merged["sqlRules"] = value
|
|
415
|
+
elif key not in merged and value:
|
|
416
|
+
merged[key] = value
|
|
417
|
+
return [merged] if merged else []
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def _relation_endpoint_tables(relation: dict[str, Any]) -> tuple[str, str]:
|
|
421
|
+
left_table = str(relation.get("leftTable") or "")
|
|
422
|
+
right_table = str(relation.get("rightTable") or "")
|
|
423
|
+
if left_table and right_table:
|
|
424
|
+
return left_table, right_table
|
|
425
|
+
from_ref = str(relation.get("from") or "")
|
|
426
|
+
to_ref = str(relation.get("to") or "")
|
|
427
|
+
left = from_ref.split(".", 1)[0] if "." in from_ref else from_ref
|
|
428
|
+
right = to_ref.split(".", 1)[0] if "." in to_ref else to_ref
|
|
429
|
+
return left, right
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def _relation_from_to_refs(relation: dict[str, Any]) -> tuple[str | None, str | None]:
|
|
433
|
+
left_table = str(relation.get("leftTable") or "")
|
|
434
|
+
right_table = str(relation.get("rightTable") or "")
|
|
435
|
+
if left_table and right_table:
|
|
436
|
+
left_column = str(relation.get("leftColumn") or relation.get("fromColumn") or "")
|
|
437
|
+
right_column = str(relation.get("rightColumn") or relation.get("toColumn") or "")
|
|
438
|
+
from_ref = f"{left_table}.{left_column}".rstrip(".") if left_column else left_table
|
|
439
|
+
to_ref = f"{right_table}.{right_column}".rstrip(".") if right_column else right_table
|
|
440
|
+
return from_ref, to_ref
|
|
441
|
+
from_ref = str(relation.get("from") or "").strip()
|
|
442
|
+
to_ref = str(relation.get("to") or "").strip()
|
|
443
|
+
return (from_ref or None), (to_ref or None)
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def _sql_output_schema(default_limit: int, question: str) -> dict[str, Any]:
|
|
447
|
+
return {
|
|
448
|
+
"sql": f"SELECT column AS 中文含义 ... LIMIT {default_limit}",
|
|
449
|
+
"tables": ["table_name"],
|
|
450
|
+
"placeholders": [],
|
|
451
|
+
"usedColumns": ["table.column"],
|
|
452
|
+
"usedJoins": ["left_table.left_column = right_table.right_column"],
|
|
453
|
+
"metricRefs": ["schemaContext.metrics.name"],
|
|
454
|
+
"clarification": None,
|
|
455
|
+
"statusEnumPolicy": {
|
|
456
|
+
"explicitStatusFilter": "用户明确提出状态筛选时,把状态枚举条件写入 WHERE,并在 SELECT 中用 CASE 或枚举关联展示中文含义。",
|
|
457
|
+
"missingOrUnspecifiedStatus": "用户未提出状态筛选或 schemaContext 缺少枚举时,不要追问;首次查询保持宽泛,并把相关状态字段及中文含义加入 SELECT。",
|
|
110
458
|
},
|
|
111
459
|
}
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def _schema_read_order(*, compact: bool = False) -> list[str]:
|
|
463
|
+
if compact:
|
|
464
|
+
return ["policy", "schema", "concepts", "relations", "enums", "policy"]
|
|
465
|
+
return [
|
|
466
|
+
"agentInstructions",
|
|
467
|
+
"policy",
|
|
468
|
+
"glossary",
|
|
469
|
+
"schema",
|
|
470
|
+
"concepts/metrics/businessTerms",
|
|
471
|
+
"defaultFilters",
|
|
472
|
+
"joins",
|
|
473
|
+
"relations",
|
|
474
|
+
"exampleJoinPatterns",
|
|
475
|
+
"enums",
|
|
476
|
+
"policy",
|
|
477
|
+
]
|
|
115
478
|
|
|
116
479
|
|
|
117
480
|
def _business_examples(examples: list[dict[str, Any]]) -> list[dict[str, Any]]:
|