본문으로 건너뛰기
cccskills
무료GitHub에 공개

cognee-improve-sessions

Store conversations, agent activity, and feedback in cognee sessions, then carry them into long-term memory. This skill explains improve(), its processing stages, result statuses, and settings for diagnosing skipped work or controlling automatic runs.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

원문원문 설명 보기

Use when working with cognee's session memory or improve() — storing conversation turns, agent traces and feedback with session_id, bridging sessions into the permanent graph, reading an ImproveResult, understanding why an improve stage was skipped, already_completed or lock_held, or tuning the IMPROVE_* settings.

설치 방법 보기

이럴 때 유용합니다

  • Saving conversations and agent activity by session
  • Moving session content into long-term memory
  • Investigating skipped or blocked processing stages
  • Adjusting when automatic improvement runs

포함된 파일(1)

  • SKILL.md13.9 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Session memory and improve()

cognee has two kinds of memory:

  • Session memory: a fast cache of conversation turns, agent traces, and feedback, keyed by session_id. Writing is instant, with no LLM extraction.
  • The permanent graph: what remember() builds without a session.

improve() connects them. It bridges session content into the graph and enriches the graph itself. remember() calls it automatically, so most users never call it directly.

import cognee

# Session write: returns immediately; improve() bridges it in the background
await cognee.remember("User prefers dark mode.", session_id="chat_1")

# Session-aware query: session cache first, then the graph
results = await cognee.recall("What does the user prefer?", session_id="chat_1")

# Bridge sessions into a dataset's graph explicitly
result = await cognee.improve(dataset="main_dataset", session_ids=["chat_1"])
print(result.status, result.stage_summary())

await cognee.wait_for_background_tasks()  # before a script exits

Use it

Writing session memory

WhatHow
A fact or noteremember(text, session_id=...) (stored as a Q&A entry with the text as the answer)
A Q&A turnrecall(query, session_id=...) with a completion search type saves the turn itself; or remember(cognee.QAEntry(question=..., answer=...), session_id=...)
An agent stepremember(cognee.TraceEntry(origin_function=..., status="success", ...), session_id=...), or the @cognee.agent_memory(save_session_traces=True) decorator
Pin a session to a project / node setnode_set=[...] on the first QAEntry/TraceEntry (or as a kwarg on any session remember) pins it; later writes repeat or omit it, a different set raises cognee.SessionNodeSetConflictError (HTTP 409). improve() keeps the set on everything it bridges, so recall(node_name=[...]) scopes to the project
Feedback on an answerremember(cognee.FeedbackEntry(qa_id=..., feedback_score=...), session_id=...) or cognee.session.add_feedback(session_id, qa_id, feedback_text=..., feedback_score=...)
Read a sessioncognee.session.get_session(session_id, last_n=...)

Requirements: CACHING=true (default). The cache backend is CACHE_BACKEND, one of sqlite (default), postgres, redis, fs, tapes. Sessions expire after SESSION_TTL_SECONDS (default 7 days).

What improve() does: nine stages, in order

Every run goes through the same ordered stages (cognee/modules/improve/registry.py). Each stage checks a gate before it spends any LLM or embedding cost, and reports one StageResult.

#StageWhat it doesRuns when
1feedback_weightsAdjusts the weight of graph elements that rated answers usedsession_ids given; adapter supports feedback weights
2persist_session_qaTurns session Q&A into graph content (node set user_sessions_from_cache)session_ids given. The only fatal stage
3persist_agent_tracesTurns agent-trace feedback into graph contentsession_ids given
4extract_agent_contextDrafts agent-profile lessons from tracessession_ids, CACHING + AUTO_FEEDBACK, an LLM
5distill_sessionsDistills session learnings into the graphsession_ids, an LLM
6update_user_preferencesFolds rated turns into per-user preferencessession_ids, PERSONALIZATION_ENABLED=true (default false)
7build_truth_subspaceBuilds the truth subspace from distilled learningssession_ids, build_truth_subspace=True, a Ladybug graph
8review_conflictsReviews dated source facts, stores conflicts and rewrites Entity descriptionsreview_conflicts=True or IMPROVE_REVIEW_CONFLICTS=true, an LLM, edge evidence
9global_context_indexBucket and root summaries for global questionsbuild_global_context_index=True, an LLM

Stages 1–7 need session_ids; 8–9 work on the graph alone. The order matters: 4 feeds 5, 5 feeds 7, and 7 runs before 8.

extraction_tasks / enrichment_tasks are deprecated and removed in the next release: they still run, as a custom_tasks stage after the others, scoped by node_name, data, node_type, vector_db_config and graph_db_config. Without custom tasks those options are ignored. Both cases warn with a FutureWarning; use run_custom_pipeline() instead.

Reading the result

improve() returns an ImproveResult, and so do POST /api/v1/improve, the CLI, and RememberResult.improve.

  • result.status: completed, errored (any stage errored), skipped (every stage skipped), or running (background, not finished).
  • result.stages: one StageResult per stage, with stage, status (completed / already_completed / skipped / errored), reason, error, counts, duration_ms.
  • result.stage("distill_sessions"), result.stage_summary(), result.lock_held, result.rerun_requested, result.rerun_passes.
  • await result.wait() finishes a background run (no-op otherwise).

