intent

package
v0.25.0 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: MIT Imports: 10 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package intent implements Stage 1 of the /ask pipeline: classifying a user's natural-language question into a Kind that Stage 2 uses to shape document retrieval (entity-weighted search, recency sort, exact-token matching, or a plain general search).

Classification never fails fatally: LLMClassifier.Classify always degrades to KindGeneral on any LLM error or malformed response so the /ask pipeline can proceed with a best-effort search rather than aborting the whole request over a classification hiccup.

Index

Constants

View Source
const (
	// OriginDeterministic: a regex matched and no LLM call was made.
	OriginDeterministic = "deterministic"
	// OriginLLM: the model produced a schema-valid plan.
	OriginLLM = "llm"
	// OriginFallback: planning failed and the plan is unconstrained. This is
	// the pre-planner behaviour, not a new failure mode (spec §6.1).
	OriginFallback = "fallback"
)

Origin values for QueryPlan.Origin.

Variables

This section is empty.

Functions

func DeterministicWindow

func DeterministicWindow(question string, now time.Time) (from, to time.Time, label string, ok bool)

DeterministicWindow runs the same regex pre-pass deterministicPlan uses to resolve one of the Korean date/period phrasings this file recognises (the original nine of spec §4.1, plus the past/relative expressions added later: 지난주/저번주, 이번달, 다음달, 지난 주말/저번 주말, 그제/그저께, N일·N주·N달 전, 지난·최근 N일/N주, 올해/작년, and 이번주/지난주/다음주 X요일) to a half-open [from, to) window, evaluated relative to the given base time rather than time.Now(). now should already be normalised to timeutil.KST() by the caller, exactly as Plan does before calling deterministicPlan — the range helpers (monthRange/weekRange/dayRange) all re-normalise internally, but the regexes' own reading of "this month" / "this week" depends on which calendar day now names, so an un-normalised UTC instant can still misclassify one.

Exported so callers outside an LLMPlanner instance can reuse the exact phrase list deterministicPlan is held to, instead of maintaining a second list that could drift. Currently used by the golden-set candidate handler (internal/api/golden.go), which resolves a period phrase like "오늘" relative to REVIEW TIME — the moment a human is actually looking at the candidate list (s.nowFunc()) — not relative to whenever the query text was originally asked or generated.

ok is false when no phrase in the pre-pass list matched — callers should then treat the query as carrying no time constraint, exactly like the LLM path's fallback plan does. label is the matched Korean phrase ("지난달", "오늘", ...), useful for a Reason-style rendering; callers that don't need it can discard it.

Types

type Classifier

type Classifier interface {
	Classify(ctx context.Context, question string) (Params, error)
}

Classifier classifies a raw user question into Params. The error return exists for interface generality (future implementations, tests); the only shipped implementation, LLMClassifier, never returns a non-nil error — see LLMClassifier.Classify.

type Kind

type Kind string

Kind describes how Stage 2 should shape the retrieval query for a classified question.

const (
	// KindGeneral is the default/fallback classification: no special
	// retrieval shaping is applied.
	KindGeneral Kind = "general"
	// KindEntity indicates the question centers on a named entity
	// (person, place, org); Stage 2 boosts the entity RRF lane.
	KindEntity Kind = "entity"
	// KindTemporal indicates the question references a specific time
	// window; Stage 2 approximates this via recency sort only — there is
	// no date-range filter on model.SearchQuery yet.
	KindTemporal Kind = "temporal"
	// KindExactToken indicates the question contains a phone-number-shaped
	// token; Stage 2 nudges the bigram-similarity lane.
	KindExactToken Kind = "exact_token"
)

type LLMClassifier

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

LLMClassifier runs a deterministic regex pre-pass first (phone numbers, Korean date phrases); anything that doesn't match falls back to a single LLM call that distinguishes "general" from "entity" questions.

func NewLLMClassifier

func NewLLMClassifier(c llm.Completer) *LLMClassifier

NewLLMClassifier returns an LLMClassifier backed by c for the LLM fallback path.

func (*LLMClassifier) Classify

func (c *LLMClassifier) Classify(ctx context.Context, question string) (Params, error)

Classify runs the deterministic pre-pass first, falling back to an LLM call when nothing matches. It never returns a non-nil error: every failure path (LLM error, malformed response) degrades to KindGeneral.

func (*LLMClassifier) WithNow

func (c *LLMClassifier) WithNow(now func() time.Time) *LLMClassifier

WithNow injects a deterministic clock into c, mirroring the unexported now field's existing "nil means time.Now" convention (see c.nowFunc). Exported so a caller OUTSIDE this package (internal/api's WithClock builder, internal/askeval's offline runner) can pin "today" without reaching into an unexported field from a different package — the existing _test.go convention of `c.now = ...` only works for same-package tests. Returns c so it composes with the existing constructor chain (NewLLMClassifier(...).WithNow(...)).

