query

package
v0.1.0-alpha.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 12 Imported by: 0

README

graph/query

Turns a natural-language question into search hints. It reads no graph data, stores nothing and starts no goroutine. A hint is one entry of ClassificationResult.Options, a map keyed by the SearchOptions JSON names (time_range, path_start_node, ...).

How a question is classified

ClassifierChain.ClassifyQuery(ctx, question) asks its two tiers in order and answers from the first one that produces a hint. A tier is one stage of the chain:

Tier Type What it does Needs
0 KeywordClassifier Regular expressions over the question; confidence 1.0 Nothing
3 LLMClassifier Asks a language model and parses its JSON answer; confidence 0.9 An LLMClient you write; this package holds none. Few-shot examples from domain example files (LoadDomainExamples) are optional

No code produces tiers 1 or 2; the numbers are kept because callers read ClassificationResult.Tier. Tier 0 needs no external provider, and the package holds no embedding code.

The default result is tier 0, no hints, confidence 1.0. The chain answers it when no composed tier produced a hint, and when the LLM tier fails while the context is live (the error is not reported; call LLMClassifier.ClassifyQuery yourself to see it). A nil chain, a nil context or an ended context gets nil, never the default result.

A hint from the keyword tier ends the chain, so tier 3 never runs for that question. That holds for every hint the keyword tier produces, including hints a caller does not read.

ClassifyQuery returns (*ClassificationResult, error). The error is set only when the question holds an impossible number or, with the keyword tier composed, names two places (see "Bounds and refusals"); every other outcome has a nil error.

Use

domains := []*query.DomainExamples{examples} // from query.LoadDomainExamples; may be nil
chain := query.NewClassifierChain(query.NewKeywordClassifier(), query.NewLLMClassifier(client, domains))
result, err := chain.ClassifyQuery(ctx, "sensors in zone A last 3 hours")
if err != nil {
    return err // an impossible number or two places; see "Bounds and refusals"
}
if result == nil {
    return ctx.Err() // a nil chain, a nil context or an ended context
}

client is your LLMClient. Without one, query.NewClassifierChain(query.NewKeywordClassifier(), nil) is the keyword tier alone. NewLLMClassifier keeps the domains' examples and their Options maps; do not edit them after the call.

Hint names and value types

A hint's Go type is the same whichever tier produced it.

Hint Tier 0 Tier 3
time_range *TimeRange *TimeRange
geo_bounds *SpatialBounds not produced
use_embeddings bool bool
path_intent, ranking_intent bool not produced
path_start_node, aggregation_type, aggregation_field string not produced
path_predicates []string not produced
limit int int
strategy, query string string
predicates, types, key_terms []string []string

Tier 0 never produces path_predicates, strategy, query, predicates, types or key_terms; the types in its column are the SearchOptions field types.

Copies

A result's Options map is the caller's own: deleting or adding a key changes no later result. The values inside an entry may be shared, so do not edit what a pointer (*TimeRange, *SpatialBounds) or a slice points to.

Time zone

The keyword tier reads the clock once per question. "Today", "yesterday", "this week", "this month" and "this year" are calendar spans in the zone of that instant, which is the server's own zone (time.Local, which Go's time package documentation says comes from the TZ environment variable, else the system's local zone, else UTC; not probed here). A server in Tokyo and a server in London answer "today" with different spans. A setting to choose the zone is not present; it waits until a consumer asks for one.

Bounds and refusals

A question with a number that cannot be a filter is refused, not answered without that filter, because answering without it would answer a wider question than the one asked. The chain returns no result and an invalid-input error (errs.IsInvalid) that names the phrase and the bound it broke. These are refused:

  • "last N hours" or "last N days" with N below 1 (a negative N included), or N so large that the span does not fit a time.Duration (about 292 years).
  • "within R of lat,lon" with a latitude outside [-90, 90], a longitude outside [-180, 180], or a radius that is not a finite number.

Every such phrase in the question is checked, and the refusal happens whichever tiers are composed and before any tier is asked. KeywordClassifier.ClassifyQuery has no error to return, so on its own it gives no hint for such a phrase and keeps the others.