Skip and no-op reasons:

ReasonMeaning / fix
no_session_idsSession stage, no session_ids passed
disabled_by_configListed in IMPROVE_STAGES_DISABLED
opt_in_disabledPass build_truth_subspace=True / review_conflicts=True / build_global_context_index=True
personalization_disabledSet PERSONALIZATION_ENABLED=true
auto_feedback_disabledStage 4 needs CACHING=true and AUTO_FEEDBACK=true
no_llm_configuredStages 4, 5, 8, 9 draft text with an LLM; none configured
edge_evidence_disabledConflict review needs EDGE_EVIDENCE_ENABLED=true
backend_unsupportedThe graph adapter lacks the feature (feedback weights, truth subspace)
session_manager_unavailableThe session cache is not reachable
lock_heldAnother improve for the same dataset or session is running (below)
aborted_by_fatal_stageStage 2 failed, so the rest did not run
budget_exhaustedAn earlier stage failed because the LLM budget is exhausted (a 402); the rest would fail the same way. Top up, then run improve again
no_new_entries, no_new_trace_steps, no_new_facts, no_writes_since_last_improveWith status already_completed: nothing new since the last run

How remember() triggers improve

  • Without a session: add, then cognify, then a foreground improve(). Its outcome is on result.improve / result.improve_error. A failed improve never marks the remember as errored.
  • With session_id: the text is cached, then a background improve(dataset, session_ids=[session_id]) starts if the debounce allows it. result.improve fills in only after await result or wait_for_background_tasks().
  • self_improvement=False turns it off per call; IMPROVE_AUTO_ENABLED=false turns it off everywhere and overrides self_improvement=True.
  • An application embedding cognee can decline one automatic improve before it starts: cognee.modules.improve.register_auto_improve_admission(check) registers one async check that remember() awaits on both paths. Returning a reason string skips the improve and sets result.improve_skipped (result.improve stays None); the data is stored either way. A check that raises allows the improve. Explicit improve() calls are never gated.

Settings (IMPROVE_*, cognee/modules/improve/config.py)

Env varDefaultMeaning
IMPROVE_AUTO_ENABLEDtrueAutomatic improve after remember()
IMPROVE_DEBOUNCE_ENTRIES1Session auto-improve fires after this many new entries
IMPROVE_DEBOUNCE_SECONDS0...or this many seconds since the last one. Seconds alone (entries left at 1) means time-only
IMPROVE_STAGES_DISABLEDemptyCSV of stage names to skip
IMPROVE_FEEDBACK_ALPHA0.1Feedback learning rate, in (0, 1]
IMPROVE_REVIEW_CONFLICTSfalseReview fact conflicts, including automatic improve
IMPROVE_EFFECTIVE_DATE_KEYeffective_dateDocument metadata key holding the source date

There is no debounce timer: held-back entries wait for the next remember() with that session, or an explicit improve().

Pitfalls

  • A plain improve(dataset) often does nothing. Without session_ids, only stages 8–9 can run, and both are off by default. Result: every stage skipped. That is expected, not an error.
  • A session's node set is pinned once. The first write carrying node_set fixes it for the session; a different set is a 409, start a new session instead. Bridged Q&A, traces and lessons carry the set, user preferences never do. The guarantee holds within one worker process (an in-process lock); with several workers, send a session's writes to one. Example: examples/guides/session_node_sets.py.
  • Typed entries do not auto-improve. remember(QAEntry/TraceEntry/ FeedbackEntry, session_id=...) stores the entry but never starts an improve. Call improve(session_ids=[...]) yourself.
  • lock_held does not wait. Improves for the same dataset or session run one at a time: a second call returns at once with every stage skipped: lock_held. If it shares a session with the running one, it sets rerun_requested=True and the holder runs up to 2 extra passes (3 passes in total; see rerun_passes). The bound is IMPROVE_MAX_RERUN_PASSES, a constant in cognee/api/v1/improve/improve.py, not an env var. The lock is per process only; multiple API workers do not share it.
  • Sessions bridge once. Q&A and trace persistence are tracked per user and session, not per dataset, so bridging a session into dataset A and then into dataset B persists no new Q&A/traces into B. Distillation is tracked per (session, dataset) and still runs into B.
  • IMPROVE_STAGES_DISABLED is validated. An unknown stage name, or persist_session_qa (fatal, cannot be disabled), raises ValueError, and the API server refuses to start.
  • Session writes with the cache off. remember(text, session_id=...) with CACHING=false only logs a warning and stores nothing; typed entries raise RuntimeError. An explicit improve(session_ids=...) then fails in the fatal stage.
  • Fatal stage failure. If stage 2 errors, improve() raises (HTTP 409) and the error carries .improve_result. In background mode it is recorded on result.error instead. Other stages failing only mark themselves errored; HTTP still returns 200, so check status.
  • Remote mode. After cognee.serve(url), a background improve is fire-and-forget: status stays running and there is no polling.
  • cognee/modules/session_bridge/ is gone (only stale __pycache__ may be left). The bridging now lives in the improve stages; some test names still say "session_bridge".

