Building a custom AskLens UI¶
AskLens does not require the packaged browser UI. Treat the packaged page as a demo shell around the public API. Production projects can build their own React, Vue, HTMX, Django-template, mobile, Slack, or internal dashboard UI and render AskLens results however they want.
Before replacing that shell, the synthetic source-demo journey provides a no-API-key reference for login, an exact suggested success, scoped empty results, safe errors, opaque denial, and cleanup. At the immutable v0.3.2 tag it reflects release-source behavior; mutable main may become newer than the public wheel.
Endpoints to call¶
Mount the API routes:
from django.urls import include, path
urlpatterns = [
path("", include("django_asklens.api.urls")),
]
Then call the same permission-gated endpoints your UI needs:
GET /asklens/catalog/
GET /asklens/capabilities/
POST /asklens/query/
GET /asklens/runs/<id>/
The endpoints use your normal Django/DRF authentication and configured AskLens API permission classes. Catalog resource/field visibility and query-help suggestions are scoped to the current request. Machine capabilities describe the installed implementation and contain no resource catalog or human help.
Discover machine capabilities and the visible catalog¶
Use /asklens/capabilities/ for machine-readable query features and limits.
An abbreviated response is:
{
"intents": ["list", "aggregate"],
"filter_logic": "implicit_and",
"types": [
{"name": "string", "operators": ["eq", "neq", "contains", "icontains", "in", "isnull"]}
],
"time_grains": ["day", "week", "month", "quarter", "year"],
"limits": {"max_result_rows": 500, "default_result_limit": 100},
"features": {"registered_metrics": true, "raw_sql": false},
"aggregate_policies": {
"to_many_count_policies": ["count_rows", "count_distinct"],
"numeric_to_many": false
},
"backend_restrictions": []
}
Use /asklens/catalog/ separately for permission-scoped resources:
{
"resources": [
{
"name": "orders",
"label": "Orders",
"timezone": "UTC",
"fields": [
{"name": "status", "label": "Status", "type": "enum", "nullable": false}
],
"metrics": [
{"name": "order_count", "label": "Orders", "result_type": "integer"}
]
}
]
}
Both responses are metadata only and contain no rows or sample values. Ask a
help question through /asklens/query/ when the UI needs human suggestions.
Common UI uses include:
- combine catalog field types with capability operator rules
- display visible resources/fields in a help panel
- hide the query composer when the catalog has no resources
- render starter questions from
help.content.suggestions
Ask a question¶
Send natural-language questions to /asklens/query/:
POST /asklens/query/
Content-Type: application/json
{"question": "Show orders by status"}
A data-query response includes response_type: "query", adapter metadata, and
one complete core result document with normalized rows, column metadata,
timing, and deterministic limit metadata:
{
"run_id": 42,
"question": "Show orders by status",
"response_type": "query",
"plan": {"resource": "orders", "intent": "aggregate", "limit": 10},
"result": {
"columns": [
{"key": "status", "label": "Status", "type": "string", "nullable": false},
{
"key": "order_count",
"label": "Orders",
"type": "integer",
"nullable": false
}
],
"data": [
{"status": "paid", "order_count": 120},
{"status": "pending", "order_count": 34}
],
"row_count": 2,
"duration_ms": 18,
"result_metadata": {
"limit": 10,
"limit_scope": "groups",
"truncated": false
}
},
"presentation": {"kind": "bar", "x": {"field": "status"}, "y": {"field": "order_count"}}
}
For grouped aggregate/chart responses, result.result_metadata.limit caps
returned groups or slices. For list/table responses, it caps returned rows. If
result.result_metadata.truncated is true, another matching row/group exists
beyond the returned limit; show a message such as “Showing the first N results.
Refine filters or increase the limit.” Ungrouped aggregates have effective limit
one and are never truncated. AskLens does not provide cursor pagination.
Use each column's canonical type and nullable metadata rather than inferring
types from the first row. Decimal values are strings to preserve precision.
Empty ungrouped aggregates contain one row (count=0, other aggregate values
null); empty grouped aggregates contain no rows and add result.empty: true.
Present that as a successful scoped result (for example, “No matching rows in
your current authorized scope”), not as an authorization failure or a statement
about rows outside the current user's scope.
Render tables by iterating result.columns for headers and result.data for row
values:
function renderTable(response) {
const table = document.createElement("table");
const thead = table.createTHead();
const header = thead.insertRow();
response.result.columns.forEach((column) => {
const th = document.createElement("th");
th.textContent = column.label || column.key;
header.appendChild(th);
});
const tbody = table.createTBody();
response.result.data.forEach((row) => {
const tr = tbody.insertRow();
response.result.columns.forEach((column) => {
const td = tr.insertCell();
td.textContent = row[column.key] ?? "";
});
});
return table;
}
Render charts with any charting library by mapping presentation.x.field and
presentation.y.field to values in result.data:
function toBarSeries(response) {
const x = response.presentation?.x?.field;
const y = response.presentation?.y?.field;
if (!x || !y) return null;
return response.result.data.map((row) => ({
label: row[x],
value: row[y],
}));
}
Presentation is separate and optional¶
presentation is display metadata outside QueryPlan, not an executable renderer contract. It cannot affect authorization, scope, compilation, ordering, limits, or returned values. Your UI can:
- ignore it and always render a table
- use it to choose a chart type
- replace it with your own chart rules
- request no presentation when you only need serialized data
POST /asklens/query/
Content-Type: application/json
{"question": "Show orders by status", "include_presentation": false}
When include_presentation is false, the response still includes the complete
result child and audit metadata.
Handle help responses¶
Questions such as show me example queries or what can I ask? return
response_type: "capabilities" and do not execute a database query. Exact
machine capabilities and permission-scoped catalog documents are siblings of
adapter-only routing and human help objects:
{
"response_type": "capabilities",
"routing": {"intent": {"intent": "capabilities"}, "source": "fallback"},
"capabilities": {"intents": ["list", "aggregate"], "filter_logic": "implicit_and"},
"catalog": {"resources": [{"name": "orders", "label": "Orders"}]},
"help": {
"source": "deterministic",
"content": {
"answer": "Try these examples.",
"suggestions": [
{
"question": "Show count of Orders by Status",
"resource_name": "orders",
"plan": {"resource": "orders", "intent": "aggregate"}
}
]
}
}
}
help.content is human guidance, not the internal machine capabilities
document. An optional safe fallback reason appears as help.error.
Your UI should branch on response_type:
if (response.response_type === "capabilities") {
renderSuggestions(response.help.content.suggestions);
} else {
renderTable(response);
}
Handle failures¶
Every handled failure from the four AskLens DRF views uses one route-local shape:
{
"error": {
"code": "asklens.authorization.denied",
"message": "The current request is not authorized."
}
}
A privacy-aware accepted AskLens failure may also include top-level run_id when the database audit sink created a row. Do not look for legacy response_type, echoed question, redundant status, or DRF detail fields. Branch on error.code, display only error.message, and continue honoring the HTTP status plus Allow, WWW-Authenticate, or Retry-After headers where applicable. This adapter is local to AskLens routes; unrelated host DRF endpoints keep the host's configured exception behavior.
Query request objects are strict. Send only question, debug, include_presentation, plan, and presentation; do not send user IDs, permissions, tenant IDs, scope tokens, audit aliases, or other policy claims. Unknown top-level keys fail before orchestration and are not echoed.
Saving queries¶
A custom UI can save useful questions in local storage, bookmarks, a project-owned database table, or another application-owned model. AskLens does not ship a first-class server-side saved-query model in alpha. A saved item can store:
{
"question": "Show count of Orders by Status",
"plan": {"resource": "orders", "intent": "aggregate"}
}
When replaying a saved suggestion, send both fields back to /asklens/query/:
POST /asklens/query/
Content-Type: application/json
{
"question": "Show count of Orders by Status",
"plan": {"resource": "orders", "intent": "aggregate"}
}
The normal AskLens API revalidates submitted plans against the current request's permissions, resource catalog, field rules, and current plan limits before execution. Execution then resolves the resource's fail-closed scope policy: deliberately reviewed per-resource global scope or a trusted current-request scope_provider under context_scoped, which may be configured once as the safe project default. Missing or invalid scope rejects without falling back to the model manager. This applies to clicked suggestions, browser-saved plans, server-saved plans, and UI-edited plans with changed filters, date intervals, ordering, or limits. A saved plan is an optimization and UX convenience, not a permission bypass.
If you build server-side saved queries, keep them project-owned until AskLens grows a first-class saved-query model after alpha. Suggested fields are:
- owner/user or team
- title
- original question
- optional saved plan JSON
- created/updated timestamps
- last run id or last run summary
Audit runs¶
For successful data queries and safe failures, AskLens writes SemanticQueryRun audit records. Retrieve one through:
GET /asklens/runs/42/
Use this for “view previous run” screens or audit links. The run endpoint still checks whether the current user may view the run.
Safety reminders for custom UIs¶
- Do not send database rows or sample values to LLM providers from your UI.
- Do not turn AskLens plans into SQL execution; AskLens is designed for validated Django ORM queries.
- Handle API failures through
error.codeand display onlyerror.message. Unknown and unauthorized members intentionally shareasklens.member.unavailable; do not attempt to infer hidden catalog membership. - Do not trust saved plans from the browser; submit them back to AskLens for revalidation.
- Keep route permissions on the API even if the UI page has its own access gate.