With the keyword tier composed, a question with an entity reference and a zone or area phrase naming another place is refused too, before any tier is asked, with or without path words: "what is connected to sensor-001 in zone-b" and "show sensor-001 in zone-b" get an invalid-input error saying the question names two places, sensor-001 and zone-b; ask about one. Two zone or area phrases naming different places are refused the same way, whether a name is written with a hyphen or a space: "what is connected to zone a in zone b" names zone-a and zone-b. One place written twice ("zone a, zone-a", case aside) is one place. The keyword tier reads one path start, so it would answer a path from one place and drop the other. A phrase that only looks like a zone ("in the zone of the plant" reads zone-of) is refused the same way when the question also names an entity or another zone. A full entity ID is an entity reference whether or not a segment has a hyphen: "what is connected to c360.test.x.y.z.001 in zone b" names c360.test.x.y.z.001 and zone-b. An entity reference inside the zone phrase ("zone-b" itself, "sensor-zone-1") is the same place. These refusals are loud and can be wrong: an ordinary hyphenated word ("in real-time", "non-zero") or "zone or area" plus a word ("the area with pumps") beside a place is refused as a second place, a known limit. KeywordClassifier.ClassifyQuery on its own still answers a path from one of them. Two entity references with no zone phrase ("from pump-1 to pump-2") are not refused; the keyword tier reads the first.

Not refused, because it is geometry: a box that reaches a pole is clamped to 90 or -90 and spans longitude -180 to 180. A box across the 180 degree line is not wrapped: its East can exceed 180 or its West fall below -180, and the reader must handle that.

What the keyword tier leaves out

An operation is one of seven things a question can ask for: count, average, sum, minimum, maximum, similarity and ranking. A clause is the text between ;, ,, ., :, ? or ! (each followed by a space or the end of the question) or the word "but". The keyword tier excludes an operation, so that it gives no hint for it, when its trigger words are:

  • negated: they follow "not", "no", "never", "don't", "do not" or "without" in the same clause;
  • quoted: they lie inside a balanced pair of " or “ ”;
  • undecided: they are one of two different operations joined by "or" in one clause, where the second trigger comes right after "or", optionally after "the", "a" or "an" ("count sensors or the average pressure"). "Count sensors or pumps" joins nouns and excludes nothing.

Exclusion is per operation: "Do not count sensors; average pressure" gives average. Other hints stand: "Do not count sensors from yesterday" keeps its time range.

When the keyword tier excludes an operation and finds no other hint, the chain returns the default result and does not ask the LLM tier. The LLM tier answers in the caller's own words, which the framework cannot read, so it could bring back the operation the question refused. The cost is that a question whose only operation is excluded gets no tier 3 answer.

Limits

  • The LLM tier drops a strategy that is not one of the SearchStrategy values and a time range that does not parse as RFC 3339, and keeps the rest of the response.
  • The exclusion rule is made of word rules. "Not only count but average" loses the count, because "not" comes before "count" in the same clause.
  • A comma ends a clause. In "count, average or sum", the "or" joins average and sum, so they are excluded and count stands.
  • Quoted filter phrases are still read for numbers: Find documents containing "last 0 hours" is refused.
  • A radius of zero gives no box and no error.
  • "like" counts as similarity only as a whole word ("likely" and "liked" do not).
  • A zone or area phrase gives path_intent and path_start_node but no path_predicates.

Documentation

Overview

Package query classifies a natural-language question into search hints: the time range, area, path start, aggregation or ranking it asks for. It reads and stores no graph data.

A ClassifierChain asks its two tiers in order and answers from the first that produces a hint:

  • Tier 0, KeywordClassifier: regular expressions over the question. Always available.
  • Tier 3, LLMClassifier: asks a language model through an LLMClient the caller supplies, with optional few-shot examples from domain example files (LoadDomainExamples). Optional; this package holds no LLM client.

No code produces tiers 1 or 2; the numbers are the values callers read from ClassificationResult.Tier.

