Getting started

Install DeepCQ, structure your agent’s memory, and send your model only the context the current question needs. Every code sample on this page has been run against the published package.

10-minute read Python 3.10+ Zero dependencies

01Install

DeepCQ is pure Python with no runtime dependencies. Install the stable release from PyPI:

shell
pip install deepcq

This guide covers DeepCQ 0.3.0, the current release. Check your installed version with pip show deepcq, and see the changelog for what changed between versions.

02Quickstart

Declare the sections your agent knows about, store some memory, and ask a question. DeepCQ returns only the section the question is about.

quickstart.py
from deepcq import DeepCQ, MemorySchema

schema = MemorySchema(sections=["status", "errors", "metrics"])
cq = DeepCQ(schema=schema)

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)
print(f"{result.metrics.reduction_pct:.1f}% smaller")
[metrics] CPU: 78% Memory: 4.2GB ['metrics'] 64.0% smaller

The query mentions memory and cpu, both of which appear in the metrics section. The errors and status sections share no terms with the query, so they stay out of the prompt.

03Core concepts

Sections and the schema

A MemorySchema lists the named sections your agent works with. In stored text each section starts with a header, [name] by default, and runs until the next header. DeepCQ doesn’t need to know what a section means. It works out relevance from the words in each query.

Scoring

The query is lowercased, stopwords are removed, and each remaining word is paired with a stem (spikes → spike). A section’s score is the fraction of unique query terms found in its name, its optional keywords, or the text currently stored under it. Sections that score at or above confidence_threshold (default 0.3) are included.

Tiers

Memory lives in five tiers, each with its own lifetime. The section-based tiers (state, notes, reference) are extracted section by section. The free-text tiers (session cache and history) are included only when their text matches a query term.

AttributeClassLifetimeWrite with
cq.stateAppState · T1Live; overwrite each turnset(section, text)
cq.cacheSessionCache · T2Per session, deduped, LRU-boundedput(key, value)
cq.historyHistory · T3Sliding window of recent turnsadd(role, text)
cq.notesLongTermStore · T4Persistent, append-only, JSON-backedappend(key, text)
cq.referenceReferenceData · T5Persistent, loaded lazilyset(key, value)

04Fill the five tiers

A more realistic agent spreads its memory across tiers. Pass store_path to keep long-term notes on disk between runs, and add keywords where a section name alone doesn’t cover the words users actually type.

research_agent.py
from deepcq import DeepCQ, MemorySchema

schema = MemorySchema(
    sections=["fundamentals", "news", "risk"],
    keywords={"fundamentals": ["earnings", "revenue", "eps"]},
)
cq = DeepCQ(schema=schema, store_path="memory/notes.json")

# T1: live state, refreshed every turn
cq.state.set("fundamentals", "[fundamentals]\nQ4 revenue $124B, EPS $2.40, gross margin 46%")
cq.state.set("news", "[news]\nNew export controls announced on advanced chips")

# T4: durable, append-only findings
cq.notes.append("risk", "[risk]\nTwo holdings exposed to chip export rules")

# T3: conversation so far
cq.history.add("user", "Pull the latest 10-Q for AAPL.")

for q in ["what were Q4 earnings?", "which holdings carry export risk?"]:
    r = cq.query(q)
    print(r.sections_included, f"{r.metrics.reduction_pct:.0f}% smaller")
['fundamentals'] 72% smaller ['risk'] 78% smaller

The second query is answered from the long-term notes tier (T4), not from live state. One call to query() reads all five tiers.

05Read the result

query() returns a QueryResult. Put content in your prompt. Use the other fields for logging, evaluation and debugging.

FieldWhat it tells you
contentThe filtered context to send to the model.
intentScore per section, from 0.0 to 1.0.
sections_includedSections that cleared the threshold.
sections_excludedSections that were left out.
metricsoriginal_chars, filtered_chars, reduction_pct.
explanationsPer section: matched tokens, literal anchors, matched phrases and tier contributions.
content_patternThe regex used to filter the free-text tiers.

Fallback is on by default. If no section reaches the threshold, query() returns the full memory so a vague question never silently loses context. In that case every section appears in sections_included, so check the scores to tell a fallback apart from a real match (see below). Set fallback_include_all=False on the schema to get an empty result instead.

