@roll-agent/octopus-agent 0.0.10 → 0.1.0
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 +19 -1
- package/SKILL.md +77 -12
- package/package.json +1 -1
- package/pyproject.toml +4 -2
- package/references/env.yaml +21 -0
- package/scripts/refresh_dictionary.py +67 -0
- package/scripts/verify_binding.py +47 -0
- package/src/octopus_skill/_version.py +1 -1
- package/src/octopus_skill/agent.py +4045 -415
- package/src/octopus_skill/config.py +55 -10
- 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 +17 -3
- package/src/octopus_skill/mcp_client.py +16 -0
- package/src/octopus_skill/octopus_run.py +370 -32
- package/src/octopus_skill/prompt_builder.py +427 -78
- package/src/octopus_skill/question_analyzer.py +388 -0
- package/src/octopus_skill/result_renderer.py +38 -14
- package/src/octopus_skill/schema_context_retriever.py +932 -159
- package/src/octopus_skill/sql_generator.py +2093 -1231
- package/src/octopus_skill/query_sql_cache.py +0 -72
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
3
|
import os
|
|
4
|
-
from dataclasses import dataclass
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
5
|
from pathlib import Path
|
|
6
6
|
|
|
7
7
|
|
|
@@ -24,13 +24,21 @@ class SchemaConfig:
|
|
|
24
24
|
refresh_interval_minutes: int
|
|
25
25
|
|
|
26
26
|
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class EntityBindingConfig:
|
|
29
|
+
# Compute bindings and log them, but do not change SQL generation yet.
|
|
30
|
+
shadow_mode: bool
|
|
31
|
+
# Entity types whose bindings are allowed to influence SQL (live rollout).
|
|
32
|
+
# In shadow_mode this is ignored.
|
|
33
|
+
enabled_entity_types: tuple[str, ...]
|
|
34
|
+
min_fuzzy_score: float
|
|
35
|
+
|
|
36
|
+
|
|
27
37
|
@dataclass(frozen=True)
|
|
28
38
|
class SqlConfig:
|
|
29
39
|
max_repair_attempts: int
|
|
30
40
|
default_limit: int
|
|
31
41
|
max_limit: int
|
|
32
|
-
query_cache_path: Path | None = None
|
|
33
|
-
query_cache_ttl_minutes: int = 30
|
|
34
42
|
|
|
35
43
|
|
|
36
44
|
@dataclass(frozen=True)
|
|
@@ -39,12 +47,19 @@ class AuditConfig:
|
|
|
39
47
|
log_path: Path
|
|
40
48
|
|
|
41
49
|
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class SamplingConfig:
|
|
52
|
+
max_tokens: int
|
|
53
|
+
|
|
54
|
+
|
|
42
55
|
@dataclass(frozen=True)
|
|
43
56
|
class AppConfig:
|
|
44
57
|
sponge_mcp: SpongeMcpConfig
|
|
45
58
|
schema: SchemaConfig
|
|
46
59
|
sql: SqlConfig
|
|
47
60
|
audit: AuditConfig
|
|
61
|
+
sampling: SamplingConfig = field(default_factory=lambda: SamplingConfig(max_tokens=4096))
|
|
62
|
+
binding: EntityBindingConfig | None = None
|
|
48
63
|
|
|
49
64
|
|
|
50
65
|
def load_config() -> AppConfig:
|
|
@@ -63,13 +78,15 @@ def load_config() -> AppConfig:
|
|
|
63
78
|
max_repair_attempts=2,
|
|
64
79
|
default_limit=50,
|
|
65
80
|
max_limit=500,
|
|
66
|
-
query_cache_path=_optional_path("OCTOPUS_QUERY_SQL_CACHE_PATH"),
|
|
67
|
-
query_cache_ttl_minutes=30,
|
|
68
81
|
),
|
|
69
82
|
audit=AuditConfig(
|
|
70
83
|
enabled=True,
|
|
71
84
|
log_path=PACKAGE_ROOT / "logs/octopus-sponge-audit.log",
|
|
72
85
|
),
|
|
86
|
+
sampling=SamplingConfig(
|
|
87
|
+
max_tokens=_env_int("OCTOPUS_SAMPLING_MAX_TOKENS", default=4096),
|
|
88
|
+
),
|
|
89
|
+
binding=None,
|
|
73
90
|
)
|
|
74
91
|
|
|
75
92
|
|
|
@@ -77,8 +94,36 @@ def load_config_from_env() -> AppConfig:
|
|
|
77
94
|
return load_config()
|
|
78
95
|
|
|
79
96
|
|
|
80
|
-
def
|
|
81
|
-
value = os.getenv(
|
|
82
|
-
if value is None or
|
|
83
|
-
return
|
|
84
|
-
return
|
|
97
|
+
def _env_bool(name: str, *, default: bool) -> bool:
|
|
98
|
+
value = os.getenv(name)
|
|
99
|
+
if value is None or value == "":
|
|
100
|
+
return default
|
|
101
|
+
return value.strip().lower() in {"1", "true", "yes", "on"}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _env_csv(name: str, *, default: tuple[str, ...] = ()) -> tuple[str, ...]:
|
|
105
|
+
value = os.getenv(name)
|
|
106
|
+
if value is None:
|
|
107
|
+
return default
|
|
108
|
+
return tuple(item.strip() for item in value.split(",") if item.strip())
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _env_float(name: str, *, default: float) -> float:
|
|
112
|
+
value = os.getenv(name)
|
|
113
|
+
if value is None or value == "":
|
|
114
|
+
return default
|
|
115
|
+
try:
|
|
116
|
+
return float(value)
|
|
117
|
+
except ValueError:
|
|
118
|
+
return default
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _env_int(name: str, *, default: int) -> int:
|
|
122
|
+
value = os.getenv(name)
|
|
123
|
+
if value is None or value == "":
|
|
124
|
+
return default
|
|
125
|
+
try:
|
|
126
|
+
parsed = int(value)
|
|
127
|
+
except ValueError:
|
|
128
|
+
return default
|
|
129
|
+
return parsed if parsed > 0 else default
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import csv
|
|
4
|
+
import os
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
from uuid import uuid4
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
DEFAULT_EXPORT_DIR = Path("/tmp/octopus-agent-exports")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class CsvExport:
|
|
17
|
+
path: Path
|
|
18
|
+
row_count: int
|
|
19
|
+
column_count: int
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def export_result_to_csv(result: dict[str, Any], *, prefix: str = "octopus_export") -> CsvExport | None:
|
|
23
|
+
rows = result.get("rows")
|
|
24
|
+
if not isinstance(rows, list) or not rows:
|
|
25
|
+
return None
|
|
26
|
+
columns = _column_names(result.get("columns"), rows)
|
|
27
|
+
if not columns:
|
|
28
|
+
return None
|
|
29
|
+
export_dir = Path(os.getenv("OCTOPUS_EXPORT_DIR") or DEFAULT_EXPORT_DIR)
|
|
30
|
+
export_dir.mkdir(parents=True, exist_ok=True)
|
|
31
|
+
path = export_dir / _csv_filename(prefix)
|
|
32
|
+
with path.open("w", newline="", encoding="utf-8-sig") as handle:
|
|
33
|
+
writer = csv.writer(handle)
|
|
34
|
+
writer.writerow(columns)
|
|
35
|
+
for row in rows:
|
|
36
|
+
writer.writerow([_cell_value(row, column) for column in columns])
|
|
37
|
+
return CsvExport(path=path, row_count=len(rows), column_count=len(columns))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _csv_filename(prefix: str) -> str:
|
|
41
|
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
42
|
+
suffix = uuid4().hex[:8]
|
|
43
|
+
safe_prefix = "".join(char if char.isalnum() or char in {"_", "-"} else "_" for char in prefix).strip("_")
|
|
44
|
+
return f"{safe_prefix or 'octopus_export'}_{timestamp}_{suffix}.csv"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _column_names(columns: Any, rows: list[Any]) -> list[str]:
|
|
48
|
+
names: list[str] = []
|
|
49
|
+
if isinstance(columns, list):
|
|
50
|
+
for column in columns:
|
|
51
|
+
if isinstance(column, dict) and column.get("name"):
|
|
52
|
+
names.append(str(column["name"]))
|
|
53
|
+
elif isinstance(column, str):
|
|
54
|
+
names.append(column)
|
|
55
|
+
if not names and rows and isinstance(rows[0], dict):
|
|
56
|
+
names = [str(key) for key in rows[0].keys()]
|
|
57
|
+
return names
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _cell_value(row: Any, column: str) -> str:
|
|
61
|
+
if not isinstance(row, dict):
|
|
62
|
+
return str(row)
|
|
63
|
+
value = row.get(column, "")
|
|
64
|
+
if value is None:
|
|
65
|
+
return ""
|
|
66
|
+
return str(value)
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from .llm_sql_generator import Sampler
|
|
7
|
+
from .prompt_builder import filter_agent_instructions_by_stage, format_numbered_instruction_lines
|
|
8
|
+
from .result_renderer import RESULT_ROW_DISPLAY_LIMIT, normalize_result_format, render_result
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
RESULT_RENDER_SYSTEM_PROMPT = """你是丸子Agent(Octopus Agent)的查询结果渲染专家。
|
|
12
|
+
业务规则的唯一来源是 payload 中的 mandatoryAgentInstructions;必须逐条遵守,不得使用训练记忆中的业务口径替代 schema 要求。
|
|
13
|
+
根据用户问题、outputFormat 和 result 数据,输出最终用户可见答复。
|
|
14
|
+
直接输出渲染后的文本,不要 JSON 包装,不要解释渲染过程。"""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def render_result_with_llm(
|
|
18
|
+
*,
|
|
19
|
+
question: str,
|
|
20
|
+
result: dict[str, Any],
|
|
21
|
+
agent_instructions: list[dict[str, Any]],
|
|
22
|
+
sampler: Sampler,
|
|
23
|
+
result_format: str | None = None,
|
|
24
|
+
) -> str:
|
|
25
|
+
output_format = normalize_result_format(question, result_format)
|
|
26
|
+
if not result.get("success", True):
|
|
27
|
+
return render_result(question, result, result_format)
|
|
28
|
+
|
|
29
|
+
if _should_render_detail_rows_locally(result):
|
|
30
|
+
local_format = "markdown" if output_format == "text" else output_format
|
|
31
|
+
return render_result(question, result, local_format)
|
|
32
|
+
|
|
33
|
+
instruction_lines = format_numbered_instruction_lines(
|
|
34
|
+
filter_agent_instructions_by_stage(agent_instructions, "after")
|
|
35
|
+
)
|
|
36
|
+
row_count = int(result.get("rowCount", len(result.get("rows", []))))
|
|
37
|
+
rows = result.get("rows", [])
|
|
38
|
+
sample = rows[:RESULT_ROW_DISPLAY_LIMIT] if isinstance(rows, list) else []
|
|
39
|
+
payload = {
|
|
40
|
+
"mandatoryAgentInstructions": instruction_lines,
|
|
41
|
+
"instruction": "按 mandatoryAgentInstructions 渲染 result,并匹配 outputFormat。",
|
|
42
|
+
"question": question,
|
|
43
|
+
"outputFormat": output_format,
|
|
44
|
+
"result": {
|
|
45
|
+
"rowCount": row_count,
|
|
46
|
+
"limited": bool(result.get("limited", False)),
|
|
47
|
+
"columns": result.get("columns", []),
|
|
48
|
+
"rows": sample,
|
|
49
|
+
},
|
|
50
|
+
}
|
|
51
|
+
try:
|
|
52
|
+
rendered = sampler(RESULT_RENDER_SYSTEM_PROMPT, json.dumps(payload, ensure_ascii=False)).strip()
|
|
53
|
+
except Exception:
|
|
54
|
+
return render_result(question, result, result_format)
|
|
55
|
+
if not rendered:
|
|
56
|
+
return render_result(question, result, result_format)
|
|
57
|
+
return rendered
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _should_render_detail_rows_locally(result: dict[str, Any]) -> bool:
|
|
61
|
+
try:
|
|
62
|
+
row_count = int(result.get("rowCount", len(result.get("rows", []))))
|
|
63
|
+
except (TypeError, ValueError):
|
|
64
|
+
row_count = 0
|
|
65
|
+
rows = result.get("rows", [])
|
|
66
|
+
if row_count <= 0 or not isinstance(rows, list) or not rows:
|
|
67
|
+
return False
|
|
68
|
+
return True
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _result_column_names(columns: Any, rows: list[Any]) -> list[str]:
|
|
72
|
+
names: list[str] = []
|
|
73
|
+
if isinstance(columns, list):
|
|
74
|
+
for column in columns:
|
|
75
|
+
if isinstance(column, dict) and column.get("name"):
|
|
76
|
+
names.append(str(column["name"]))
|
|
77
|
+
elif isinstance(column, str):
|
|
78
|
+
names.append(column)
|
|
79
|
+
if not names and rows and isinstance(rows[0], dict):
|
|
80
|
+
names = [str(key) for key in rows[0].keys()]
|
|
81
|
+
return names
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _is_aggregate_column_name(column: str) -> bool:
|
|
85
|
+
lowered = column.lower()
|
|
86
|
+
aggregate_terms = (
|
|
87
|
+
"count",
|
|
88
|
+
"sum",
|
|
89
|
+
"avg",
|
|
90
|
+
"min",
|
|
91
|
+
"max",
|
|
92
|
+
"数量",
|
|
93
|
+
"总数",
|
|
94
|
+
"人数",
|
|
95
|
+
"次数",
|
|
96
|
+
"平均",
|
|
97
|
+
"最大",
|
|
98
|
+
"最小",
|
|
99
|
+
"合计",
|
|
100
|
+
)
|
|
101
|
+
return any(term in lowered or term in column for term in aggregate_terms)
|
|
@@ -7,7 +7,7 @@ from typing import Any, Callable
|
|
|
7
7
|
|
|
8
8
|
from .prompt_builder import NL2SQL_SYSTEM_PROMPT, build_nl2sql_prompt, build_sql_repair_prompt
|
|
9
9
|
from .schema_context_retriever import SchemaContext
|
|
10
|
-
from .sql_generator import GeneratedSql, SqlGenerationError
|
|
10
|
+
from .sql_generator import GeneratedSql, SqlGenerationError, contains_forbidden_dml_keyword
|
|
11
11
|
|
|
12
12
|
|
|
13
13
|
Sampler = Callable[[str, str], str]
|
|
@@ -18,6 +18,7 @@ class SamplingSqlGenerator:
|
|
|
18
18
|
sampler: Sampler
|
|
19
19
|
default_limit: int
|
|
20
20
|
max_limit: int
|
|
21
|
+
confirmed_query_plan: dict[str, Any] | None = None
|
|
21
22
|
|
|
22
23
|
def generate(
|
|
23
24
|
self,
|
|
@@ -30,6 +31,7 @@ class SamplingSqlGenerator:
|
|
|
30
31
|
schema_context=schema_context,
|
|
31
32
|
default_limit=self.default_limit,
|
|
32
33
|
max_limit=self.max_limit,
|
|
34
|
+
confirmed_query_plan=self.confirmed_query_plan,
|
|
33
35
|
)
|
|
34
36
|
return _parse_generated_sql(self.sampler(NL2SQL_SYSTEM_PROMPT, prompt))
|
|
35
37
|
|
|
@@ -48,6 +50,7 @@ class SamplingSqlGenerator:
|
|
|
48
50
|
schema_context=schema_context,
|
|
49
51
|
default_limit=self.default_limit,
|
|
50
52
|
max_limit=self.max_limit,
|
|
53
|
+
confirmed_query_plan=self.confirmed_query_plan,
|
|
51
54
|
)
|
|
52
55
|
return _parse_generated_sql(self.sampler(NL2SQL_SYSTEM_PROMPT, prompt))
|
|
53
56
|
|
|
@@ -63,7 +66,16 @@ def _parse_generated_sql(text: str) -> GeneratedSql:
|
|
|
63
66
|
return GeneratedSql(sql=sql, tables=[], placeholders=[])
|
|
64
67
|
sql = payload.get("sql")
|
|
65
68
|
if isinstance(sql, str) and not sql.strip():
|
|
66
|
-
|
|
69
|
+
clarification = payload.get("clarification") if isinstance(payload.get("clarification"), dict) else None
|
|
70
|
+
return GeneratedSql(
|
|
71
|
+
sql="",
|
|
72
|
+
tables=[],
|
|
73
|
+
placeholders=[],
|
|
74
|
+
used_columns=[],
|
|
75
|
+
used_joins=[],
|
|
76
|
+
metric_refs=[],
|
|
77
|
+
clarification=clarification,
|
|
78
|
+
)
|
|
67
79
|
if not isinstance(sql, str):
|
|
68
80
|
fallback_sql = _extract_sql_text(text)
|
|
69
81
|
if fallback_sql is None:
|
|
@@ -77,6 +89,7 @@ def _parse_generated_sql(text: str) -> GeneratedSql:
|
|
|
77
89
|
used_columns = payload.get("usedColumns") if isinstance(payload.get("usedColumns"), list) else []
|
|
78
90
|
used_joins = payload.get("usedJoins") if isinstance(payload.get("usedJoins"), list) else []
|
|
79
91
|
metric_refs = payload.get("metricRefs") if isinstance(payload.get("metricRefs"), list) else []
|
|
92
|
+
clarification = payload.get("clarification") if isinstance(payload.get("clarification"), dict) else None
|
|
80
93
|
return GeneratedSql(
|
|
81
94
|
sql=sql,
|
|
82
95
|
tables=[str(table) for table in tables],
|
|
@@ -84,6 +97,7 @@ def _parse_generated_sql(text: str) -> GeneratedSql:
|
|
|
84
97
|
used_columns=[str(column) for column in used_columns],
|
|
85
98
|
used_joins=[str(join) for join in used_joins],
|
|
86
99
|
metric_refs=[str(metric) for metric in metric_refs],
|
|
100
|
+
clarification=clarification,
|
|
87
101
|
)
|
|
88
102
|
|
|
89
103
|
|
|
@@ -125,5 +139,5 @@ def _require_select_sql(sql: str) -> None:
|
|
|
125
139
|
normalized = sql.strip().lower()
|
|
126
140
|
if not normalized.startswith("select "):
|
|
127
141
|
raise SqlGenerationError("LLM SQL must be SELECT only")
|
|
128
|
-
if
|
|
142
|
+
if contains_forbidden_dml_keyword(sql):
|
|
129
143
|
raise SqlGenerationError("LLM SQL contains a forbidden keyword")
|
|
@@ -31,6 +31,22 @@ class SpongeMcpClient:
|
|
|
31
31
|
}
|
|
32
32
|
return self._post("get_schema", payload)
|
|
33
33
|
|
|
34
|
+
def search_entities(
|
|
35
|
+
self,
|
|
36
|
+
*,
|
|
37
|
+
trace_id: str,
|
|
38
|
+
session_id: str | None = None,
|
|
39
|
+
entity_types: list[str] | tuple[str, ...] | None = None,
|
|
40
|
+
name: str | None = None,
|
|
41
|
+
) -> dict[str, Any]:
|
|
42
|
+
payload = {
|
|
43
|
+
"traceId": trace_id,
|
|
44
|
+
"sessionId": session_id,
|
|
45
|
+
"entityTypes": list(entity_types) if entity_types else None,
|
|
46
|
+
"name": name,
|
|
47
|
+
}
|
|
48
|
+
return self._post("search_entities", payload)
|
|
49
|
+
|
|
34
50
|
def validate_sql(
|
|
35
51
|
self,
|
|
36
52
|
*,
|