DeepCQDeep Context Query·Ternary Capital Research

Remember everything.
Read only what matters.

ICTIR 2026Paper accepted →

DeepCQ is a context layer for long-horizon AI agents. Before every model call it scores the agent’s memory against the question and passes on only the sections that matter, along with a record of why.

$ pip install deepcq
Figure 1. DeepCQ, running in your browser live  ·  the 0.3.0 algorithm in JavaScript, matching the Python package on 1,506 test queries
try
Agent memory · 5 tiersscore
    threshold 0.30T2/T3 are free text: included whole when any query term appears
    Context sent to the model
    Fallback. No section reached the 0.30 threshold, so DeepCQ sends the full memory rather than silently dropping context. In production, log and count these.
    —
    Memory: a research agent following Novatek Semiconductor, a fictional company. Figures are illustrative. Memory · Port · Parity test

    Fig. 1. Each memory section is scored by the share of query terms it contains, after stopwords are removed and words are stemmed. Sections at or above the dashed threshold are sent; the rest stay in memory. Exact numbers, quoted phrases and identifiers count as literal anchors. Ask “give me the big picture” to see the fallback.

    57.6%
    Fewer input tokens
    Mean per call; 40–70% depending on query type.
    +0.6
    Answer relevance
    3.9 → 4.5 on a 5-point human rating. Correctness held.
    0.8%
    False negatives
    Queries where needed context was wrongly left out.
    <1%
    Duplicate tool calls
    Down from 18%: the session tier stops agents re-fetching data.

    From 1,000 production queries of a multi-turn investment-research agent, against a full-context baseline; quality rated by three annotators on 100 stratified queries (Fleiss’ κ = 0.74). ICTIR 2026. Your reduction depends on how your memory is structured and what users ask.

    § 01Problem

    Agents drown in their own context.

    A long-running agent builds up live state, tool results, conversation history, notes and reference data. The usual pipeline resends all of it on every call. In our deployment one research turn carried 40,000–50,000 tokens, most of them irrelevant to the question.

    1. Cost grows with history, not with the question.

      Every turn pays to resend the whole memory. At 43,000 tokens per call, 100k calls a month and $3 per million input tokens, that’s about $155k a year in input tokens alone.

    2. Attention gets diluted.

      Models recall less from the middle of long contexts1, and irrelevant input measurably lowers reasoning accuracy2. More context can produce worse answers.

    3. Memory has no structure.

      Short-lived state, durable notes and static reference data end up in one blob with no rule for what to keep, refresh or drop. Agents then fetch data they already have: 18% of tool calls were duplicates in our baseline3.

    § 02Method

    Score, threshold, extract.

    DeepCQ runs just before prompt assembly. There is no model in the loop: relevance is computed from the query’s own terms, so the same question over the same memory always yields the same context.

    01

    Structure

    Declare the named sections your agent works with and write them to five tiers, each with its own lifetime and update rule.

    MemorySchema(sections=[…])
    02

    Score

    Lowercase the query, drop stopwords, add stems, then measure how many of those terms each section covers in its name, keywords and stored text.

    “exposed” → exposed, expos
    03

    Extract

    Sections at or above the threshold are cut out verbatim with a boundary regex and returned with their scores, matched terms and the size reduction.

    QueryResult(content, intent, …)
    score(s, q) = | T(q) ∩ V(s) || T(q) | ≥ τ

    A section is sent when it covers at least a fraction τ of the query’s terms. Default τ = 0.30.

    T(q)
    Query terms: words minus stopwords, plus their stems.
    V(s)
    Section vocabulary: its name, optional keywords, and the text stored under its header in every tier.
    anchor
    A number, quoted phrase or identifier found verbatim in s sets its score to 1.
    fallback
    If no section reaches τ, the full memory is returned, never an empty prompt.

    Five tiers, five lifetimes

    How long each tier’s content lives. One query reads all five.

    T1AppStateLive application state
    rebuilt every turn
    T2SessionCacheTool results, scratch data
    per session · deduped, LRU-bounded
    T3HistoryRecent conversation
    sliding window of N turns
    T4LongTermStoreNotes, theses, findings
    append-only · persisted to JSON · keeps full provenance
    T5ReferenceDataStatic configuration and domain data
    persistent · loaded lazily, only when needed

    Deterministic

    Same query, same memory, same context. Results can be reviewed, unit-tested and kept under version control.

    Explainable

    Every result lists included and excluded sections, each score and the exact terms that matched.

    Fails open

    When nothing matches, the full context is sent and the result says so, so fallbacks can be logged and counted.

    No embedding stack

    Pure Python, zero dependencies. Use it alongside RAG: retrieve documents there, decide what reaches the prompt here.

    § 03Results

    Less context, better answers.

    Filtering is not only a cost lever. With irrelevant sections removed, human raters scored answers as more relevant, and correctness and completeness held steady or improved.

    Figure 2. Answer quality
    Human rating, 1–5 · n = 100
    Relevance
    +0.6
    Correctness
    +0.1
    Completeness
    +0.1
    Full-context baselineDeepCQ
    Figure 3. Input tokens per call, by query type
    1,000 production queries · mean 43,000 → 18,220
    Full contextDeepCQ
      View as table
      Query typeFull contextDeepCQReductionΔ quality
      § 04Benchmarks

      Context-selection latency.

      Lower is better. The time to decide what goes into the prompt, per request, over a 44,000-token agent memory. The LLM call itself is not included.

      Figure 4. Per-request selection latency, p50 with p95
      Memory
      Scale
        p50 (median)p50 to p95
        View as table
        MethodScenariop50p95Mean

        Setup. DeepCQ 0.3.0, rank_bm25 and all-MiniLM-L6-v2 on CPU (top-8 chunks), on an AMD Ryzen 5 5600X. Memory has 7 sections and 432 paragraph chunks, about 44k tokens, sized like the paper’s stock context. Changes every turn means live state is rewritten before each query: DeepCQ runs uncached, BM25 rebuilds its index, and dense retrieval re-embeds the live chunks. Unchanged lets every method reuse its cache or index. 400 runs per cell (20 for dense re-embedding). Reproduce with context_selection_latency.py · raw results.

        § 05Research

        Published work.

        DeepCQ comes out of Ternary Capital Research’s work on long-horizon investment-research agents. The papers describe the architecture, the production evaluation and its limitations.

        ICTIR 2026
        Accepted paper
        April 2026 · 7 pp.

        DeepCQ: A Hierarchical Memory and Intent-Aware Context Optimisation Architecture for Multi-Turn Investment Research Agents

        Ternary Capital Research

        We present DeepCQ, an agentic information retrieval system that addresses the tension between comprehensive context and effective attention allocation. It combines a five-tier hierarchical memory architecture with intent-aware, RegEx-driven context filtering. Evaluated on 1,000 real research queries, it reduces input tokens by 40–70% (mean 57.6%) and improves relevance by +0.6 on a 5-point scale, suggesting that structural, rule-based filtering remains competitive with, and complementary to, learned approaches for well-defined domain schemas.

        PDF Code ↗
        @inproceedings{deepcq2026ictir,
          title     = {DeepCQ: A Hierarchical Memory and Intent-Aware Context
                       Optimisation Architecture for Multi-Turn Investment
                       Research Agents},
          author    = {{Ternary Capital Research}},
          booktitle = {Proceedings of the 2026 ACM SIGIR International
                       Conference on the Theory of Information Retrieval (ICTIR)},
          year      = {2026}
        }
        Tech report
        March 2026 · 6 pp.

        Intent-Based Context Filter: Analyzing Query Intent to Reduce LLM Agent Token Consumption

        Ternary Capital Research

        A two-stage pipeline that classifies the information demand of a query along twelve intent dimensions, then extracts only the relevant sections from each memory tier, with no secondary model calls and correctness and completeness left intact.

        PDF
        @techreport{deepcq2026icf,
          title       = {Intent-Based Context Filter: Analyzing Query Intent
                         to Reduce LLM Agent Token Consumption},
          author      = {{Ternary Capital Research}},
          institution = {Ternary Capital Research},
          year        = {2026},
          month       = mar
        }
        § 06Use it

        Running in under a minute.

        • One pip install. No services, no API keys, no dependencies.
        • Works in front of any model: it returns plain text for your prompt.
        • Examples for the OpenAI Agents SDK, Claude Agent SDK, Qwen and Google A2A.
        quickstart.py
        from deepcq import DeepCQ, MemorySchema
        
        cq = DeepCQ(schema=MemorySchema(sections=["status", "errors", "metrics"]))
        
        cq.state.set("errors",  "[errors]\n- OOM at 02:15\n")
        cq.state.set("metrics", "[metrics]\nCPU: 78%\nMemory: 4.2GB\n")
        cq.state.set("status",  "[status]\nAll services running\n")
        
        result = cq.query("any memory or cpu spikes?")
        print(result.content)
        print(result.sections_included, result.metrics.reduction_pct)
        [metrics] CPU: 78% Memory: 4.2GB ['metrics'] 64.0