주의: WithNow는 고루틴 안전하지 않다(잠금 없이 c.now를 대입) — 서버가 요청 처리를 시작하기 전(eval/test 초기화 시점)에만 호출할 것.

type LLMPlanner

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

LLMPlanner implements Planner with a deterministic regex pre-pass plus a single LLM call for everything the pre-pass misses.

The regexes are a CACHE for common phrasings, not a second set of semantics. That distinction is the whole architecture: the original defect was that "오늘" produced a date window and "내일" — absent from the regex list — produced no window at all, so a missing vocabulary entry silently became "search everything, ranked by meaning", and a three-month-old call transcript outranked tomorrow's calendar entry. Because both paths now return a QueryPlan, a regex miss costs one LLM round-trip instead of deleting the filter.

REQUIRED DEPLOYMENT CONDITION — LLM_THINKING=disabled (spec §4.2). The remote model bills reasoning_content against the same max_tokens budget as the visible answer. With reasoning enabled, the ~750-token budget this prompt is sized for is consumed before a single content byte is emitted and the client returns *llm.TruncatedError (finish_reason="length", content length 0). This planner treats that as a failure and falls back — correctly, but on EVERY call, which turns the feature off while leaving no user-visible error at all. Raising max_tokens instead costs ~17x the tokens (measured; see internal/llm's thinking documentation).

func NewLLMPlanner

func NewLLMPlanner(c llm.Completer, defaultLimit int) *LLMPlanner

NewLLMPlanner returns a planner backed by c, stamping every plan with defaultLimit. c may be nil or disabled: planning then always falls back.

func (*LLMPlanner) Plan

func (p *LLMPlanner) Plan(ctx context.Context, question string) QueryPlan

Plan implements Planner. It runs the deterministic pre-pass, then the LLM path, and absorbs every failure into an unconstrained fallback plan.

func (*LLMPlanner) WithNow

func (p *LLMPlanner) WithNow(now func() time.Time) *LLMPlanner

WithNow injects a deterministic clock into p, the Planner counterpart of LLMClassifier.WithNow above — see that method's doc comment for why this exists as an exported builder rather than direct field access.

주의: WithNow는 고루틴 안전하지 않다(잠금 없이 p.now를 대입) — 서버가 요청 처리를 시작하기 전(eval/test 초기화 시점)에만 호출할 것.

type Params

type Params struct {
	RawQuery     string
	Kind         Kind
	EntityName   string
	OccurredFrom *time.Time
	OccurredTo   *time.Time
	Confidence   float64
}

Params is the result of Stage 1 classification.

type Planner

type Planner interface {
	Plan(ctx context.Context, question string) QueryPlan
}

Planner turns one question into exactly one QueryPlan.

There is no error return, by design: every failure inside a planner is absorbed into an unconstrained fallback plan (spec §6), because a /ask request that cannot be planned is still answerable — just not narrowed. Callers that need to know planning failed read Origin.

type QueryPlan

type QueryPlan struct {
	// OccurredFrom / OccurredTo are the half-open event-time window
	// [From, To) on documents.occurred_at. Both nil means no time constraint.
	// The half-open convention is the same one dayRange/weekRange/monthRange
	// return and the same one internal/store binds to
	// `occurred_at >= $from AND occurred_at < $to`; an inclusive upper bound
	// would drop the period's final second and leave gaps between consecutive
	// windows.
	OccurredFrom *time.Time
	OccurredTo   *time.Time

	// SourceTypes is the include set. Empty means "all sources", NOT "no
	// sources". It never contains model.SourceInsight — see stripInsight.
	SourceTypes []model.SourceType

	// Limit is the candidate cap for the observed lane.
	Limit int

	// Reason is a one-line, user-facing rationale ("내일(8/20) 캘린더만 조회").
	//
	// PRIVACY (design spec §9): on the LLM path this string is written by the
	// model from the user's question and can therefore contain names, phone
	// numbers, or any other personal detail the question carried. It is
	// returned to the asking user and to nobody else: never log it, never use
	// it as a metric label, never put it in an error. Log len(Reason) if you
	// need a signal at all (same rule as llm.TruncatedError, issue #194).
	Reason string

	// Origin is OriginDeterministic, OriginLLM, or OriginFallback. It exists
	// so a wrong plan can be diagnosed at all: a fallback spike means the LLM
	// path is down, an "llm" plan with an empty window means the prompt is
	// wrong, and a "deterministic" plan with a wrong window means the regex or
	// the timezone is wrong. Those are three different repairs and without
	// this field they look identical from the outside.
	Origin string
}

QueryPlan is the answer to "what must be fetched to answer this question". Both the deterministic path and the LLM path produce this one type — see LLMPlanner's doc comment for why that matters more than which path ran.

The zero value is a valid unconstrained plan except for Limit, which callers must treat as "use your own default" when zero (assembleRetrieval does).

Jump to

Keyboard shortcuts

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