agent2dashboard 0.2.0__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.
- agent2dashboard/__init__.py +593 -0
- agent2dashboard/__main__.py +3 -0
- agent2dashboard/_env.py +79 -0
- agent2dashboard/a2ui/__init__.py +1 -0
- agent2dashboard/a2ui/catalogs/dashboard/v1/catalog.json +496 -0
- agent2dashboard/a2ui/checks.py +656 -0
- agent2dashboard/a2ui/express.py +349 -0
- agent2dashboard/a2ui/layout_actions.py +409 -0
- agent2dashboard/a2ui/render.py +252 -0
- agent2dashboard/a2ui/state.py +600 -0
- agent2dashboard/a2ui/surfaces.py +23 -0
- agent2dashboard/agent/__init__.py +83 -0
- agent2dashboard/agent/builtin_tools.py +258 -0
- agent2dashboard/agent/history.py +218 -0
- agent2dashboard/agent/loop.py +341 -0
- agent2dashboard/agent/prompt.py +66 -0
- agent2dashboard/agent/tools.py +162 -0
- agent2dashboard/agent/turn.py +201 -0
- agent2dashboard/auth.py +350 -0
- agent2dashboard/cli/__init__.py +50 -0
- agent2dashboard/errors.py +18 -0
- agent2dashboard/http/__init__.py +40 -0
- agent2dashboard/http/dashboards.py +100 -0
- agent2dashboard/http/functions.py +462 -0
- agent2dashboard/http/queries.py +168 -0
- agent2dashboard/http/revisions.py +126 -0
- agent2dashboard/http/router.py +353 -0
- agent2dashboard/http/schemas.py +102 -0
- agent2dashboard/llm/__init__.py +7 -0
- agent2dashboard/llm/_messages_api.py +123 -0
- agent2dashboard/llm/bedrock.py +96 -0
- agent2dashboard/llm/direct.py +40 -0
- agent2dashboard/llm/messages.py +45 -0
- agent2dashboard/migrations/__init__.py +383 -0
- agent2dashboard/migrations/versions/0001_initial.py +228 -0
- agent2dashboard/ports.py +538 -0
- agent2dashboard/py.typed +0 -0
- agent2dashboard/query/__init__.py +65 -0
- agent2dashboard/query/errors.py +39 -0
- agent2dashboard/query/executor.py +203 -0
- agent2dashboard/query/filters.py +446 -0
- agent2dashboard/query/governed.py +155 -0
- agent2dashboard/query/readonly.py +166 -0
- agent2dashboard/query/registry.py +213 -0
- agent2dashboard/query/row_filter.py +135 -0
- agent2dashboard/query/service.py +93 -0
- agent2dashboard/query/sql_guard.py +219 -0
- agent2dashboard/runs/__init__.py +87 -0
- agent2dashboard/runs/errors.py +65 -0
- agent2dashboard/runs/events.py +147 -0
- agent2dashboard/runs/hooks.py +135 -0
- agent2dashboard/runs/http.py +169 -0
- agent2dashboard/runs/memory.py +148 -0
- agent2dashboard/runs/redis_bus.py +219 -0
- agent2dashboard/runs/service.py +728 -0
- agent2dashboard/runs/writer.py +95 -0
- agent2dashboard/semantic/__init__.py +6 -0
- agent2dashboard/semantic/cube.py +39 -0
- agent2dashboard/semantic/static.py +81 -0
- agent2dashboard/storage/__init__.py +60 -0
- agent2dashboard/storage/lifecycle.py +105 -0
- agent2dashboard/storage/memory.py +488 -0
- agent2dashboard/storage/records.py +219 -0
- agent2dashboard/storage/sql.py +666 -0
- agent2dashboard/storage/tables.py +387 -0
- agent2dashboard/testing/__init__.py +20 -0
- agent2dashboard/testing/event_bus.py +10 -0
- agent2dashboard/testing/fake_llm.py +129 -0
- agent2dashboard/testing/host.py +191 -0
- agent2dashboard/tracing/__init__.py +36 -0
- agent2dashboard/tracing/db.py +143 -0
- agent2dashboard/tracing/fanout.py +153 -0
- agent2dashboard/tracing/langfuse.py +339 -0
- agent2dashboard/tracing/masking.py +26 -0
- agent2dashboard-0.2.0.dist-info/METADATA +81 -0
- agent2dashboard-0.2.0.dist-info/RECORD +79 -0
- agent2dashboard-0.2.0.dist-info/WHEEL +4 -0
- agent2dashboard-0.2.0.dist-info/entry_points.txt +3 -0
- agent2dashboard-0.2.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""The agent: tool loop, tool registry, system prompt, history replay and the run's turn
|
|
2
|
+
function (design §3.5, §5.1).
|
|
3
|
+
|
|
4
|
+
`build_turn_function` and `build_tool_registry` (`agent.turn`) are imported lazily: they
|
|
5
|
+
depend on `agent2dashboard.a2ui`, which itself imports `agent.tools`.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from agent2dashboard.agent.history import (
|
|
11
|
+
HISTORY_LIMIT,
|
|
12
|
+
StoredMessage,
|
|
13
|
+
replay_history,
|
|
14
|
+
trail_entry,
|
|
15
|
+
)
|
|
16
|
+
from agent2dashboard.agent.loop import (
|
|
17
|
+
CANCELLED,
|
|
18
|
+
INTERRUPTED,
|
|
19
|
+
MAX_TOOL_ROUNDS,
|
|
20
|
+
CancelCheck,
|
|
21
|
+
TurnEvent,
|
|
22
|
+
TurnResult,
|
|
23
|
+
TurnState,
|
|
24
|
+
run_agent_loop,
|
|
25
|
+
)
|
|
26
|
+
from agent2dashboard.agent.prompt import DEFAULT_SYSTEM_PROMPT, build_system_prompt
|
|
27
|
+
from agent2dashboard.agent.tools import (
|
|
28
|
+
DEFINE_QUERY,
|
|
29
|
+
DESCRIBE_TABLE,
|
|
30
|
+
GET_METRIC,
|
|
31
|
+
LIST_TABLES,
|
|
32
|
+
RENDER_DASHBOARD,
|
|
33
|
+
SEARCH_METRICS,
|
|
34
|
+
Tool,
|
|
35
|
+
ToolContext,
|
|
36
|
+
ToolEmit,
|
|
37
|
+
ToolError,
|
|
38
|
+
ToolHandler,
|
|
39
|
+
ToolProgress,
|
|
40
|
+
ToolRegistry,
|
|
41
|
+
ToolResult,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
__all__ = [
|
|
45
|
+
"CANCELLED",
|
|
46
|
+
"DEFAULT_SYSTEM_PROMPT",
|
|
47
|
+
"DEFINE_QUERY",
|
|
48
|
+
"DESCRIBE_TABLE",
|
|
49
|
+
"GET_METRIC",
|
|
50
|
+
"HISTORY_LIMIT",
|
|
51
|
+
"INTERRUPTED",
|
|
52
|
+
"LIST_TABLES",
|
|
53
|
+
"MAX_TOOL_ROUNDS",
|
|
54
|
+
"RENDER_DASHBOARD",
|
|
55
|
+
"SEARCH_METRICS",
|
|
56
|
+
"CancelCheck",
|
|
57
|
+
"StoredMessage",
|
|
58
|
+
"Tool",
|
|
59
|
+
"ToolContext",
|
|
60
|
+
"ToolEmit",
|
|
61
|
+
"ToolError",
|
|
62
|
+
"ToolHandler",
|
|
63
|
+
"ToolProgress",
|
|
64
|
+
"ToolRegistry",
|
|
65
|
+
"ToolResult",
|
|
66
|
+
"TurnEvent",
|
|
67
|
+
"TurnResult",
|
|
68
|
+
"TurnState",
|
|
69
|
+
"build_system_prompt",
|
|
70
|
+
"build_tool_registry",
|
|
71
|
+
"build_turn_function",
|
|
72
|
+
"replay_history",
|
|
73
|
+
"run_agent_loop",
|
|
74
|
+
"trail_entry",
|
|
75
|
+
]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def __getattr__(name: str) -> Any:
|
|
79
|
+
if name in ("build_turn_function", "build_tool_registry"):
|
|
80
|
+
from agent2dashboard.agent import turn
|
|
81
|
+
|
|
82
|
+
return getattr(turn, name)
|
|
83
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"""The SDK's own agent tools over the host's ports (design §1.10 *Agent tools*, §3.2).
|
|
2
|
+
|
|
3
|
+
- `list_tables`, `describe_table`: the governed schema, plus the `SemanticProvider`'s meaning
|
|
4
|
+
of a table when there is one (CHAT);
|
|
5
|
+
- `search_metrics`, `get_metric`: the semantic provider's metric definitions (CHAT; only
|
|
6
|
+
offered when the host configured a provider);
|
|
7
|
+
- `define_query`: guard, row filter, read-only run, registered into the run's
|
|
8
|
+
`DashboardSession` registry (QUERY).
|
|
9
|
+
|
|
10
|
+
`render_dashboard` lives with the A2UI code (`agent2dashboard.a2ui.render`). Every answer is
|
|
11
|
+
structure only: names, types, descriptions and result shapes, never row values.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
from collections.abc import Mapping
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from agent2dashboard.agent.tools import (
|
|
21
|
+
DESCRIBE_TABLE,
|
|
22
|
+
GET_METRIC,
|
|
23
|
+
LIST_TABLES,
|
|
24
|
+
SEARCH_METRICS,
|
|
25
|
+
Tool,
|
|
26
|
+
ToolContext,
|
|
27
|
+
ToolError,
|
|
28
|
+
ToolResult,
|
|
29
|
+
)
|
|
30
|
+
from agent2dashboard.errors import RowFilterDenied
|
|
31
|
+
from agent2dashboard.ports import (
|
|
32
|
+
Capability,
|
|
33
|
+
GovernedSchema,
|
|
34
|
+
GovernedTable,
|
|
35
|
+
Metric,
|
|
36
|
+
SemanticProvider,
|
|
37
|
+
ToolDef,
|
|
38
|
+
)
|
|
39
|
+
from agent2dashboard.query.errors import QueryError
|
|
40
|
+
from agent2dashboard.query.registry import DEFINE_QUERY_TOOL, define_query
|
|
41
|
+
from agent2dashboard.query.service import QueryService
|
|
42
|
+
|
|
43
|
+
__all__ = [
|
|
44
|
+
"DESCRIBE_TABLE_TOOL",
|
|
45
|
+
"GET_METRIC_TOOL",
|
|
46
|
+
"LIST_TABLES_TOOL",
|
|
47
|
+
"SEARCH_METRICS_TOOL",
|
|
48
|
+
"define_query_tool",
|
|
49
|
+
"describe_table_tool",
|
|
50
|
+
"get_metric_tool",
|
|
51
|
+
"list_tables_tool",
|
|
52
|
+
"lookup_tools",
|
|
53
|
+
"search_metrics_tool",
|
|
54
|
+
]
|
|
55
|
+
|
|
56
|
+
# `ToolContext.extras` key of the run's `DashboardSession` (same value as
|
|
57
|
+
# `agent2dashboard.a2ui.state.DASHBOARD_SESSION`; not imported, to keep `agent` free of `a2ui`).
|
|
58
|
+
_DASHBOARD_SESSION = "dashboard_session"
|
|
59
|
+
MAX_METRIC_RESULTS = 10
|
|
60
|
+
|
|
61
|
+
LIST_TABLES_TOOL = ToolDef(
|
|
62
|
+
name=LIST_TABLES,
|
|
63
|
+
description=(
|
|
64
|
+
"List the governed tables you may query, with their column names. Use describe_table "
|
|
65
|
+
"for column types, keys and what a table means."
|
|
66
|
+
),
|
|
67
|
+
input_schema={"type": "object", "properties": {}, "additionalProperties": False},
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
DESCRIBE_TABLE_TOOL = ToolDef(
|
|
71
|
+
name=DESCRIBE_TABLE,
|
|
72
|
+
description=(
|
|
73
|
+
"Describe one governed table: its columns (type, nullability, keys, allowed values), "
|
|
74
|
+
"time columns, and what the table and its columns mean."
|
|
75
|
+
),
|
|
76
|
+
input_schema={
|
|
77
|
+
"type": "object",
|
|
78
|
+
"properties": {"name": {"type": "string", "minLength": 1, "description": "Table name."}},
|
|
79
|
+
"required": ["name"],
|
|
80
|
+
"additionalProperties": False,
|
|
81
|
+
},
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
SEARCH_METRICS_TOOL = ToolDef(
|
|
85
|
+
name=SEARCH_METRICS,
|
|
86
|
+
description=(
|
|
87
|
+
"Search the business metric definitions by words from the user's question. Returns "
|
|
88
|
+
"the best matches with their description and unit; use get_metric for a metric's SQL."
|
|
89
|
+
),
|
|
90
|
+
input_schema={
|
|
91
|
+
"type": "object",
|
|
92
|
+
"properties": {
|
|
93
|
+
"text": {"type": "string", "minLength": 1},
|
|
94
|
+
"limit": {"type": "integer", "minimum": 1, "maximum": MAX_METRIC_RESULTS},
|
|
95
|
+
},
|
|
96
|
+
"required": ["text"],
|
|
97
|
+
"additionalProperties": False,
|
|
98
|
+
},
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
GET_METRIC_TOOL = ToolDef(
|
|
102
|
+
name=GET_METRIC,
|
|
103
|
+
description=(
|
|
104
|
+
"Get one metric definition by name: description, unit, SQL and instructions. Use its "
|
|
105
|
+
"SQL when it answers the question."
|
|
106
|
+
),
|
|
107
|
+
input_schema={
|
|
108
|
+
"type": "object",
|
|
109
|
+
"properties": {"name": {"type": "string", "minLength": 1}},
|
|
110
|
+
"required": ["name"],
|
|
111
|
+
"additionalProperties": False,
|
|
112
|
+
},
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _text_arg(tool_input: Mapping[str, Any], key: str) -> str:
|
|
117
|
+
value = tool_input.get(key)
|
|
118
|
+
if not isinstance(value, str) or not value.strip():
|
|
119
|
+
raise ToolError(f"`{key}` must be a non-empty string.")
|
|
120
|
+
return value.strip()
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _table_text(table: GovernedTable) -> str:
|
|
124
|
+
lines = [f"Table `{table.name}` columns:"]
|
|
125
|
+
for column in table.columns:
|
|
126
|
+
facts = [column.sql_type, "null" if column.nullable else "not null"]
|
|
127
|
+
if column.primary_key:
|
|
128
|
+
facts.append("primary key")
|
|
129
|
+
if column.unique and not column.primary_key:
|
|
130
|
+
facts.append("unique")
|
|
131
|
+
if column.foreign_key:
|
|
132
|
+
facts.append(f"references {column.foreign_key[0]}.{column.foreign_key[1]}")
|
|
133
|
+
if column.enum_values:
|
|
134
|
+
facts.append("one of " + ", ".join(column.enum_values))
|
|
135
|
+
if not column.filterable:
|
|
136
|
+
facts.append("not filterable")
|
|
137
|
+
lines.append(f"- `{column.name}`: " + ", ".join(facts))
|
|
138
|
+
if table.time_columns:
|
|
139
|
+
lines.append("Time columns: " + ", ".join(table.time_columns))
|
|
140
|
+
return "\n".join(lines)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _metric_summary(metric: Metric) -> dict[str, Any]:
|
|
144
|
+
out: dict[str, Any] = {"name": metric.name, "description": metric.description}
|
|
145
|
+
if metric.unit:
|
|
146
|
+
out["unit"] = metric.unit
|
|
147
|
+
if metric.synonyms:
|
|
148
|
+
out["synonyms"] = list(metric.synonyms)
|
|
149
|
+
return out
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def list_tables_tool(governed: GovernedSchema) -> Tool:
|
|
153
|
+
async def handler(tool_input: Mapping[str, Any], context: ToolContext) -> ToolResult:
|
|
154
|
+
tables = governed.tables()
|
|
155
|
+
if not tables:
|
|
156
|
+
return ToolResult("No governed tables are available.")
|
|
157
|
+
lines = [
|
|
158
|
+
f"- `{name}`: " + ", ".join(c.name for c in table.columns)
|
|
159
|
+
for name, table in sorted(tables.items())
|
|
160
|
+
]
|
|
161
|
+
return ToolResult("Governed tables:\n" + "\n".join(lines))
|
|
162
|
+
|
|
163
|
+
return Tool(LIST_TABLES_TOOL, handler, Capability.CHAT)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def describe_table_tool(governed: GovernedSchema, semantic: SemanticProvider | None) -> Tool:
|
|
167
|
+
"""Only governed tables are described. The provider's description is used when it has
|
|
168
|
+
one (it usually includes structure); otherwise the governed schema's columns."""
|
|
169
|
+
|
|
170
|
+
async def handler(tool_input: Mapping[str, Any], context: ToolContext) -> ToolResult:
|
|
171
|
+
name = _text_arg(tool_input, "name")
|
|
172
|
+
tables = governed.tables()
|
|
173
|
+
table = tables.get(name)
|
|
174
|
+
if table is None:
|
|
175
|
+
known = ", ".join(sorted(tables)) or "none"
|
|
176
|
+
raise ToolError(f"Unknown table `{name}`. Governed tables: {known}.")
|
|
177
|
+
described = await semantic.describe_table(name) if semantic is not None else None
|
|
178
|
+
return ToolResult(described.strip() if described else _table_text(table))
|
|
179
|
+
|
|
180
|
+
return Tool(DESCRIBE_TABLE_TOOL, handler, Capability.CHAT)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def search_metrics_tool(semantic: SemanticProvider) -> Tool:
|
|
184
|
+
async def handler(tool_input: Mapping[str, Any], context: ToolContext) -> ToolResult:
|
|
185
|
+
text = _text_arg(tool_input, "text")
|
|
186
|
+
limit = tool_input.get("limit", 5)
|
|
187
|
+
if not isinstance(limit, int) or isinstance(limit, bool):
|
|
188
|
+
limit = 5
|
|
189
|
+
limit = max(1, min(limit, MAX_METRIC_RESULTS))
|
|
190
|
+
metrics = await semantic.search_metrics(text, limit=limit)
|
|
191
|
+
if not metrics:
|
|
192
|
+
return ToolResult(f"No metric matches {json.dumps(text, ensure_ascii=False)}.")
|
|
193
|
+
return ToolResult(
|
|
194
|
+
json.dumps([_metric_summary(m) for m in metrics[:limit]], ensure_ascii=False)
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
return Tool(SEARCH_METRICS_TOOL, handler, Capability.CHAT)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def get_metric_tool(semantic: SemanticProvider) -> Tool:
|
|
201
|
+
async def handler(tool_input: Mapping[str, Any], context: ToolContext) -> ToolResult:
|
|
202
|
+
name = _text_arg(tool_input, "name")
|
|
203
|
+
metric = await semantic.get_metric(name)
|
|
204
|
+
if metric is None:
|
|
205
|
+
raise ToolError(f"Unknown metric `{name}`. Use search_metrics to find one.")
|
|
206
|
+
out = _metric_summary(metric) | {"sql": metric.sql}
|
|
207
|
+
if metric.instructions:
|
|
208
|
+
out["instructions"] = metric.instructions
|
|
209
|
+
return ToolResult(json.dumps(out, ensure_ascii=False))
|
|
210
|
+
|
|
211
|
+
return Tool(GET_METRIC_TOOL, handler, Capability.CHAT)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def lookup_tools(governed: GovernedSchema, semantic: SemanticProvider | None) -> list[Tool]:
|
|
215
|
+
"""The CHAT tools: tables always, metrics when the host has a semantic provider."""
|
|
216
|
+
tools = [list_tables_tool(governed), describe_table_tool(governed, semantic)]
|
|
217
|
+
if semantic is not None:
|
|
218
|
+
tools += [search_metrics_tool(semantic), get_metric_tool(semantic)]
|
|
219
|
+
return tools
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def define_query_tool(service: QueryService) -> Tool:
|
|
223
|
+
"""`define_query` over the run's `DashboardSession` registry
|
|
224
|
+
(`context.extras["dashboard_session"]`). Its answer to the model is the JSON of
|
|
225
|
+
`DefineQueryResult` on one line (shape only), which history and revision replay read back
|
|
226
|
+
from the tool trail."""
|
|
227
|
+
|
|
228
|
+
async def handler(tool_input: Mapping[str, Any], context: ToolContext) -> ToolResult:
|
|
229
|
+
session = context.extras.get(_DASHBOARD_SESSION)
|
|
230
|
+
registry = getattr(session, "registry", None)
|
|
231
|
+
if registry is None:
|
|
232
|
+
raise ToolError("define_query is not available outside a dashboard run.")
|
|
233
|
+
sql = _text_arg(tool_input, "sql")
|
|
234
|
+
try:
|
|
235
|
+
result = await define_query(
|
|
236
|
+
service=service,
|
|
237
|
+
registry=registry,
|
|
238
|
+
principal=context.principal,
|
|
239
|
+
query_id=tool_input.get("query_id", ""),
|
|
240
|
+
sql=sql,
|
|
241
|
+
filters=tool_input.get("filters"),
|
|
242
|
+
)
|
|
243
|
+
except (QueryError, RowFilterDenied) as exc:
|
|
244
|
+
return ToolResult(
|
|
245
|
+
str(exc) or "The query was refused.",
|
|
246
|
+
is_error=True,
|
|
247
|
+
trace_metadata={"error": type(exc).__name__},
|
|
248
|
+
)
|
|
249
|
+
return ToolResult(
|
|
250
|
+
result.model_dump_json(),
|
|
251
|
+
trace_metadata={
|
|
252
|
+
"query_id": result.query_id,
|
|
253
|
+
"row_count": result.row_count,
|
|
254
|
+
"columns": len(result.columns),
|
|
255
|
+
},
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
return Tool(DEFINE_QUERY_TOOL, handler, Capability.QUERY)
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""History replay and the tool trail (copied from XoraOps' `assistant/service.py`).
|
|
2
|
+
|
|
3
|
+
The stored turns are replayed to the model as text. Two notes are added so follow-ups work
|
|
4
|
+
without redoing everything, which bounds the extra tokens:
|
|
5
|
+
- the most recent A2UI Express the model wrote (the dashboard it can edit);
|
|
6
|
+
- if the latest assistant turn was interrupted or cancelled, the queries it had already
|
|
7
|
+
registered with `define_query`, so "continue" can pick up from them (§5.3).
|
|
8
|
+
|
|
9
|
+
Nothing here ever carries row values: the trail keeps each tool's answer to the model, which
|
|
10
|
+
is structure only.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
from collections.abc import Mapping, Sequence
|
|
17
|
+
from typing import Any, Protocol
|
|
18
|
+
|
|
19
|
+
from a2ui.constants import A2UI_INFERENCE_CLOSE_TAG, A2UI_INFERENCE_OPEN_TAG
|
|
20
|
+
|
|
21
|
+
from agent2dashboard.agent.tools import DEFINE_QUERY, RENDER_DASHBOARD, ToolProgress
|
|
22
|
+
from agent2dashboard.ports import ChatMessage
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"DASHBOARD_NOTE",
|
|
26
|
+
"HISTORY_LIMIT",
|
|
27
|
+
"INTERRUPTED_NOTE",
|
|
28
|
+
"INTERRUPTED_STOP_REASONS",
|
|
29
|
+
"NO_REPLY",
|
|
30
|
+
"StoredMessage",
|
|
31
|
+
"StoredRevision",
|
|
32
|
+
"TOOL_TRAIL_INPUT_CHARS",
|
|
33
|
+
"TOOL_TRAIL_MAX_CALLS",
|
|
34
|
+
"TOOL_TRAIL_RESULT_CHARS",
|
|
35
|
+
"public_trail_entry",
|
|
36
|
+
"replay_history",
|
|
37
|
+
"trail_entry",
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
# Most recent stored messages replayed with each turn; older ones stay stored and visible.
|
|
41
|
+
HISTORY_LIMIT = 40
|
|
42
|
+
|
|
43
|
+
# Bounds on the tool trail kept with each assistant turn.
|
|
44
|
+
TOOL_TRAIL_MAX_CALLS = 40
|
|
45
|
+
TOOL_TRAIL_INPUT_CHARS = 4000
|
|
46
|
+
TOOL_TRAIL_RESULT_CHARS = 300
|
|
47
|
+
|
|
48
|
+
# Stop reasons of a turn that ended before the model finished (§5.2, §5.3).
|
|
49
|
+
INTERRUPTED_STOP_REASONS = frozenset({"interrupted", "cancelled"})
|
|
50
|
+
|
|
51
|
+
NO_REPLY = "(no reply)"
|
|
52
|
+
DASHBOARD_NOTE = (
|
|
53
|
+
"[Context for you, not shown to the user: the A2UI Express you last rendered for this "
|
|
54
|
+
"conversation's dashboard. Start from it when asked to change or continue the dashboard.]"
|
|
55
|
+
)
|
|
56
|
+
INTERRUPTED_NOTE = (
|
|
57
|
+
"[Context for you, not shown to the user: this reply was interrupted before it finished. "
|
|
58
|
+
"Queries already registered successfully, with their result shapes:]"
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class StoredMessage(Protocol):
|
|
63
|
+
"""The fields of a stored message that replay reads (the storage task's message row)."""
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def role(self) -> str: ...
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def content(self) -> str: ...
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def stop_reason(self) -> str | None: ...
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def tool_trace(self) -> Sequence[Mapping[str, Any]] | None: ...
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def a2ui(self) -> str | None: ...
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _clip(text: str, limit: int) -> str:
|
|
82
|
+
return text if len(text) <= limit else text[: limit - 1] + "…"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _with_note(content: str, note: str) -> str:
|
|
86
|
+
return f"{content}\n\n{note}" if content else note
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def trail_entry(progress: ToolProgress) -> dict[str, Any]:
|
|
90
|
+
"""One finished tool call, compact, for the message's `tool_trace`. The Express of a
|
|
91
|
+
`render_dashboard` call is stored whole in `message.a2ui`, so only its size is kept."""
|
|
92
|
+
tool_input: Any = dict(progress.tool_input)
|
|
93
|
+
if progress.name == RENDER_DASHBOARD:
|
|
94
|
+
express = tool_input.get("a2ui")
|
|
95
|
+
tool_input = {"a2ui_chars": len(express) if isinstance(express, str) else 0}
|
|
96
|
+
encoded = json.dumps(tool_input, default=str)
|
|
97
|
+
if len(encoded) > TOOL_TRAIL_INPUT_CHARS:
|
|
98
|
+
tool_input = {"truncated": _clip(encoded, TOOL_TRAIL_INPUT_CHARS)}
|
|
99
|
+
return {
|
|
100
|
+
"name": progress.name,
|
|
101
|
+
"input": tool_input,
|
|
102
|
+
"result": _clip(progress.result or "", TOOL_TRAIL_RESULT_CHARS),
|
|
103
|
+
"is_error": progress.is_error,
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def public_trail_entry(entry: Mapping[str, Any]) -> dict[str, Any]:
|
|
108
|
+
"""What the browser may see of one stored trail entry: the tool's name, whether it failed
|
|
109
|
+
and the same `label` as its `tool.finished` event. Never its input (SQL, filters) or its
|
|
110
|
+
result (§4.1, §7); the full entry stays server-side for replay."""
|
|
111
|
+
name = str(entry.get("name") or "")
|
|
112
|
+
params: dict[str, Any] = {}
|
|
113
|
+
tool_input = entry.get("input")
|
|
114
|
+
table = tool_input.get("table") if isinstance(tool_input, Mapping) else None
|
|
115
|
+
if isinstance(table, str):
|
|
116
|
+
params["table"] = table
|
|
117
|
+
return {
|
|
118
|
+
"name": name,
|
|
119
|
+
"is_error": bool(entry.get("is_error")),
|
|
120
|
+
"label": {"code": f"tool.{name}", "params": params},
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _registered_queries(trail: Sequence[Mapping[str, Any]] | None) -> list[str]:
|
|
125
|
+
lines = []
|
|
126
|
+
for call in trail or []:
|
|
127
|
+
tool_input = call.get("input")
|
|
128
|
+
if (
|
|
129
|
+
call.get("name") != DEFINE_QUERY
|
|
130
|
+
or call.get("is_error")
|
|
131
|
+
or not isinstance(tool_input, Mapping)
|
|
132
|
+
or not tool_input.get("sql")
|
|
133
|
+
or not call.get("result")
|
|
134
|
+
):
|
|
135
|
+
continue
|
|
136
|
+
query_id = tool_input.get("query_id") or "?"
|
|
137
|
+
first_line = str(call["result"]).splitlines()[0]
|
|
138
|
+
lines.append(f"- `{query_id}`: `{tool_input['sql']}` -> {first_line}")
|
|
139
|
+
return lines
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class StoredRevision(Protocol):
|
|
143
|
+
"""The fields of a stored dashboard revision that replay reads (`RevisionRecord`)."""
|
|
144
|
+
|
|
145
|
+
@property
|
|
146
|
+
def message_id(self) -> int | None: ...
|
|
147
|
+
|
|
148
|
+
@property
|
|
149
|
+
def run_id(self) -> str | None: ...
|
|
150
|
+
|
|
151
|
+
@property
|
|
152
|
+
def express(self) -> str: ...
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _tagged(blocks: Sequence[str]) -> str:
|
|
156
|
+
return "\n".join(f"{A2UI_INFERENCE_OPEN_TAG}\n{b}\n{A2UI_INFERENCE_CLOSE_TAG}" for b in blocks)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _last_render(
|
|
160
|
+
messages: Sequence[StoredMessage],
|
|
161
|
+
assistant_turns: Sequence[StoredMessage],
|
|
162
|
+
revisions: Sequence[StoredRevision] | None,
|
|
163
|
+
) -> tuple[StoredMessage | None, str | None]:
|
|
164
|
+
"""The message the "last rendered" note goes on, and the Express it shows.
|
|
165
|
+
|
|
166
|
+
From the revision rows when given: the Express of the newest revision and of the others
|
|
167
|
+
stored with it (same message, or same run when no message records them yet), on the
|
|
168
|
+
message that records them, or on the latest assistant turn when that message is missing
|
|
169
|
+
(a reaped run). Otherwise from `message.a2ui`."""
|
|
170
|
+
if revisions is None:
|
|
171
|
+
message = next((m for m in reversed(assistant_turns) if m.a2ui), None)
|
|
172
|
+
return message, message.a2ui if message is not None else None
|
|
173
|
+
if not revisions:
|
|
174
|
+
return None, None
|
|
175
|
+
last = revisions[-1]
|
|
176
|
+
if last.message_id is not None:
|
|
177
|
+
group = [r for r in revisions if r.message_id == last.message_id]
|
|
178
|
+
elif last.run_id is not None:
|
|
179
|
+
group = [r for r in revisions if r.message_id is None and r.run_id == last.run_id]
|
|
180
|
+
else:
|
|
181
|
+
group = [last]
|
|
182
|
+
target = next((m for m in messages if getattr(m, "id", None) == last.message_id), None)
|
|
183
|
+
if target is None or last.message_id is None:
|
|
184
|
+
target = assistant_turns[-1] if assistant_turns else None
|
|
185
|
+
return target, _tagged([r.express for r in group])
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def replay_history(
|
|
189
|
+
messages: Sequence[StoredMessage],
|
|
190
|
+
*,
|
|
191
|
+
limit: int | None = HISTORY_LIMIT,
|
|
192
|
+
revisions: Sequence[StoredRevision] | None = None,
|
|
193
|
+
) -> list[ChatMessage]:
|
|
194
|
+
"""The stored turns (oldest first) as model messages, starting with a user turn.
|
|
195
|
+
|
|
196
|
+
`revisions` (the conversation's `dashboard_revision` rows, oldest first) is where the
|
|
197
|
+
"Express you last rendered" note comes from; without it, from `message.a2ui`."""
|
|
198
|
+
if limit is not None:
|
|
199
|
+
messages = messages[-limit:] if limit > 0 else []
|
|
200
|
+
assistant_turns = [m for m in messages if m.role == "assistant"]
|
|
201
|
+
last_render, last_express = _last_render(messages, assistant_turns, revisions)
|
|
202
|
+
last_assistant = assistant_turns[-1] if assistant_turns else None
|
|
203
|
+
history: list[ChatMessage] = []
|
|
204
|
+
for message in messages:
|
|
205
|
+
content = message.content or ""
|
|
206
|
+
if message is last_render and last_express:
|
|
207
|
+
content = _with_note(content, f"{DASHBOARD_NOTE}\n```\n{last_express}\n```")
|
|
208
|
+
if message is last_assistant and message.stop_reason in INTERRUPTED_STOP_REASONS:
|
|
209
|
+
registered = _registered_queries(message.tool_trace)
|
|
210
|
+
if registered:
|
|
211
|
+
content = _with_note(content, INTERRUPTED_NOTE + "\n" + "\n".join(registered))
|
|
212
|
+
if message.role == "assistant" and not content:
|
|
213
|
+
content = NO_REPLY
|
|
214
|
+
role = "assistant" if message.role == "assistant" else "user"
|
|
215
|
+
history.append(ChatMessage(role=role, content=content))
|
|
216
|
+
while history and history[0].role != "user":
|
|
217
|
+
history.pop(0)
|
|
218
|
+
return history
|