When no composed tier produces a hint, the chain answers the default result: tier 0, no hints, confidence 1.0. A nil or ended context gets no answer (nil), never the default result. ClassifierChain.ClassifyQuery documents each outcome, including a failed LLM tier.

A question holding an impossible number ("last 0 hours", a latitude of 95) is refused: ClassifierChain.ClassifyQuery returns no result and an invalid-input error naming the phrase, whichever tiers are composed. With the keyword tier composed, a question naming an entity reference and a zone or area phrase for another place ("sensor-001 in zone-b"), or two zone or area phrases for different places ("zone a in zone b"), is refused the same way, naming both places. "Today" and the other calendar ranges follow the server's zone (time.Local).

Hints travel as ClassificationResult.Options, a map keyed by the SearchOptions JSON names (time_range, path_intent, path_start_node, ...). Each result's map is the caller's own copy.

Index

Constants

View Source
const (
	AggregationCount = "count"
	AggregationAvg   = "avg"
	AggregationSum   = "sum"
	AggregationMin   = "min"
	AggregationMax   = "max"
)

Aggregation type constants for aggregation queries.

Variables

This section is empty.

Functions

This section is empty.

Types

type ClassificationResult

type ClassificationResult struct {
	Tier       int            // Which tier produced the result (0=keyword or default, 3=LLM)
	Intent     string         // Classified intent (from the LLM, empty for keyword)
	Options    map[string]any // SearchOptions hints (from keyword or LLM)
	Confidence float64        // Confidence score (1.0 for keywords and the default, 0.9 for the LLM)
}

ClassificationResult contains the classification output from the tiered classifier chain.

type Classifier

type Classifier interface {
	// ClassifyQuery analyzes a query string and returns SearchOptions.
	ClassifyQuery(ctx context.Context, query string) *SearchOptions
}

Classifier analyzes natural language queries to extract search intent.

type ClassifierChain

type ClassifierChain struct {
	// contains filtered or unexported fields
}

ClassifierChain orchestrates tiered query classification.

Routing logic:

  • T0 (keyword): Always try first - a keyword hint stops the ladder
  • An operation the keyword tier excluded, with no keyword hint: the default result
  • T3 (LLM): Only if no keyword hint AND one is composed
  • Default: T0 with no hints and confidence 1.0, while the context is live

Thread-safe for concurrent ClassifyQuery calls.

func NewClassifierChain

func NewClassifierChain(keyword *KeywordClassifier, llm *LLMClassifier) *ClassifierChain

NewClassifierChain creates a classifier chain with a keyword classifier and an LLM classifier. Tier numbers stay 0 and 3, the values callers read from ClassificationResult.Tier.

Either may be nil: a nil llm means no LLM tier, and the chain routes queries through the tiers it has. The LLM tier is one fixed parameter rather than a list, so a call written for a chain with a third tier, (keyword, nil, llm), fails to compile instead of dropping its LLM tier.

func (*ClassifierChain) ClassifyQuery

func (c *ClassifierChain) ClassifyQuery(ctx context.Context, query string) (*ClassificationResult, error)

ClassifyQuery classifies a query through the tier chain and returns the answer of the first tier that produces a hint:

  • T0: the keyword hints (temporal, spatial, similarity, path, zone, aggregation, ranking), confidence 1.0
  • T3: the LLM classifier's result, when it is composed and succeeds
  • Default: T0 with no hints and confidence 1.0

The keyword tier's outcome decides whether the LLM tier is asked:

Keyword outcome                    Chain result
any hint                           tier 0, those hints
no hint, nothing excluded          tier 3, then the default result
no hint, some operation excluded   the default result; tier 3 is not asked

An exclusion (a negated, quoted or undecided operation; KeywordClassifier.ClassifyQuery states the rules) binds the final decision whether or not an LLM tier is composed. The LLM tier answers in the caller's own words, which no framework rule can read, so the chain does not ask it. The cost: a question whose only operation is excluded gets no tier 3 answer.

