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,593 @@
|
|
|
1
|
+
"""Agent-built, governed dashboards rendered with A2UI inside a conversation.
|
|
2
|
+
|
|
3
|
+
A host builds one `AgentDashboard` at startup and mounts it (design §2.2). Everything not
|
|
4
|
+
passed in comes from environment variables (`AgentDashboard.from_env`):
|
|
5
|
+
|
|
6
|
+
dashboard = AgentDashboard.from_env(
|
|
7
|
+
app_name="cs-ops",
|
|
8
|
+
governed=GovernedSchema.from_models([Ticket, Team]),
|
|
9
|
+
auth=OIDCAuth.from_env(), # or an async function (request) -> Principal
|
|
10
|
+
)
|
|
11
|
+
dashboard.mount(app, prefix="/api/agent2dashboard") # only when AGENT2DASHBOARD_ENABLED
|
|
12
|
+
|
|
13
|
+
`mount` migrates the SDK's tables on startup and closes everything on shutdown. Advanced
|
|
14
|
+
hosts pass every port to the constructor (`AgentDashboard(config=..., data=..., auth=...,
|
|
15
|
+
llm=..., ...)`) and include `dashboard.router()` themselves.
|
|
16
|
+
|
|
17
|
+
Runs then execute real agent turns (`agent2dashboard.agent.build_turn_function`): the model,
|
|
18
|
+
the SDK's tools, the conversation's dashboard, and an `llm_call` row per model round.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import asyncio
|
|
24
|
+
import re
|
|
25
|
+
from collections.abc import AsyncIterator, Callable, Mapping, Sequence
|
|
26
|
+
from contextlib import asynccontextmanager
|
|
27
|
+
from dataclasses import dataclass, field, fields
|
|
28
|
+
from typing import TYPE_CHECKING, Any
|
|
29
|
+
|
|
30
|
+
from agent2dashboard.ports import (
|
|
31
|
+
AuthProvider,
|
|
32
|
+
CatalogConfig,
|
|
33
|
+
DataSource,
|
|
34
|
+
LLMProvider,
|
|
35
|
+
RowFilter,
|
|
36
|
+
SemanticProvider,
|
|
37
|
+
Storage,
|
|
38
|
+
TraceSink,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
if TYPE_CHECKING:
|
|
42
|
+
from agent2dashboard.query import GovernedSchema
|
|
43
|
+
|
|
44
|
+
__all__ = ["DEFAULT_PREFIX", "AgentDashboard", "Limits", "SDKConfig"]
|
|
45
|
+
|
|
46
|
+
DEFAULT_PREFIX = "/api/agent2dashboard"
|
|
47
|
+
|
|
48
|
+
_REDACTED = "***"
|
|
49
|
+
# Field names that hold secrets; their values never appear in a repr.
|
|
50
|
+
_SECRET_NAME = re.compile(r"secret|password|passwd|token|api_?key|credential|dsn|_url$", re.I)
|
|
51
|
+
# Credentials embedded in a URL: scheme://user:password@host
|
|
52
|
+
_URL_USERINFO = re.compile(r"(?P<scheme>[a-z][a-z0-9+.-]*://)[^/@\s]*@", re.I)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _redact(name: str, value: Any) -> str:
|
|
56
|
+
if value is not None and _SECRET_NAME.search(name):
|
|
57
|
+
return _REDACTED
|
|
58
|
+
text = repr(value)
|
|
59
|
+
return _URL_USERINFO.sub(rf"\g<scheme>{_REDACTED}@", text)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True)
|
|
63
|
+
class Limits:
|
|
64
|
+
"""Abuse limits (design §7, §5.3)."""
|
|
65
|
+
|
|
66
|
+
max_concurrent_runs_per_principal: int = 2
|
|
67
|
+
max_message_chars: int = 8000
|
|
68
|
+
max_tool_rounds: int = 15
|
|
69
|
+
max_rows_per_widget: int = 500
|
|
70
|
+
render_concurrency: int = 4
|
|
71
|
+
event_stream_maxlen: int = 5000 # XADD MAXLEN ~
|
|
72
|
+
event_stream_ttl_seconds: int = 3600 # live events kept after the terminal event
|
|
73
|
+
# Surface functions (runQuery / filterOptions): calls per principal and surface per minute,
|
|
74
|
+
# and how long a result is reused for the same caller, query and filter values (0 = off).
|
|
75
|
+
function_calls_per_minute: int = 240
|
|
76
|
+
function_cache_seconds: float = 30.0
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass(frozen=True, repr=False)
|
|
80
|
+
class SDKConfig:
|
|
81
|
+
app_name: str
|
|
82
|
+
# Table names are `<table_prefix><table>` in `schema`. The default schema keeps the SDK's
|
|
83
|
+
# tables out of the host's own (and its autogenerate); `migrate()` creates it.
|
|
84
|
+
table_prefix: str = ""
|
|
85
|
+
schema: str | None = "agent2dashboard"
|
|
86
|
+
default_locale: str = "en"
|
|
87
|
+
# The host's environment name; queries may use the app connection only in "local" (§7).
|
|
88
|
+
environment: str = "production"
|
|
89
|
+
# Refuse the in-memory event bus when more than one API instance serves the SDK.
|
|
90
|
+
multi_instance: bool = False
|
|
91
|
+
# Local dev only: let queries run on the app connection when no read-only role is set.
|
|
92
|
+
allow_app_connection_for_queries: bool = False
|
|
93
|
+
# None keeps conversations forever (§10 #8).
|
|
94
|
+
retention_days: int | None = None
|
|
95
|
+
limits: Limits = field(default_factory=Limits)
|
|
96
|
+
|
|
97
|
+
def __repr__(self) -> str:
|
|
98
|
+
parts = ", ".join(
|
|
99
|
+
f"{f.name}={_redact(f.name, getattr(self, f.name))}" for f in fields(self)
|
|
100
|
+
)
|
|
101
|
+
return f"{type(self).__name__}({parts})"
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class AgentDashboard:
|
|
105
|
+
"""The host-facing facade: holds the config and the host's port implementations."""
|
|
106
|
+
|
|
107
|
+
def __init__(
|
|
108
|
+
self,
|
|
109
|
+
*,
|
|
110
|
+
config: SDKConfig,
|
|
111
|
+
data: DataSource,
|
|
112
|
+
auth: AuthProvider | Callable[[Any], Any],
|
|
113
|
+
llm: LLMProvider,
|
|
114
|
+
semantic: SemanticProvider | None = None,
|
|
115
|
+
row_filter: RowFilter | None = None,
|
|
116
|
+
traces: Sequence[TraceSink] = (),
|
|
117
|
+
storage: Storage | None = None,
|
|
118
|
+
storage_session: Callable[[], Any] | None = None,
|
|
119
|
+
events: Any | None = None,
|
|
120
|
+
catalog: CatalogConfig | None = None,
|
|
121
|
+
system_prompt_addendum: str | None = None,
|
|
122
|
+
locale_addenda: Mapping[str, str] | None = None,
|
|
123
|
+
record_llm_calls: bool = True,
|
|
124
|
+
turn_function: Callable[[Any], Any] | None = None,
|
|
125
|
+
) -> None:
|
|
126
|
+
"""`system_prompt_addendum` follows the SDK's system prompt, and `locale_addenda`
|
|
127
|
+
adds text for the principal's locale (§3.9). With `record_llm_calls`, a `DbTraceSink`
|
|
128
|
+
over `storage.llm_calls` is added unless `traces` already has one (§3.6, §9 item 9).
|
|
129
|
+
`turn_function` replaces the SDK's agent turn (tests, custom agents). `auth` is an
|
|
130
|
+
`AuthProvider`, or an async function `(request) -> Principal` (wrapped in
|
|
131
|
+
`agent2dashboard.auth.FunctionAuth`)."""
|
|
132
|
+
from agent2dashboard.auth import as_auth_provider
|
|
133
|
+
|
|
134
|
+
self.config = config
|
|
135
|
+
self.data = data
|
|
136
|
+
self.auth = as_auth_provider(auth)
|
|
137
|
+
self.llm = llm
|
|
138
|
+
self.semantic = semantic
|
|
139
|
+
self.row_filter = row_filter
|
|
140
|
+
self.traces = tuple(traces)
|
|
141
|
+
self.storage = storage
|
|
142
|
+
self.storage_session = storage_session
|
|
143
|
+
self.events = events
|
|
144
|
+
self.catalog = catalog
|
|
145
|
+
self.system_prompt_addendum = system_prompt_addendum
|
|
146
|
+
self.locale_addenda = dict(locale_addenda or {})
|
|
147
|
+
self.record_llm_calls = record_llm_calls
|
|
148
|
+
# Resolved by `agent2dashboard.runs` when a run starts: this, or the SDK's agent turn.
|
|
149
|
+
self.turn_function = turn_function
|
|
150
|
+
self._processor: Any = None
|
|
151
|
+
self._query_service: Any = None
|
|
152
|
+
self._trace_sinks: tuple[TraceSink, ...] | None = None
|
|
153
|
+
|
|
154
|
+
self.readonly_check: Any = None
|
|
155
|
+
self._started = False
|
|
156
|
+
self._start_lock: asyncio.Lock | None = None
|
|
157
|
+
self._closed = False
|
|
158
|
+
# Engines `from_env` created, disposed by `aclose()`.
|
|
159
|
+
self._owned_engines: list[Any] = []
|
|
160
|
+
# Missing settings `from_env` tolerated because the SDK is switched off.
|
|
161
|
+
self.config_problems: tuple[str, ...] = ()
|
|
162
|
+
self._env: Any = None
|
|
163
|
+
|
|
164
|
+
# --- building from the environment ---------------------------------------------------------
|
|
165
|
+
|
|
166
|
+
_CONSTRUCTOR_OPTIONS = frozenset(
|
|
167
|
+
{
|
|
168
|
+
"config",
|
|
169
|
+
"data",
|
|
170
|
+
"llm",
|
|
171
|
+
"semantic",
|
|
172
|
+
"row_filter",
|
|
173
|
+
"traces",
|
|
174
|
+
"storage",
|
|
175
|
+
"storage_session",
|
|
176
|
+
"events",
|
|
177
|
+
"catalog",
|
|
178
|
+
"system_prompt_addendum",
|
|
179
|
+
"locale_addenda",
|
|
180
|
+
"record_llm_calls",
|
|
181
|
+
"turn_function",
|
|
182
|
+
}
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
@classmethod
|
|
186
|
+
def from_env(
|
|
187
|
+
cls,
|
|
188
|
+
*,
|
|
189
|
+
app_name: str,
|
|
190
|
+
governed: GovernedSchema,
|
|
191
|
+
auth: AuthProvider | Callable[[Any], Any],
|
|
192
|
+
env_prefix: str = "AGENT2DASHBOARD_",
|
|
193
|
+
environ: Mapping[str, str] | None = None,
|
|
194
|
+
**overrides: Any,
|
|
195
|
+
) -> AgentDashboard:
|
|
196
|
+
"""Build the dashboard from environment variables (`environ`, default `os.environ`).
|
|
197
|
+
|
|
198
|
+
Any keyword of the constructor (`llm=`, `data=`, `events=`, `traces=`, `semantic=`,
|
|
199
|
+
`row_filter=`, `storage_session=`, `config=`, ...) or field of `SDKConfig`
|
|
200
|
+
(`table_prefix=`, `environment=`, `limits=`, `retention_days=`, ...) wins over the
|
|
201
|
+
variables. Nothing connects here: engines, Redis and the model client are created
|
|
202
|
+
lazily. A missing required setting raises `ConfigurationError` naming the variable,
|
|
203
|
+
unless `<prefix>ENABLED` is off; then the dashboard is built without it and `mount`
|
|
204
|
+
mounts nothing. The variables are listed in `docs/integrating.md`."""
|
|
205
|
+
from agent2dashboard._env import Env, async_database_url
|
|
206
|
+
from agent2dashboard.errors import ConfigurationError
|
|
207
|
+
|
|
208
|
+
config_fields = {f.name for f in fields(SDKConfig)} - {"app_name"}
|
|
209
|
+
unknown = set(overrides) - cls._CONSTRUCTOR_OPTIONS - config_fields
|
|
210
|
+
if unknown:
|
|
211
|
+
raise TypeError(f"from_env() got unexpected keyword arguments: {sorted(unknown)}")
|
|
212
|
+
config_overrides = {k: overrides.pop(k) for k in list(overrides) if k in config_fields}
|
|
213
|
+
if "config" in overrides and config_overrides:
|
|
214
|
+
raise TypeError("pass either config= or SDKConfig fields, not both")
|
|
215
|
+
|
|
216
|
+
env = Env(environ, env_prefix)
|
|
217
|
+
enabled = env.enabled()
|
|
218
|
+
problems: list[str] = []
|
|
219
|
+
options: dict[str, Any] = dict(overrides)
|
|
220
|
+
|
|
221
|
+
config: SDKConfig = options.get("config") or SDKConfig(
|
|
222
|
+
app_name=app_name,
|
|
223
|
+
**{
|
|
224
|
+
"schema": env.get("SCHEMA") or "agent2dashboard",
|
|
225
|
+
"table_prefix": env.get("TABLE_PREFIX") or "",
|
|
226
|
+
"default_locale": env.get("DEFAULT_LOCALE") or "en",
|
|
227
|
+
"environment": env.get("ENVIRONMENT", "ENVIRONMENT") or "production",
|
|
228
|
+
"multi_instance": env.flag("MULTI_INSTANCE"),
|
|
229
|
+
**config_overrides,
|
|
230
|
+
},
|
|
231
|
+
)
|
|
232
|
+
options["config"] = config
|
|
233
|
+
|
|
234
|
+
# Storage: the app connection (the SDK's own tables).
|
|
235
|
+
storage_url: str | None = None
|
|
236
|
+
raw = env.get("DATABASE_URL", "DATABASE_URL")
|
|
237
|
+
if raw is not None:
|
|
238
|
+
storage_url = async_database_url(raw, name=f"{env.name('DATABASE_URL')}/DATABASE_URL")
|
|
239
|
+
engine = None
|
|
240
|
+
if "storage" not in options and "storage_session" not in options:
|
|
241
|
+
if storage_url is None:
|
|
242
|
+
problems.append(f"{env.name('DATABASE_URL')} (or DATABASE_URL) is not set")
|
|
243
|
+
else:
|
|
244
|
+
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
|
245
|
+
|
|
246
|
+
engine = create_async_engine(storage_url, pool_pre_ping=True)
|
|
247
|
+
options["storage_session"] = async_sessionmaker(engine, expire_on_commit=False)
|
|
248
|
+
|
|
249
|
+
# Queries: the read-only role, else the app connection (accepted only in local).
|
|
250
|
+
if "data" not in options:
|
|
251
|
+
readonly = env.get("READONLY_DATABASE_URL")
|
|
252
|
+
if readonly is not None:
|
|
253
|
+
readonly = async_database_url(readonly, name=env.name("READONLY_DATABASE_URL"))
|
|
254
|
+
if readonly is None and storage_url is None:
|
|
255
|
+
problems.append(
|
|
256
|
+
f"{env.name('READONLY_DATABASE_URL')} (or {env.name('DATABASE_URL')} "
|
|
257
|
+
"in local development) is not set"
|
|
258
|
+
)
|
|
259
|
+
else:
|
|
260
|
+
from agent2dashboard.query import SqlAlchemyDataSource
|
|
261
|
+
|
|
262
|
+
options["data"] = SqlAlchemyDataSource(readonly, governed, app_url=storage_url)
|
|
263
|
+
|
|
264
|
+
# Events: Redis Streams, else in memory (one instance only).
|
|
265
|
+
if "events" not in options:
|
|
266
|
+
redis_url = env.get("REDIS_URL", "REDIS_URL")
|
|
267
|
+
limits = config.limits
|
|
268
|
+
if redis_url is not None:
|
|
269
|
+
from agent2dashboard.runs import RedisEventBus
|
|
270
|
+
|
|
271
|
+
options["events"] = RedisEventBus(
|
|
272
|
+
url=redis_url,
|
|
273
|
+
maxlen=limits.event_stream_maxlen,
|
|
274
|
+
retention_s=limits.event_stream_ttl_seconds,
|
|
275
|
+
)
|
|
276
|
+
elif config.multi_instance:
|
|
277
|
+
problems.append(
|
|
278
|
+
f"{env.name('MULTI_INSTANCE')} is on but {env.name('REDIS_URL')} "
|
|
279
|
+
"(or REDIS_URL) is not set"
|
|
280
|
+
)
|
|
281
|
+
else:
|
|
282
|
+
from agent2dashboard.runs import InMemoryEventBus
|
|
283
|
+
|
|
284
|
+
options["events"] = InMemoryEventBus(
|
|
285
|
+
maxlen=limits.event_stream_maxlen,
|
|
286
|
+
retention_s=limits.event_stream_ttl_seconds,
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
# Model: Bedrock, credentials from the default AWS chain on first use.
|
|
290
|
+
if "llm" not in options:
|
|
291
|
+
from agent2dashboard.llm import BedrockProvider
|
|
292
|
+
|
|
293
|
+
try:
|
|
294
|
+
options["llm"] = BedrockProvider.from_env(environ, env_prefix=env_prefix)
|
|
295
|
+
except ConfigurationError as exc:
|
|
296
|
+
problems.append(str(exc))
|
|
297
|
+
|
|
298
|
+
if "traces" not in options:
|
|
299
|
+
options["traces"] = _langfuse_from_env(env, config.environment)
|
|
300
|
+
|
|
301
|
+
if "semantic" not in options:
|
|
302
|
+
path = env.get("SEMANTIC_CONTEXT")
|
|
303
|
+
if path is not None:
|
|
304
|
+
from agent2dashboard.semantic.static import StaticSemanticProvider
|
|
305
|
+
|
|
306
|
+
try:
|
|
307
|
+
options["semantic"] = StaticSemanticProvider(path, governed=governed)
|
|
308
|
+
except OSError:
|
|
309
|
+
problems.append(f"{env.name('SEMANTIC_CONTEXT')}: cannot read {path!r}")
|
|
310
|
+
|
|
311
|
+
if "system_prompt_addendum" not in options:
|
|
312
|
+
options["system_prompt_addendum"] = env.get("SYSTEM_PROMPT_ADDENDUM")
|
|
313
|
+
|
|
314
|
+
problems.extend(getattr(auth, "config_problems", ()) or ())
|
|
315
|
+
if problems and enabled:
|
|
316
|
+
raise ConfigurationError("agent2dashboard is not configured: " + "; ".join(problems))
|
|
317
|
+
|
|
318
|
+
dashboard = cls(
|
|
319
|
+
auth=auth,
|
|
320
|
+
data=options.pop("data", None), # type: ignore[arg-type]
|
|
321
|
+
llm=options.pop("llm", None), # type: ignore[arg-type]
|
|
322
|
+
**options,
|
|
323
|
+
)
|
|
324
|
+
if engine is not None:
|
|
325
|
+
dashboard._owned_engines.append(engine)
|
|
326
|
+
dashboard.config_problems = tuple(problems)
|
|
327
|
+
dashboard._env = env
|
|
328
|
+
return dashboard
|
|
329
|
+
|
|
330
|
+
def _check_configured(self) -> None:
|
|
331
|
+
if self.config_problems:
|
|
332
|
+
from agent2dashboard.errors import ConfigurationError
|
|
333
|
+
|
|
334
|
+
raise ConfigurationError(
|
|
335
|
+
"agent2dashboard is not configured: " + "; ".join(self.config_problems)
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
# --- mounting ------------------------------------------------------------------------------
|
|
339
|
+
|
|
340
|
+
def is_enabled(self) -> bool:
|
|
341
|
+
"""`<prefix>ENABLED` (true/1/yes/on), from the environment `from_env` read, else from
|
|
342
|
+
`os.environ` with the default prefix. Off by default."""
|
|
343
|
+
from agent2dashboard._env import Env
|
|
344
|
+
|
|
345
|
+
return (self._env or Env()).enabled()
|
|
346
|
+
|
|
347
|
+
def mount(
|
|
348
|
+
self,
|
|
349
|
+
app: Any,
|
|
350
|
+
*,
|
|
351
|
+
prefix: str = DEFAULT_PREFIX,
|
|
352
|
+
enabled: bool | None = None,
|
|
353
|
+
migrate: bool = True,
|
|
354
|
+
**router_options: Any,
|
|
355
|
+
) -> bool:
|
|
356
|
+
"""Mount the SDK's routes on `app` under `prefix`; returns whether it did.
|
|
357
|
+
|
|
358
|
+
`enabled=None` reads `AGENT2DASHBOARD_ENABLED` (off by default). Off: nothing is
|
|
359
|
+
mounted and nothing is opened. On: `router(**router_options)` is included, in a
|
|
360
|
+
router whose lifespan runs `migrate()` on startup (when `migrate` and the storage is
|
|
361
|
+
`SqlAlchemyStorage`) and `aclose()` on shutdown; `app.state.agent2dashboard` is set.
|
|
362
|
+
"""
|
|
363
|
+
if enabled is None:
|
|
364
|
+
enabled = self.is_enabled()
|
|
365
|
+
if not enabled:
|
|
366
|
+
return False
|
|
367
|
+
self._check_configured()
|
|
368
|
+
from fastapi import APIRouter
|
|
369
|
+
|
|
370
|
+
@asynccontextmanager
|
|
371
|
+
async def lifespan(_: Any) -> AsyncIterator[None]:
|
|
372
|
+
if migrate and self._uses_sql_storage():
|
|
373
|
+
await self.migrate()
|
|
374
|
+
try:
|
|
375
|
+
yield
|
|
376
|
+
finally:
|
|
377
|
+
await self.aclose()
|
|
378
|
+
|
|
379
|
+
outer = APIRouter(lifespan=lifespan)
|
|
380
|
+
outer.include_router(self.router(**router_options))
|
|
381
|
+
app.include_router(outer, prefix=prefix)
|
|
382
|
+
app.state.agent2dashboard = self
|
|
383
|
+
return True
|
|
384
|
+
|
|
385
|
+
def _uses_sql_storage(self) -> bool:
|
|
386
|
+
from agent2dashboard.storage import SqlAlchemyStorage
|
|
387
|
+
|
|
388
|
+
return isinstance(self.resolve_storage(), SqlAlchemyStorage)
|
|
389
|
+
|
|
390
|
+
async def aclose(self) -> None:
|
|
391
|
+
"""Stop this instance's runs (`shutdown()`), then close the event bus, dispose the
|
|
392
|
+
data source and the engines `from_env` created. Safe to call twice."""
|
|
393
|
+
if self._closed:
|
|
394
|
+
return
|
|
395
|
+
self._closed = True
|
|
396
|
+
await self.shutdown()
|
|
397
|
+
for closer in (
|
|
398
|
+
getattr(self.events, "close", None),
|
|
399
|
+
getattr(self.data, "dispose", None),
|
|
400
|
+
*(engine.dispose for engine in self._owned_engines),
|
|
401
|
+
):
|
|
402
|
+
if closer is not None:
|
|
403
|
+
await closer()
|
|
404
|
+
|
|
405
|
+
def resolve_storage(self) -> Storage:
|
|
406
|
+
"""The `Storage` passed in, or `SqlAlchemyStorage` over `storage_session` with the
|
|
407
|
+
config's schema and table prefix."""
|
|
408
|
+
if self.storage is None:
|
|
409
|
+
if self.storage_session is None:
|
|
410
|
+
raise ValueError("AgentDashboard needs storage or storage_session")
|
|
411
|
+
from agent2dashboard.storage import SqlAlchemyStorage, TableNames
|
|
412
|
+
|
|
413
|
+
self.storage = SqlAlchemyStorage(
|
|
414
|
+
self.storage_session,
|
|
415
|
+
TableNames.prefixed(self.config.table_prefix),
|
|
416
|
+
schema=self.config.schema,
|
|
417
|
+
)
|
|
418
|
+
return self.storage
|
|
419
|
+
|
|
420
|
+
async def migrate(self) -> None:
|
|
421
|
+
"""Create or upgrade the SDK's tables (`agent2dashboard.migrations.migrate`) through
|
|
422
|
+
the storage's session factory, in the storage's schema, and commit. Safe on every
|
|
423
|
+
start; concurrent callers wait for one another."""
|
|
424
|
+
from agent2dashboard.migrations import migrate
|
|
425
|
+
from agent2dashboard.storage import SqlAlchemyStorage
|
|
426
|
+
|
|
427
|
+
storage = self.resolve_storage()
|
|
428
|
+
if not isinstance(storage, SqlAlchemyStorage):
|
|
429
|
+
raise TypeError("migrate() needs SqlAlchemyStorage; a custom Storage migrates itself")
|
|
430
|
+
t = storage.tables
|
|
431
|
+
async with storage.session_factory() as session, session.begin():
|
|
432
|
+
conn = await session.connection()
|
|
433
|
+
await conn.run_sync(
|
|
434
|
+
lambda sync: migrate(sync, schema=t.schema, tables=t.names, principal=t.principal)
|
|
435
|
+
)
|
|
436
|
+
|
|
437
|
+
@property
|
|
438
|
+
def processor(self) -> Any:
|
|
439
|
+
"""The host's `ExpressProcessor` (agent copy of the catalog), built once."""
|
|
440
|
+
if self._processor is None:
|
|
441
|
+
from agent2dashboard.a2ui.express import ExpressProcessor
|
|
442
|
+
|
|
443
|
+
self._processor = ExpressProcessor(self.catalog)
|
|
444
|
+
return self._processor
|
|
445
|
+
|
|
446
|
+
@property
|
|
447
|
+
def query_service(self) -> Any:
|
|
448
|
+
"""The one `QueryService` (guard -> row filter -> read-only execute) for the agent's
|
|
449
|
+
`define_query` and the surface functions."""
|
|
450
|
+
if self._query_service is None:
|
|
451
|
+
from agent2dashboard.query import QueryService
|
|
452
|
+
|
|
453
|
+
self._query_service = QueryService(
|
|
454
|
+
self.data,
|
|
455
|
+
row_filter=self.row_filter,
|
|
456
|
+
max_rows=self.config.limits.max_rows_per_widget,
|
|
457
|
+
)
|
|
458
|
+
return self._query_service
|
|
459
|
+
|
|
460
|
+
def trace_sinks(self) -> tuple[TraceSink, ...]:
|
|
461
|
+
"""`traces`, plus a `DbTraceSink` writing `llm_call` rows when `record_llm_calls` and
|
|
462
|
+
none was passed."""
|
|
463
|
+
if self._trace_sinks is None:
|
|
464
|
+
from agent2dashboard.tracing import DbTraceSink
|
|
465
|
+
|
|
466
|
+
sinks = tuple(self.traces)
|
|
467
|
+
if self.record_llm_calls and not any(isinstance(s, DbTraceSink) for s in sinks):
|
|
468
|
+
sinks += (DbTraceSink(self.resolve_storage().llm_calls),)
|
|
469
|
+
self._trace_sinks = sinks
|
|
470
|
+
return self._trace_sinks
|
|
471
|
+
|
|
472
|
+
async def startup(self) -> None:
|
|
473
|
+
"""Checks the query connection once (`check_readonly_role`, §7); raises
|
|
474
|
+
`ReadOnlyRoleError` when it isn't a proper read-only role. The router runs it on
|
|
475
|
+
startup and again before any query, so a host can't skip it."""
|
|
476
|
+
if self._started:
|
|
477
|
+
return
|
|
478
|
+
if self._start_lock is None:
|
|
479
|
+
self._start_lock = asyncio.Lock()
|
|
480
|
+
async with self._start_lock:
|
|
481
|
+
if self._started:
|
|
482
|
+
return
|
|
483
|
+
from agent2dashboard.query import SqlAlchemyDataSource, check_readonly_role
|
|
484
|
+
|
|
485
|
+
if isinstance(self.data, SqlAlchemyDataSource):
|
|
486
|
+
self.readonly_check = await check_readonly_role(
|
|
487
|
+
self.data,
|
|
488
|
+
environment=self.config.environment,
|
|
489
|
+
allow_app_connection_for_queries=self.config.allow_app_connection_for_queries,
|
|
490
|
+
)
|
|
491
|
+
self._started = True
|
|
492
|
+
|
|
493
|
+
def router(
|
|
494
|
+
self,
|
|
495
|
+
*,
|
|
496
|
+
run_routers: Sequence[Any] | None = None,
|
|
497
|
+
action_handler: Any | None = None,
|
|
498
|
+
rate_limiter: Any | None = None,
|
|
499
|
+
) -> Any:
|
|
500
|
+
"""The FastAPI router to mount: conversations, surface functions and actions, the
|
|
501
|
+
catalog, and the run routes.
|
|
502
|
+
|
|
503
|
+
Run routes and the action handler come from `agent2dashboard.runs` when it provides
|
|
504
|
+
`build_runs_router(dashboard)` / `build_action_handler(dashboard)`; they can also be
|
|
505
|
+
passed here. `rate_limiter` replaces the per-instance limit of surface functions."""
|
|
506
|
+
from fastapi import APIRouter
|
|
507
|
+
|
|
508
|
+
self._check_configured()
|
|
509
|
+
|
|
510
|
+
from agent2dashboard import runs as runs_package
|
|
511
|
+
from agent2dashboard.http import (
|
|
512
|
+
InMemoryRateLimiter,
|
|
513
|
+
ResultCache,
|
|
514
|
+
SurfaceFunctions,
|
|
515
|
+
build_router,
|
|
516
|
+
)
|
|
517
|
+
from agent2dashboard.http.queries import build_queries_router
|
|
518
|
+
from agent2dashboard.http.revisions import build_revisions_router
|
|
519
|
+
|
|
520
|
+
storage = self.resolve_storage()
|
|
521
|
+
limits = self.config.limits
|
|
522
|
+
if run_routers is None:
|
|
523
|
+
factory = getattr(runs_package, "build_runs_router", None)
|
|
524
|
+
run_routers = [factory(self)] if factory is not None else []
|
|
525
|
+
if action_handler is None:
|
|
526
|
+
factory = getattr(runs_package, "build_action_handler", None)
|
|
527
|
+
action_handler = factory(self) if factory is not None else None
|
|
528
|
+
functions = SurfaceFunctions(
|
|
529
|
+
storage=storage,
|
|
530
|
+
queries=self.query_service,
|
|
531
|
+
can=self.auth.can,
|
|
532
|
+
rate_limiter=rate_limiter or InMemoryRateLimiter(limits.function_calls_per_minute),
|
|
533
|
+
cache=ResultCache(limits.function_cache_seconds),
|
|
534
|
+
semantic=self.semantic,
|
|
535
|
+
max_rows=limits.max_rows_per_widget,
|
|
536
|
+
concurrency=limits.render_concurrency,
|
|
537
|
+
)
|
|
538
|
+
inner = build_router(
|
|
539
|
+
self,
|
|
540
|
+
storage=storage,
|
|
541
|
+
functions=functions,
|
|
542
|
+
run_routers=[
|
|
543
|
+
*run_routers,
|
|
544
|
+
build_revisions_router(self, storage=storage),
|
|
545
|
+
build_queries_router(self, storage=storage, functions=functions),
|
|
546
|
+
],
|
|
547
|
+
action_handler=action_handler,
|
|
548
|
+
ready=self.startup,
|
|
549
|
+
)
|
|
550
|
+
|
|
551
|
+
@asynccontextmanager
|
|
552
|
+
async def lifespan(_: Any) -> Any:
|
|
553
|
+
await self.startup()
|
|
554
|
+
yield
|
|
555
|
+
|
|
556
|
+
outer = APIRouter(lifespan=lifespan)
|
|
557
|
+
outer.include_router(inner)
|
|
558
|
+
return outer
|
|
559
|
+
|
|
560
|
+
async def shutdown(self) -> None:
|
|
561
|
+
"""Stop the run reaper and this instance's runs (marked `interrupted`, §5.3)."""
|
|
562
|
+
from agent2dashboard.runs.hooks import shutdown_runs
|
|
563
|
+
|
|
564
|
+
await shutdown_runs(self)
|
|
565
|
+
|
|
566
|
+
def __repr__(self) -> str:
|
|
567
|
+
return f"AgentDashboard(config={self.config!r}, llm={type(self.llm).__name__})"
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def _langfuse_from_env(env: Any, environment: str) -> list[TraceSink]:
|
|
571
|
+
"""A Langfuse sink when `LANGFUSE_PUBLIC_KEY` and `LANGFUSE_SECRET_KEY` are set and the
|
|
572
|
+
`[langfuse]` extra is installed; otherwise none (the `llm_call` DB sink is always added)."""
|
|
573
|
+
import importlib.util
|
|
574
|
+
import logging
|
|
575
|
+
|
|
576
|
+
public_key, secret_key = env.raw("LANGFUSE_PUBLIC_KEY"), env.raw("LANGFUSE_SECRET_KEY")
|
|
577
|
+
if not (public_key and secret_key):
|
|
578
|
+
return []
|
|
579
|
+
if importlib.util.find_spec("langfuse") is None:
|
|
580
|
+
logging.getLogger(__name__).warning(
|
|
581
|
+
"LANGFUSE_* keys are set but the langfuse extra is not installed; no Langfuse traces"
|
|
582
|
+
)
|
|
583
|
+
return []
|
|
584
|
+
from agent2dashboard.tracing import LangfuseTraceSink
|
|
585
|
+
|
|
586
|
+
return [
|
|
587
|
+
LangfuseTraceSink(
|
|
588
|
+
public_key=public_key,
|
|
589
|
+
secret_key=secret_key,
|
|
590
|
+
base_url=env.raw("LANGFUSE_HOST") or env.raw("LANGFUSE_BASE_URL"),
|
|
591
|
+
environment=environment,
|
|
592
|
+
)
|
|
593
|
+
]
|
agent2dashboard/_env.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Reading the SDK's settings from environment variables (`AgentDashboard.from_env`, the CLI).
|
|
2
|
+
|
|
3
|
+
Values are never logged, and errors name the variable, never its value: database and Redis
|
|
4
|
+
URLs carry passwords.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
|
|
12
|
+
from sqlalchemy.engine import make_url
|
|
13
|
+
from sqlalchemy.exc import ArgumentError
|
|
14
|
+
|
|
15
|
+
from agent2dashboard.errors import ConfigurationError
|
|
16
|
+
|
|
17
|
+
__all__ = ["DEFAULT_ENV_PREFIX", "Env", "async_database_url", "env_flag"]
|
|
18
|
+
|
|
19
|
+
DEFAULT_ENV_PREFIX = "AGENT2DASHBOARD_"
|
|
20
|
+
_TRUE = frozenset({"1", "true", "yes", "on"})
|
|
21
|
+
_FALSE = frozenset({"", "0", "false", "no", "off"})
|
|
22
|
+
_SYNC_DRIVERS = frozenset({"postgresql", "postgres", "postgresql+psycopg2"})
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def async_database_url(raw: str, *, name: str = "database URL") -> str:
|
|
26
|
+
"""`raw` with a sync Postgres driver (`postgresql://`, `postgresql+psycopg2://`) replaced
|
|
27
|
+
by psycopg's async one. `name` is used in the error instead of the URL."""
|
|
28
|
+
try:
|
|
29
|
+
url = make_url(raw)
|
|
30
|
+
except ArgumentError:
|
|
31
|
+
raise ConfigurationError(f"{name} is not a valid database URL") from None
|
|
32
|
+
if url.drivername in _SYNC_DRIVERS:
|
|
33
|
+
url = url.set(drivername="postgresql+psycopg")
|
|
34
|
+
return url.render_as_string(hide_password=False)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def env_flag(value: str | None, *, name: str = "flag", default: bool = False) -> bool:
|
|
38
|
+
"""`true`/`1`/`yes`/`on` (any case) is on, `false`/`0`/`no`/`off`/empty is off."""
|
|
39
|
+
if value is None:
|
|
40
|
+
return default
|
|
41
|
+
text = value.strip().lower()
|
|
42
|
+
if text in _TRUE:
|
|
43
|
+
return True
|
|
44
|
+
if text in _FALSE:
|
|
45
|
+
return False
|
|
46
|
+
raise ConfigurationError(f"{name} must be true or false")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class Env:
|
|
50
|
+
"""Prefixed variables (`<prefix>NAME`), with an optional unprefixed fallback."""
|
|
51
|
+
|
|
52
|
+
def __init__(
|
|
53
|
+
self, environ: Mapping[str, str] | None = None, prefix: str = DEFAULT_ENV_PREFIX
|
|
54
|
+
) -> None:
|
|
55
|
+
self.environ: Mapping[str, str] = os.environ if environ is None else environ
|
|
56
|
+
self.prefix = prefix
|
|
57
|
+
|
|
58
|
+
def name(self, key: str) -> str:
|
|
59
|
+
return f"{self.prefix}{key}"
|
|
60
|
+
|
|
61
|
+
def get(self, key: str, *fallbacks: str) -> str | None:
|
|
62
|
+
"""`<prefix>key`, else the first fallback set (unprefixed names). Empty is unset."""
|
|
63
|
+
for name in (self.name(key), *fallbacks):
|
|
64
|
+
value = self.environ.get(name)
|
|
65
|
+
if value is not None and value.strip() != "":
|
|
66
|
+
return value.strip()
|
|
67
|
+
return None
|
|
68
|
+
|
|
69
|
+
def raw(self, name: str) -> str | None:
|
|
70
|
+
"""An unprefixed variable (empty is unset)."""
|
|
71
|
+
value = self.environ.get(name)
|
|
72
|
+
return value.strip() if value is not None and value.strip() != "" else None
|
|
73
|
+
|
|
74
|
+
def flag(self, key: str, *, default: bool = False) -> bool:
|
|
75
|
+
return env_flag(self.environ.get(self.name(key)), name=self.name(key), default=default)
|
|
76
|
+
|
|
77
|
+
def enabled(self) -> bool:
|
|
78
|
+
"""`<prefix>ENABLED`, off by default."""
|
|
79
|
+
return self.flag("ENABLED")
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""a2ui: filled by a later task (design §2.1)."""
|