06Add it to your agent

Call DeepCQ right before you build the prompt, and record each turn afterwards. The pattern is the same for any model provider. This example also logs and counts fallbacks, so you can see how often your queries match nothing.

agent.py
import logging
from collections import Counter
from deepcq import DeepCQ, MemorySchema

log = logging.getLogger("agent.context")
schema = MemorySchema(sections=["fundamentals", "news", "risk"])
cq = DeepCQ(schema=schema, store_path="memory/notes.json")
stats = Counter()

def build_context(question: str) -> str:
    result = cq.query(question)
    if max(result.intent.values(), default=0.0) < schema.confidence_threshold:
        stats["fallback"] += 1
        log.warning("deepcq fallback: nothing matched %r, sending full memory", question)
    else:
        stats["filtered"] += 1
        log.info("deepcq kept %s, dropped %s (%.0f%% smaller)",
                 result.sections_included, result.sections_excluded,
                 result.metrics.reduction_pct)
    return result.content

def answer(question: str) -> str:
    context = build_context(question)
    reply = call_llm(                       # your model client
        system=f"<memory>\n{context}\n</memory>",
        user=question,
    )
    cq.history.add("user", question)
    cq.history.add("assistant", reply)
    return reply

Ready-to-adapt versions for the OpenAI Agents SDK, Claude Agent SDK, Qwen and Google A2A are in the repository’s examples/ folder. If you use LangChain, deepcq.integrations.ternary.LangChainMemoryAdapter can be passed directly as a chain’s memory=.

07Tune relevance

Start with the schema

Most tuning is done in the schema. Add keywords for jargon section names, change the header format to match how your memory is already written, and adjust the threshold.

schema.py
schema = MemorySchema(
    sections=["db", "api"],
    keywords={"db": ["database", "postgres", "migration"]},
    section_header_format="## {name}",   # Markdown headers instead of [name]
    confidence_threshold=0.25,
)

Opt-in matching

These options are off by default. Synonym packs let “eps” match stored “earnings per share”. Phrase matching rewards adjacent terms such as “moving average”. tier_weights makes matches in stale tiers count for less.

tuning.py
from deepcq import MemorySchema, SynonymMap, load_pack

vocab = load_pack("finance") | SynonymMap.from_dict({"arr": ["annual recurring revenue"]})
schema = MemorySchema(
    sections=["fundamentals", "news"],
    vocabulary=vocab,
    phrase_sizes=(2,),
    tier_weights={"history": 0.5},
)

Calibrate the threshold from labels

Rather than guessing a threshold, label a handful of real queries with the sections they need and sweep. The report shows precision, recall and F1 for each threshold.

calibrate.py
from deepcq import DeepCQ, calibrate, LabeledExample

def build():                      # one populated DeepCQ per case
    cq = DeepCQ(schema)
    cq.state.set("fundamentals", "[fundamentals]\nEarnings per share rose to $2.40")
    cq.state.set("news", "[news]\nNew export controls announced")
    return cq

report = calibrate([
    LabeledExample(build, "what was eps?", {"fundamentals"}),
    LabeledExample(build, "latest export news", {"news"}),
])
print(report.summary())
schema.confidence_threshold = report.best.threshold

Phrase boosts raise scores, so recalibrate after turning them on. Pass min_precision= to calibrate() to get the highest-recall threshold that meets a precision target.

08Search plain documents

For “which part of this text answers the question?”, with no schema or tiers, use locate(). It splits text on blank lines, scores each chunk, and returns matching chunks unmodified and in their original order, so they’re safe to quote verbatim.

locate.py
from deepcq import locate

doc = (
    "The authentication service validates tokens on every request.\n\n"
    "Rate limiting is enforced per API key using a sliding window counter.\n\n"
    "The database migration tool applies schema changes in order."
)

for c in locate(doc, "how does rate limiting work?"):
    print(c.index, c.score, c.text)
1 0.75 Rate limiting is enforced per API key using a sliding window counter.

Use chunk_on= to change the delimiter and max_candidates= to keep only the top-scoring chunks.

09Next steps