Lotus.AI.QueryOptimizer (Lotus v1.0.0)

Copy Markdown View Source

Generates AI-powered optimization suggestions for a query.

Runs the adapter's prepare_for_analysis/2 to resolve Lotus template syntax into a form parseable by the engine's diagnostic endpoint, calls query_plan/3 to get an execution plan (when available), and sends both the statement and the plan to the LLM for review.

The module is adapter-agnostic — SQL dialects produce EXPLAIN output, non-SQL adapters can produce whatever their native profile/diagnostic API returns (or nil if unavailable; the LLM then reviews the statement structurally).

Summary

Functions

Generate optimization suggestions for a statement.

Types

optimization_response()

@type optimization_response() :: %{
  suggestions: [map()],
  model: String.t(),
  usage: %{
    prompt_tokens: non_neg_integer(),
    completion_tokens: non_neg_integer(),
    total_tokens: non_neg_integer()
  }
}

Functions

suggest_optimizations(model_string, opts)

@spec suggest_optimizations(
  String.t(),
  keyword()
) :: {:ok, optimization_response()} | {:error, term()}

Generate optimization suggestions for a statement.

Options

  • :statement (required) — a %Lotus.Query.Statement{} to review.
  • :data_source (required) — name of the data source.
  • :api_key (required) — API key for the LLM provider.
  • :search_path (optional) — Postgres search path.
  • :temperature (optional) — LLM temperature (default: 0.1).

Returns

  • {:ok, result} — map with :suggestions, :model, :usage.
  • {:error, :ai_not_supported_for_source} — adapter returned {:error, _} from ai_context/1.
  • {:error, term} — other failure.