Skip to main content

Query and Explore usage data

Query and Explore lets you answer your own questions about how your organisation uses AI through the gateway, without exporting anything. Which models cost the most this week? Which team's spend doubled since last month? How many people used our chat app yesterday, and how many of last week's new users came back? You can write the question as one SQL SELECT, let Ask AI write the SQL for you, or click a chart together in Explore without any SQL at all. Queries and charts you use often can be saved and shared with your colleagues.

Everything on this page only reads. Nobody can change or delete data from here, prompts, answers and IP addresses are never visible, and each person only ever sees the rows their role allows, also when they open a query someone else shared.

A real-world scenario​

The finance lead asks the platform team why AI spend rose 40 percent last week. An admin opens Observability, then Query and Explore, switches to Explore and picks Spend (USD) split by Team. One team stands out. In Trends she ranks models by spend, last 7 days against the 7 before, and sees that the team moved a batch job to a larger model. She opens the Query tab, asks Ask AI "spend per day for team payments by model over the last 14 days", runs the draft, downloads the CSV for finance and saves the query as "Payments spend by model", shared with everyone, so the team lead can open it too. The team lead opens the shared query and sees the same numbers for his own team, but nothing about other teams, because a shared query always runs with the rights of the person who opens it.

Who sees what​

RoleRows they seeSave and shareAsk AI
Proxy adminEvery rowYes, and may change or delete anyone's saved itemsYes
Admin viewerEvery rowNoNo
Org admin and internal userTheir own requests and the requests of teams whose logs they may readYes, their own itemsNo
Internal viewerTheir own requests and the requests of teams whose logs they may readNoNo
A virtual key with no userNothing, the routes answer 403NoNo

"Teams whose logs they may read" means teams where the person is a team admin or has the spend logs permission, the same rule as the Logs page. Ask AI is for proxy admins only, because the model call that writes the draft is billed to the gateway.

What you can query​

A query may read five tables. Each one is a safe view of the real table: it only has the columns listed below, only rows inside the time window, and only the rows your role may see. GET /analytics/query/help and the Tables you can query box on the page list the same tables with the rows you see in each.