How it works

improve() resolves the dataset once (creating it if the name is new), claims the improve lock for dataset:<id> plus every session:<user>:<session_id>, probes the graph adapter's capabilities, and runs the stages with one frozen ImproveRunInputs. Each stage is a gate plus a call into existing pipelines plus a result mapping. Stages never own retries or ordering.

Watermarks keep repeat runs cheap:

  • Session stages track how many entries were already persisted, per user and session.
  • Conflict review uses its last succeeded stamp to select touched entities, and retries conflicts with missing citations or pending writes. Source dates come from document metadata; session windows use their last entry time. Fixed attributes remain disputed even when one document is newer.

The improve operation row is written when the run finishes: failed if any stage errored (a retry is never gated off), noop if nothing ran.

  • Orchestrator: cognee/api/v1/improve/improve.py (HTTP: routers/get_improve_router.py; CLI: cognee/cli/commands/improve_command.py)
  • Stages, registry, results: cognee/modules/improve/ (stages.py, registry.py, stage.py, result.py, inputs.py, capabilities.py, config.py, graph_changes.py, constants.py)
  • Lock: cognee/infrastructure/locks/session_lock.py
  • Session store and watermarks: cognee/infrastructure/session/ (session_manager.py, session_persist_watermark.py, feedback_detection.py); cache backends in cognee/infrastructure/databases/cache/
  • Auto-improve from remember: cognee/api/v1/remember/remember.py, cognee/api/v1/remember/auto_improve_debounce.py
  • Entry types: cognee/memory/entries.py
  • Background tasks: cognee/infrastructure/background_tasks.py

Examples: examples/guides/improve_quickstart.py, sessions.py, session_distillation.py, review_conflicts.py, global_context_index.py, agent_memory_quickstart.py, and examples/advanced_guides/remember_recall_improve_example.py.

Extending it

Adding a stage:

  1. Subclass BaseStage in cognee/modules/improve/stages.py. Set name, needs_sessions, and fatal (leave it False; exactly one fatal stage is enforced at import). Implement gate() (return a skip reason constant, or None, before any LLM/embedding cost) and run() (call existing pipeline code, return a StageResult).
  2. Insert it into DEFAULT_STAGES in registry.py at the right position. The order is pinned by cognee/tests/unit/modules/improve/test_registry_order.py; update it deliberately.
  3. If it can re-run cheaply, give it a watermark so a repeat run reports already_completed (graph-wide stages can stamp the improve row with the helpers in graph_changes.py, as conflict review does).
  4. Tests: cognee/tests/unit/modules/improve/ (gates, results, config) and cognee/tests/unit/api/v1/improve/ (orchestration, rerun, router).

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Operate cognee from the terminal to store, retrieve, update, and remove information. Covers dataset and configuration management, ingestion cost estimates, session history access, and commands for inspecting or applying database migrations.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Storing documents and asking questions from the terminal
  • Estimating token usage and cost before importing data
  • Managing datasets and saved configuration
topoteretes/cognee3.3만2026년 10월 20일 업데이트

Connect cognee to additional databases and data sources through community packages. The skill covers installing and registering adapters, importing data through connectors, configuring monitoring, and developing extension packages with examples and tests.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Connect cognee to Qdrant or another database
  • Import data from Slack or Gmail
  • Configure monitoring with Keywords AI
topoteretes/cognee3.3만2026년 10월 20일 업데이트

Define custom entities and relationships in cognee, a memory system for AI applications. This skill guides model design, identity matching, searchable fields, and troubleshooting when entities are duplicated or relationships are missing.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Designing custom entities and relationships
  • Preventing duplicate entities across imports
  • Investigating missing search results or relationships
topoteretes/cognee3.3만2026년 10월 20일 업데이트

Build custom cognee processing by chaining Python tasks, defining data types, and saving results to graph and vector databases. Use it to enrich existing data, inspect run status, and troubleshoot how tasks pass data.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Building custom extraction and processing steps
  • Saving custom data types to graph and vector databases
  • Adding information to an existing graph
topoteretes/cognee3.3만2026년 10월 20일 업데이트

Run cognee in Docker, starting with a prebuilt image for local document ingestion and questions. It also covers Docker Compose profiles for adding the UI, MCP server, Postgres, and Neo4j, plus persistent data storage.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Try cognee locally using a prebuilt Docker image
  • Test document ingestion and questions through the API
  • Start the UI, MCP server, and databases with Docker Compose
topoteretes/cognee3.3만2026년 10월 20일 업데이트

Find and remove stored content from cognee using its SDK, HTTP API, or CLI. Inspect documents before deletion, choose document or dataset removal, or keep raw files while clearing derived graph relationships and search vectors.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Find and delete a specific stored document
  • Remove an entire dataset
  • Clear derived memory while keeping original files
topoteretes/cognee3.3만2026년 10월 20일 업데이트

topoteretes의 스킬 모두 보기

이 스킬의 문제 신고