A question with an out-of-range number is refused: no result and an invalid-input error (errs.IsInvalid) naming the phrase and the bound it broke. The bounds: "last N hours" and "last N days" need N of at least 1 and N hours or days within a time.Duration (about 292 years), so a negative N is refused; "within R of lat,lon" needs lat in [-90, 90], lon in [-180, 180] and R finite. The refusal holds whichever tiers are composed, the keyword tier included or not, and no tier is asked: answering without the phrase's filter would answer a wider question than the one asked. When the keyword tier is composed, a question with an entity reference and a zone or area phrase naming another place ("what is connected to sensor-001 in zone-b", "show sensor-001 in zone-b"), or two zone or area phrases naming different places ("zone a in zone b"), is refused the same way, naming both places: the keyword tier would answer a path from one of them. Every other outcome comes with a nil error.

The keyword tier reads the clock once per question; "today", "yesterday", "this week" and the other calendar ranges are in that instant's zone, the server's time.Local.

It returns nil and a nil error when the chain is nil, when ctx is nil or has ended before it starts, and when ctx has ended by the time the LLM tier has produced nothing: an ended context never gets the default result.

A failed LLM tier under a live context is a declared degrade to the default result: the chain answers as if no LLM were composed, and the error is not reported. A caller that must tell the two apart calls LLMClassifier.ClassifyQuery itself.

Each result's Options map is the caller's own; values nested inside an entry may be shared.

type DomainExamples

type DomainExamples struct {
	Domain   string    `json:"domain"`
	Version  string    `json:"version"`
	Examples []Example `json:"examples"`
}

DomainExamples represents a collection of examples for a domain.

func LoadDomainExamples

func LoadDomainExamples(filePath string) (*DomainExamples, error)

LoadDomainExamples loads query examples from a JSON file.

type Example

type Example struct {
	Query   string         `json:"query"`   // Natural language query
	Intent  string         `json:"intent"`  // Intent category
	Options map[string]any `json:"options"` // SearchOptions hints (optional)
}

Example represents a single domain query example for intent classification.

type KeywordClassifier

type KeywordClassifier struct{}

KeywordClassifier implements regex-based natural language query classification. Uses pattern matching to extract temporal, spatial, and intent information.

func NewKeywordClassifier

func NewKeywordClassifier() *KeywordClassifier

NewKeywordClassifier creates a new keyword-based classifier.

func (*KeywordClassifier) ClassifyQuery

func (k *KeywordClassifier) ClassifyQuery(_ context.Context, query string) *SearchOptions

ClassifyQuery analyzes a natural language query and populates SearchOptions. Detects temporal, spatial, similarity, path, and aggregation intents. Always returns non-nil SearchOptions with the original query preserved.

An excluded operation gives no hint and other hints stand. The seven operations are count, avg, sum, min, max, similarity and ranking, each excluded on its own when one of its triggers (a) follows not, no, never, don't, do not or without in the same clause, (b) lies inside a balanced pair of straight (") or curly (“ ”) double quotes, or (c) is one of two different operations joined by "or" in one clause. A clause is the text between ; , . : ? ! (each followed by a space or the end of the question) or the word "but". These are word rules: "not only count but average" reads count as negated.

Time ranges come from one reading of the clock per question, in that instant's zone (the server's time.Local): "today" is the server's calendar day. A phrase whose number is out of range gives no hint and other hints stand: "last N hours" or "last N days" with N below 1 (negative N included) or a span past a time.Duration (about 292 years), and "within R of lat,lon" with lat outside [-90, 90], lon outside [-180, 180] or R not finite. ClassifierChain.ClassifyQuery refuses such a question instead, and a question naming an entity reference or a second place beside a zone or area phrase, of which this answers a path from one. A box is clamped to the poles, spans every longitude when it reaches one, and is not wrapped across the antimeridian (East can exceed 180, West fall below -180).

type LLMClassifier

type LLMClassifier struct {
	// contains filtered or unexported fields
}

LLMClassifier classifies queries by asking an LLM to return structured SearchOptions.

It is the T3 tier in the ClassifierChain — called only when the T0 (keyword) tier produces no hint and excludes no operation. When the LLM call fails or returns unparseable JSON, LLMClassifier returns an error so the chain can fall back gracefully rather than silently returning a wrong classification.