TableOne row perColumns
spend_logsrequest, last 30 days by defaultrequest_id, call_type, api_key (the key's hash, never the key), spend, total_tokens, prompt_tokens, completion_tokens, start_time, end_time, request_duration_ms, completion_start_time, model, model_id, model_group, provider, user_id, team_id, organization_id, end_user, session_id, status, cache_hit, mcp_tool, agent_id, routing_preset (the routing preset that served the request), budget_tier (the budget tier that served it)
daily_user_spendday, gateway user, key, model and route, last 365 days by defaultuser_id, date, api_key, model, model_group, provider, mcp_tool, endpoint, prompt_tokens, completion_tokens, cache_read_input_tokens, spend, api_requests, successful_requests, failed_requests, total_response_time_ms, timed_requests
daily_team_spendday, team, key, model and routeteam_id and the same usage columns
daily_end_user_spendday, end user of your application, key, model and routeend_user_id and the same usage columns
daily_tag_spendday, request tag, key, model and route. A request with two tags counts under each tagtag and the same usage columns

Prompts, answers, request metadata, IP addresses and provider addresses are not in any of these tables, so no query can read them. The only values taken from the request metadata are the routing preset and the budget tier. Dates in the daily tables are text in YYYY-MM-DD form, so write date::date when you do date math.

A query may use SELECT with joins, WITH, UNION, GROUP BY, HAVING, ORDER BY, LIMIT, FILTER, window functions and CASE, and these functions: abs, age, array_agg, avg, bool_and, bool_or, btrim, ceil, coalesce, concat, concat_ws, corr, count, covar_pop, covar_samp, cume_dist, current_date, date_part, date_trunc, dense_rank, exp, extract, first_value, floor, greatest, initcap, lag, last_value, lead, least, left, length, ln, log, lower, ltrim, make_interval, max, min, now, nth_value, ntile, nullif, percent_rank, percentile_cont, percentile_disc, position, power, rank, regexp_replace, replace, right, round, row_number, rtrim, sign, split_part, sqrt, stddev, stddev_pop, stddev_samp, string_agg, substring, sum, to_char, to_date, to_number, to_timestamp, trim, upper, var_pop, variance and width_bucket. A value may be cast to a number, text, date, timestamp, boolean or interval.

How the gateway keeps a query safe​

Before anything reaches the database, the gateway reads the SQL into a syntax tree and checks every part of it against a list of what is allowed. Anything else is refused with a message that names the problem, for example the function pg_read_file is not allowed or unknown table Spanway_UserTable. Only one statement is accepted, it must be a SELECT, and recursive queries, parameters, SELECT INTO, row locks, schema names and any table or function not listed above are refused.

The statement that runs is then written by the gateway from the checked tree, with every table swapped for its safe view and every name quoted, so nothing you typed reaches the database without passing the checks. It runs in a transaction that cannot write, with a time limit, and on the read replica when one is configured (DATABASE_URL_READ_REPLICA). For users who only see their own rows, each view is filtered before your query looks at it, so your own conditions can never be tested against other people's rows. The database itself adds up the size of the answer and stops the query when it passes 10 MB, so an oversized answer never reaches the gateway's memory. Functions that only make values longer, such as lpad, rpad and repeat, are not allowed. Each gateway instance runs at most max_concurrent queries at once and answers 429 with Retry-After when it is busy.

Ask AI​

Ask AI writes the SQL for you from a question in plain words. You pick a model that is served by this gateway, the gateway sends the model your question and the list of tables and columns (never your data), checks the draft with the same rules as a run and puts it in the editor. Nothing runs until you press Run. If the draft would be refused, the page says why so you can fix it first. Each draft writes an audit row with the model and the length of the question, not the question itself.

Explore​

Explore charts one measure, such as spend, requests, tokens, failed requests or average response time, from the daily usage tables between two dates, split by up to two of eleven dimensions: day, model, model name asked for, provider, key, gateway route, MCP tool, user, team, end user and request tag. Splitting or filtering by user, team, end user or tag reads that table, so only one of those four can be used in one chart. There is no MCP server dimension. MCP tool names start with their server name, and the server split lives on the MCP usage view. MCP calls are tagged with the client app as MCP-Client: <label> when a client label is set up, so the request tag dimension filtered on that tag charts one client app.

Trends compares the last 1, 7 or 30 days with the same number of days before and lists what moved most, for example the models whose spend grew fastest. A group with nothing in the earlier period shows as new. The database ranks every group before the top ones are picked, so even with thousands of end users, keys or tags the biggest movers shown are the real ones.

Saved queries and charts​

A query or an Explore chart can be saved under a name, so you can open it again with one click. A saved item is private by default and only you see it. Turn on Share this query with everyone (or Share this chart with everyone) to list it for everyone who can use the page, for example a weekly cost review the whole platform team uses. Sharing shares the question, never the answers: whoever opens a shared item runs it with their own rights and sees only the rows their role allows. The owner and proxy admins can Share, Unshare and Delete an item, and each person can keep up to 200 items.

End user analytics​

From one header: if your application sends the header x-spanway-end-user-id (or x-spanway-customer-id, or the OpenAI user field) with each request, the gateway counts each value as one end user of your application. Nothing else needs to be set up. The End users section of Explore then shows how many end users were active each day of the last 30 days, how many were new that day, and a weekly retention table: end users grouped by the week they first sent a request, with the share of each group that came back in each later week. The same numbers are in GET /analytics/users/active and GET /analytics/users/retention. First use is counted inside the daily window (365 days by default).

curl http://localhost:4000/v1/chat/completions \
-H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \
-H "x-spanway-end-user-id: customer-4711" \
-d '{"model": "gpt-5.5", "messages": [{"role": "user", "content": "Hello"}]}'

Step by step​

  1. Make sure the gateway has a database (DATABASE_URL). The tables above are filled by every request already, nothing else is needed.

  2. In the Admin UI open Observability, then Query and Explore. The Query tab opens with an example query.

  3. Press Run, or run a query over the API:

    curl -X POST http://localhost:4000/analytics/query \
    -H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
    -d '{"sql": "SELECT model, count(*) AS requests, round(sum(spend)::numeric, 4) AS spend FROM spend_logs WHERE start_time > now() - make_interval(days => 7) GROUP BY model ORDER BY spend DESC"}'

    Expected result: {"columns": ["model", "requests", "spend"], "rows": [["gpt-5.5", 1240, 18.4127], ["claude-sonnet-5-5", 610, 9.0312]], "row_count": 2, "truncated": false, "elapsed_ms": 42}. When truncated is true more rows matched than the row limit, so add a filter or a GROUP BY.

  4. Press Download CSV or Download JSON to take the result to a spreadsheet. A cell that starts with =, +, - or @ is written with a leading ' so a spreadsheet does not run it as a formula.

  5. As a proxy admin, type a question in Ask AI, pick a Model and press Draft SQL. Over the API:

    curl -X POST http://localhost:4000/analytics/query/draft \
    -H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
    -d '{"question": "Which models cost the most this week?", "model": "gpt-5.5"}'

    Expected result: {"sql": "SELECT model, ...", "model": "gpt-5.5", "valid": true, "problem": null}.

  6. Type a name in Save query as, turn on Share this query with everyone if colleagues should see it, and press Save query. Over the API:

    curl -X POST http://localhost:4000/analytics/saved \
    -H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
    -d '{"name": "Spend per model this week", "visibility": "shared", "definition": {"kind": "sql", "sql": "SELECT model, sum(spend) FROM spend_logs GROUP BY model"}}'

    Expected result: the saved item with its query_id. It appears under Saved queries, where its owner (or a proxy admin) can Share, Unshare or Delete it.

  7. Open the Explore tab, pick a Measure, Split by and optionally Then by, set From and To and press Show. Over the API:

    curl -X POST http://localhost:4000/analytics/explore \
    -H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
    -d '{"metric": "spend", "group_by": ["date", "model"], "start_date": "2026-11-01", "end_date": "2026-11-22"}'

    Expected result: {"metric": "spend", "group_by": ["date", "model"], "source": "daily_user_spend", "rows": [{"group": ["2026-11-22", "gpt-5.5"], "value": 12.5}], "truncated": false}. Save it with Save chart as and Save chart.

  8. Read Trends and End users further down the tab, or call:

    curl "http://localhost:4000/analytics/trends?metric=spend&dimension=model&days=7" -H "Authorization: Bearer $SPANWAY_MASTER_KEY"
    curl "http://localhost:4000/analytics/users/active" -H "Authorization: Bearer $SPANWAY_MASTER_KEY"
    curl "http://localhost:4000/analytics/users/retention?weeks=8" -H "Authorization: Bearer $SPANWAY_MASTER_KEY"
  9. Open Logs, then Audit logs, to see who ran which query (by the hash of its SQL) and who saved, changed or deleted which saved item.

Settings​

All settings sit under general_settings.analytics_query in the config file. Leave it out to use the defaults.

general_settings:
analytics_query:
enabled: true
max_rows: 1000
timeout_seconds: 10
spend_log_days: 30
daily_days: 365
max_concurrent: 4
SettingDefaultWhat it does and when to change it
enabledtrueTurns the whole page and its routes on or off. Turn it off if you do not want anyone to run their own queries. When off, every route answers 403 disabled and the rest of the gateway is not affected.
max_rows1000The most rows one query returns, from 1 to 10,000. A caller can ask for fewer with max_rows in the request but never more. Raise it for larger exports, at the cost of larger answers.
timeout_seconds10How long a query may run before the database stops it, from 1 to 60. Raise it if legitimate reports over a long period time out, keep it low to protect the database on busy days.
spend_log_days30How many days of single requests spend_logs shows, from 1 to 365. Longer windows let you query further back but make queries over all rows slower. The daily tables cover longer periods cheaply.
daily_days365How many days of daily totals the daily tables show, from 1 to 1,830.
max_concurrent4How many queries one gateway instance runs at the same time, from 1 to 32. More let more people work at once, fewer protect the database. Further queries answer 429 until one finishes.

An invalid block, for example one with a misspelled key or a value out of range, turns analytics off until it is fixed, so a block meant to turn the feature off can never turn it on by mistake. Every route then answers 403 disabled and the gateway logs a warning, see the logs below.

Routes​

MethodPathWhat it doesWho
GET/analytics/query/helpThe tables, columns, functions, limits and examples for the caller.Any gateway user
POST/analytics/queryRuns one read only SELECT.Any gateway user
POST/analytics/query/draftAsk AI, drafts SQL from a question with a model on this gateway.Proxy admins
POST/analytics/exploreOne measure grouped by up to two dimensions.Any gateway user
GET/analytics/trendsWhat moved most against the previous period.Any gateway user
GET/analytics/users/activeDaily active and new end users.Any gateway user
GET/analytics/users/retentionWeekly retention of end users.Any gateway user
GET/analytics/savedYour saved items and the shared ones.Any gateway user
GET/analytics/saved/{query_id}One saved item you own or that is shared.Any gateway user
POST/analytics/savedSaves a query or chart, at most 200 per person.Proxy admins, org admins and internal users
PATCH/analytics/saved/{query_id}Renames, shares, unshares or replaces an item.The owner or a proxy admin
DELETE/analytics/saved/{query_id}Deletes an item.The owner or a proxy admin

Audit​

TableActionWhen and what
Spanway_SpendLogs (Request logs)viewedEvery query sent, always, whatever audit_log_list_reads says, because a query can read any column of the tables above. That includes queries the checks refused, queries the database stopped and queries turned away while the instance was busy, so admins can see attempts to get around the checks. object_id analytics_query, with read analytics_query, the SHA-256 hash and length of the SQL (never the SQL), the tables it read, the scope (all or owned), the outcome (ok, refused, failed, timeout, busy or unavailable), row_count and truncated when it ran, the error_code when it did not, the checks' reason when they refused it, the caller's role, ip and user_agent.
Spanway_SpendLogs (Request logs)invokedEvery Ask AI draft. object_id analytics_query_draft, with the model, the length of the question and whether the draft was valid.
Spanway_AnalyticsSavedQuery (Saved queries and charts)created, updated, deletedSaving, changing and deleting a saved query or chart, with the item before and after.

Explore, Trends and the end user views read daily totals only and write no audit row.

Privacy​

Saved items hold the name, description, SQL or chart settings and the owner's user id. They never hold query results. A data subject request exports the saved items a user owns, created or last changed, and erasure deletes the items the user owns and replaces their id with the pseudonym where they only made the last change. The end user analytics count end user ids from the daily totals, which a data subject request for an end user already pseudonymises.

Errors​

Errors answer as {"detail": {"code": "<code>", "message": "<message>"}}.

Status and codeExample messageMeaningFix
400 query_refusedthe function pg_read_file is not allowed, unknown table Spanway_UserTable, tables you may read: ..., only SELECT queries are allowed, send exactly one statementThe SQL uses something the checks do not allow. Nothing ran.Use only the tables, functions and statement shapes listed on this page.
400 query_failedcolumn "cost" does not exist, a column has the type interval, cast it to text or a number, the result is larger than 10 MB, return fewer rows or shorter valuesThe database could not run the query, returned a value the gateway cannot send, or the answer would be larger than 10 MB, in which case the database stops it before anything is sent.Fix the column name or cast the value, for example extract(epoch FROM age(start_time)).
400 query_timeoutthe query ran past the time limitThe query ran longer than timeout_seconds and was stopped.Narrow the dates, use a daily table instead of spend_logs, or raise timeout_seconds.
400 invalid_requestuser, team, end_user and tag come from different tables, pick one of them, model gpt-unknown is not served by this gatewayAn Explore, Trends or end user request that cannot be answered, or an Ask AI model this gateway does not serve.Pick one of the four, or a model from Models + Endpoints.
400 limit_reachedyou already have 200 saved itemsEach person may keep 200 saved items.Delete items you no longer need.
403 forbiddenAnalytics queries need a gateway user, this key belongs to no userA virtual key that belongs to no user, a view only role trying to save, Ask AI for a non admin, or a change to someone else's item.Use a key or Admin UI session that belongs to a user with the right role.
403 disabledAnalytics queries are turned off on this gatewayanalytics_query.enabled is false, or the analytics_query block is invalid.Ask an admin to turn it on or fix the block the log warning names.
404 not_foundsaved query <id> not foundNo saved item has that id, or it is private to someone else.Check the id in GET /analytics/saved.
422Value error, text must not contain control characters, answered in FastAPI's {"detail": [...]} list formA name, description, filter value or question holds control characters, or a field is out of range.Send plain text within the limits.
429 busy4 queries are already running, try again shortlyThis gateway instance already runs max_concurrent queries.Retry after the Retry-After seconds.
500 unavailableDB not connected. This endpoint needs a database; set DATABASE_URL ...The gateway runs without a database.Set DATABASE_URL.
503 unavailablethe database did not answerThe database or the read replica did not answer.Check the database and retry.

Logs​

LevelLineMeaningAction
WARNINGgeneral_settings.analytics_query is invalid, analytics stay off until it is fixed: <error>A value in the analytics_query block is out of range, of the wrong type, or the block has an unknown key, so analytics are turned off.Fix the value the error names.

Refused and failed queries are answered to the caller and written to the audit log with a hash of the SQL, never to the gateway log, so SQL text never reaches either.