Provider configuration

AskLens treats provider output as untrusted data. A provider returns an envelope containing an executable query_plan and optional separate presentation; AskLens validates the plan before compilation or execution. Presentation metadata cannot alter authorization, scope, compilation, ordering, limits, or returned values. Metric requests contain only a registered semantic name; providers never choose or receive the operation, private Django binding, distinct key, or permission token.

Default backend: dummy

The default backend is deterministic and local:

DJANGO_ASKLENS = {
    "LLM_BACKEND": "dummy",
    "DUMMY_PLANS": {
        "Show orders by status": {
            "query_plan": {
                "resource": "orders",
                "intent": "aggregate",
                "group_by": [{"field": "status"}],
                "metrics": [{"metric": "order_count"}],
                "limit": 100,
            },
            "presentation": {
                "kind": "bar",
                "x": "status",
                "y": "order_count",
            },
        }
    },
    "DUMMY_DEFAULT_PLAN": None,
}

DummyProvider makes no network calls and requires no API keys. It matches the question string exactly; unless DUMMY_DEFAULT_PLAN is explicitly configured, arbitrary rewordings fail safely rather than being interpreted as natural language. Tests and evaluation fixtures should use it by default. To try the existing synthetic source demo with reviewed success, empty, denial, and error paths, follow Example Django AskLens integration.

OpenAI-compatible backend

AskLens includes an OpenAI-compatible chat-completions provider implemented with Python stdlib HTTP. It adds no required runtime dependency.

import os

DJANGO_ASKLENS = {
    "LLM_BACKEND": "openai_compatible",
    "LLM_BASE_URL": "https://api.openai.com/v1",
    "LLM_API_KEY": os.environ["OPENAI_API_KEY"],
    "LLM_MODEL": "gpt-4.1-mini",
    "LLM_TIMEOUT_SECONDS": 30,
    "LLM_TEMPERATURE": 0,
}

Use environment variables or your deployment secret manager for LLM_API_KEY. Do not commit API keys or place them in docs, fixtures, or tests.

Gemini through the OpenAI-compatible endpoint

Gemini can be used through Google's OpenAI-compatible endpoint:

import os

DJANGO_ASKLENS = {
    "LLM_BACKEND": "openai_compatible",
    "LLM_BASE_URL": "https://generativelanguage.googleapis.com/v1beta/openai",
    "LLM_API_KEY": os.environ["GEMINI_API_KEY"],
    "LLM_MODEL": "gemini-2.5-flash",
    "LLM_TIMEOUT_SECONDS": 30,
    "LLM_TEMPERATURE": 0,
}

As with every provider, Gemini output is still parsed as untrusted JSON and validated locally before execution.

For local prompt/provider tuning, you can temporarily enable provider I/O logging:

DJANGO_ASKLENS = {
    # ...
    "LOG_LLM_IO": True,
}

This logs the outbound chat-completions request body, raw provider response, and parsed JSON content to the django_asklens.llms.openai_compatible logger at INFO level. Authorization headers and API keys are excluded. Treat these logs as sensitive anyway: they can include user questions, permission-scoped provider-guidance/catalog metadata, and provider-generated plans/help. Do not enable this in production unless your logging pipeline is approved for that data.

The provider sends a request to:

POST {LLM_BASE_URL}/chat/completions

For normal live /asklens/query/ calls, it requests strict JSON output with a unified AskLens provider-response schema using OpenAI-compatible response_format={"type": "json_schema", ...}. That single response chooses either a data QueryPlan or capability QueryHelp. Other lower-level planner/helper APIs may request their narrower schemas directly.

Provider interface

Providers implement the LLMProvider protocol:

class LLMProvider(Protocol):
    def complete_json(
        self, *, messages: Sequence[LLMMessage], schema: Mapping[str, Any]
    ) -> Mapping[str, Any]: ...

AskLens sends:

  • permission-scoped provider guidance derived from safe catalog metadata and machine capabilities,
  • the user's question,
  • a strict JSON schema for the response being requested.

AskLens must not send sample database rows, secrets, credentials, .env content, or unregistered/unauthorized sensitive fields by default.

Prompt-size optimization

Live /asklens/query/ calls use internal permission-scoped query guidance for provider prompts. This guidance is derived from the separate catalog and machine capability facts; it is not the public machine capability document. By default, AskLens sends all visible resources in a compact provider-facing shape so the provider can choose among the user's full allowed catalog. Compact resource metadata retains the server-owned timezone, and compact field metadata retains canonical type, nullability, supported operators, and explicitly registered enum values/aliases; it still omits Django bindings, model labels, permission tokens, and database values. The provider cannot override the resource timezone in a plan.

Resource shortlisting is available as an opt-in prompt-size optimization for larger catalogs. When enabled, likely data questions send only the top matching visible resources before the provider call. This can reduce prompt size and cost, but it is not an authorization decision: every returned plan is still validated against the full catalog, request permissions, and limits before execution.

Explicit help questions such as show me example queries keep full visible provider guidance so users can discover everything available to them. Human examples and guidance never become fields in the machine capability document.

The alpha default is 0, which disables resource shortlisting:

DJANGO_ASKLENS = {
    "PROMPT_RESOURCE_SHORTLIST_LIMIT": 0,
}

To opt into data-question resource shortlisting, set a positive value such as 4 after validating representative questions against your catalog.

Testing live providers

Default tests never call live providers and require no API keys.

Run the opt-in live smoke test only when you explicitly want to test a configured provider:

DJANGO_ASKLENS_LIVE_LLM=1 \
DJANGO_ASKLENS_LIVE_LLM_API_KEY="$OPENAI_API_KEY" \
DJANGO_ASKLENS_LIVE_LLM_MODEL="gpt-4.1-mini" \
uv run pytest tests/evaluation/test_live_openai_compatible.py \
  tests/evaluation/test_live_api_openai_compatible.py

Optional:

DJANGO_ASKLENS_LIVE_LLM_BASE_URL="https://api.openai.com/v1"

The example Django app can also use the live provider by setting DJANGO_ASKLENS_DEMO_LIVE_LLM=1 before starting tests.test_project.demo_settings. See Example Django AskLens integration.

Live provider output must still pass strict schema parsing plus catalog/permission validation. Unified live query responses validate either the returned QueryPlan or the returned QueryHelp suggestions; help suggestions get executable plans synthesized and validated locally. Before production use, validate live provider behavior in a safe non-production environment that mirrors your permissions and tenant scoping.

Safety notes

  • Provider output is untrusted.
  • QueryPlan validation remains mandatory.
  • Never execute provider-generated SQL.
  • Do not send sample rows to providers by default.
  • Errors and opt-in provider I/O logs exclude API keys and authorization headers.