func NewLLMClassifier

func NewLLMClassifier(client LLMClient, domains []*DomainExamples) *LLMClassifier

NewLLMClassifier creates an LLMClassifier with an LLM backend and optional domain examples.

domains may be nil or empty; when provided, a few representative examples are included in the prompt as few-shot context to improve classification accuracy.

It keeps the domains' examples and their Options maps; do not edit them after the call.

func (*LLMClassifier) ClassifyQuery

func (c *LLMClassifier) ClassifyQuery(ctx context.Context, query string) (*ClassificationResult, error)

ClassifyQuery classifies a natural language query using an LLM and returns a ClassificationResult at Tier 3.

A strategy that is not one of the SearchStrategy values and a time range that does not parse as RFC 3339 are dropped from the result without an error; the rest of the response is kept.

Returns an error if:

  • ctx is nil (an invalid-input error, before the client is called)
  • The LLM call fails (network, auth, quota)
  • The LLM response is not valid JSON
  • Context is cancelled before the call completes

type LLMClient

type LLMClient interface {
	// ClassifyQuery sends a structured classification prompt to the LLM and returns
	// the raw JSON response string.
	ClassifyQuery(ctx context.Context, prompt string) (string, error)
}

LLMClient is the minimal interface for sending a classification prompt to an LLM backend.

The returned string must be valid JSON matching llmResponse. Implementations are responsible for retries, timeouts, and backend-specific authentication.

type SearchOptions

type SearchOptions struct {
	Query          string         `json:"query,omitempty"`
	GeoBounds      *SpatialBounds `json:"geo_bounds,omitempty"`
	TimeRange      *TimeRange     `json:"time_range,omitempty"`
	Predicates     []string       `json:"predicates,omitempty"`
	Types          []string       `json:"types,omitempty"`
	KeyTerms       []string       `json:"key_terms,omitempty"`
	UseEmbeddings  bool           `json:"use_embeddings,omitempty"`
	Strategy       SearchStrategy `json:"strategy,omitempty"`
	Limit          int            `json:"limit,omitempty"`
	PathIntent     bool           `json:"path_intent,omitempty"`
	PathStartNode  string         `json:"path_start_node,omitempty"`
	PathPredicates []string       `json:"path_predicates,omitempty"`
	// AggregationType specifies the type of aggregation (count, avg, sum, min, max).
	// Use the AggregationCount / AggregationAvg / … constants.
	AggregationType string `json:"aggregation_type,omitempty"`
	// AggregationField is the property or attribute to aggregate on (e.g. "temperature").
	// Empty means aggregate over entity count.
	AggregationField string `json:"aggregation_field,omitempty"`
	// RankingIntent is true when the query requests a ranked/top-N result set.
	RankingIntent bool `json:"ranking_intent,omitempty"`
}

SearchOptions provides declarative search configuration.

type SearchStrategy

type SearchStrategy string

SearchStrategy represents the type of search to perform.

const (
	StrategyGraphRAG         SearchStrategy = "graphrag"
	StrategyGeoGraphRAG      SearchStrategy = "geo_graphrag"
	StrategyTemporalGraphRAG SearchStrategy = "temporal_graphrag"
	StrategyHybridGraphRAG   SearchStrategy = "hybrid_graphrag"
	StrategyPathRAG          SearchStrategy = "pathrag"
	StrategySemantic         SearchStrategy = "semantic"
	StrategyExact            SearchStrategy = "exact"
	StrategyAggregation      SearchStrategy = "aggregation"
)

Search strategy constants for query routing.

type SpatialBounds

type SpatialBounds struct {
	North float64 `json:"north"`
	South float64 `json:"south"`
	East  float64 `json:"east"`
	West  float64 `json:"west"`
}

SpatialBounds represents geographic bounding box.

type TimeRange

type TimeRange struct {
	Start time.Time `json:"start"`
	End   time.Time `json:"end"`
}

TimeRange represents temporal query bounds.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL