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 ¶
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.