Skip to content

🧠 Query Expansion (Pre-Search) #216

Closed

Description

@hurttlocker

Summary

Add LLM-powered query expansion before search. When a user searches "what was that trading thing we decided?", a fast LLM expands it into 3-5 precise queries, runs all of them, and merges results via RRF.

Priority: HIGHEST IMPACT — biggest bang, easiest to implement, nearly free.

Spec

New Package: internal/llm/

Create a provider-agnostic LLM adapter:

type Provider interface {
    Complete(ctx context.Context, prompt string, opts CompletionOpts) (string, error)
    Name() string
}

type CompletionOpts struct {
    MaxTokens   int
    Temperature float64
    Model       string
    Format      string // "json" for structured output
}

Providers to implement:

  • openai.go — OpenAI API (GPT-5.1 Codex Mini)
  • google.go — Google AI (Gemini 3 Flash)
  • config.go — reads provider/model/key from env vars or ~/.cortex/config.yaml

Query Expansion: internal/search/expand.go

func ExpandQuery(ctx context.Context, llm llm.Provider, query string) ([]string, error)
  • Takes a natural language query
  • Returns 3-5 precise search queries
  • Prompt template: stored in internal/search/prompts/expand.txt
  • Timeout: 2 seconds max (fall back to original query on timeout)
  • Caching: LRU cache of recent expansions (avoid re-expanding identical queries)

CLI Integration

cortex search "what was that trading thing" --expand          # uses default LLM
cortex search "what was that trading thing" --expand --llm google/gemini-3-flash
cortex search "what was that trading thing" --expand --llm openai/gpt-5.1-codex-mini
cortex search "what was that trading thing"                   # no expansion (unchanged behavior)

MCP Integration

Add expand parameter to existing search_memory MCP tool.

Files to Create/Modify

  • internal/llm/provider.go — interface + factory
  • internal/llm/openai.go — OpenAI provider
  • internal/llm/google.go — Google AI provider
  • internal/llm/config.go — configuration loading
  • internal/llm/llm_test.go — unit tests (mock provider)
  • internal/search/expand.go — query expansion logic
  • internal/search/expand_test.go — expansion tests
  • internal/search/prompts/expand.txt — prompt template
  • cmd/cortex/main.go — add --expand and --llm flags to search command
  • internal/mcp/server.go — add expand param to search tool

Benchmark Test Spec

Test Corpus

Use 10 real-world vague queries from actual Cortex usage:

  1. "what was that trading thing we decided"
  2. "SB health stuff"
  3. "when did we lock the config"
  4. "that spear customer issue"
  5. "what model does hawk use"
  6. "the eBay jewelry numbers"
  7. "something about PDT and accounts"
  8. "youtube pipeline changes"
  9. "agent architecture decisions"
  10. "cortex release notes"

Metrics to Capture (per query, per model)

Metric Target
Latency (expansion only) <500ms
Tokens in <100
Tokens out <200
Cost per query <$0.001
Expansion quality (0-5 rubric) ≥3.5 avg
Search result relevance (NDCG@5 vs no expansion) >1.2x improvement

Quality Rubric (0-5)

  • 5: All expansions directly relevant, captures intent perfectly
  • 4: Most expansions relevant, one might be tangential
  • 3: Decent expansion, captures main intent but misses nuance
  • 2: Some relevant, some noise
  • 1: Mostly irrelevant expansions
  • 0: Completely missed the intent

Benchmark Script

Create scripts/benchmark_expand.go:

  • Runs all 10 queries against both models
  • Records latency, token counts, cost
  • Human rates quality (interactive mode) or uses pre-scored rubric
  • Outputs comparison table as markdown

Acceptance Criteria

  • internal/llm/ package with OpenAI + Google providers
  • --expand flag on cortex search works with both models
  • Fallback to original query on LLM timeout/error
  • LRU cache prevents duplicate expansions
  • Benchmark results for both models documented in PR
  • All existing tests still pass
  • No LLM calls when --expand is not specified

Dependencies

None (first in sequence, creates the LLM adapter all others use).

Estimated Cost

~$0.001/query = $0.01/day at 10 queries/day = **$0.30/month**

Activity

  1. added
    search
    v0.9.0
    llm
    benchmark
    on Feb 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    benchmarkllmsearchv0.9.0

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions