> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cognee.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Company Brain for Docs, Code, and Conversations

> Teach one memory a written fact, a code repository, and a rule stated in conversation, then answer one question that needs all three at once

What a new engineer needs to know about your payments API lives in three different places: one sentence in a doc, the duplicate-charge guard in the code itself, and a release rule somebody stated in chat months ago. Answering "how do I ship this safely?" means holding all three at once.

## What You'll Build

Three kinds of knowledge go into a single cognee dataset: a plain-text fact about who owns the payments API and which database it uses, a tiny Python module extracted into a code graph, and a two-turn conversation in which a release rule is stated and then distilled into permanent memory. One question — who maintains the API, which database it uses, what release rule the team learned, and which function guards against duplicate charges — is then asked from a brand-new session. Each part is answerable from exactly one of the three sources, and the answer draws on all of them even though the session that learned the rule is gone.

The complete runnable script is
[`examples/demos/company_brain/company_brain_demo.py`](https://github.com/topoteretes/cognee/blob/dev/examples/demos/company_brain/company_brain_demo.py) —
this page walks through its key moments rather than reproducing it.

## Features in Play

* [Remember](/core-concepts/main-operations/remember) — writes the text fact and the code fixture into one dataset, with `content_type="code"` selecting the code pipeline for the second
* [Code Graph](/guides/code-graph) — extracts symbols from the sample module with Enola, with no LLM call; `index_vectors=True` also embeds them so the final answer can reach them
* [Sessions](/guides/sessions) — carries the scripted two-turn conversation in which the release rule is stated
* [Session Distillation](/guides/session-distillation) — promotes that conversation's lesson out of the session cache and into the permanent graph
* [Recall](/core-concepts/main-operations/recall) — answers the final question with `GRAPH_COMPLETION` from a fresh session id, proving the knowledge outlived the conversation

## What to Expect

A successful run prints five numbered steps; the excerpts below cover the three worth watching — the code graph (step 2), distillation (step 4), and the final answer (step 5). They come from a real run, trimmed: startup banners and per-task pipeline lines are cut, home directories are shortened, and session ids are truncated. The lesson wording, how many lessons the curator accepts, and the final answer all come from live model calls, so yours will read differently. Expect a couple of minutes end to end, most of it in the distillation step.

**Enola installs itself, then the code graph is built.** The first code run downloads the pinned binary into `~/.cognee/bin`, extracts the two functions, and writes them as graph nodes and edges. Extraction is deterministic — no LLM call — and `index_vectors=True` adds the symbol embeddings the final answer needs.

```text theme={null}
Downloading enola v0.4.12 (darwin-arm64) from https://github.com/enola-labs/enola/releases/download/v0.4.12/enola-0.4.12-darwin-arm64.tar.gz
Installed enola v0.4.12 at ~/.cognee/bin/enola-0.4.12-darwin-arm64
Parsed 3 fact(s) (0 from insights.json) from .cognee-readme-demo/payments-example/.enola/facts.jsonl
Mapped 3 enola fact(s) to 4 data point(s).
Code graph node delta: 3 added, 0 updated, 0 unchanged.
Code graph edge delta: 3 new, 0 already present.
```

**`query_facts` reads the symbols straight back out.** Both functions come back as `CodeSymbol` facts with their file and line, and `payments.replay_test` carries the `calls` edge to `payments.charge_once` that Enola derived from the source. This is a deterministic listing from the graph index, not a similarity ranking.

```text theme={null}
[
  {
    "operation": "query_facts",
    "facts": [
      {
        "kind": "symbol",
        "type": "CodeSymbol",
        "name": "payments.charge_once",
        "file": "payments.py",
        "line": 4,
        "repo": "payments-example",
        "description": "symbol: cyclomatic=2, exported=True, language=python, return_type=bool, symbol_kind=function",
...
      },
      {
        "kind": "symbol",
        "type": "CodeSymbol",
        "name": "payments.replay_test",
        "file": "payments.py",
        "line": 12,
        "repo": "payments-example",
...
        "relations": [
          {
            "type": "calls",
            "target": "payments.charge_once"
          },
...
        ]
      }
    ],
    "total": 2,
    "offset": 0,
    "limit": 10,
    "has_more": false
  }
]
```

**The session's rule becomes a permanent lesson document.** Distillation reports `completed` and publishes the lessons the curator accepted, each written as a markdown document and cognified into the dataset. The lesson is rewritten rather than quoted, and one conversation can yield more than one.

```text theme={null}
Distillation: completed; 1 lesson documents
# Session learning — 2026-09-14 (session readme-learning-821c92e6…)

For every Payments API release, run the replay test before deploying to prevent duplicate webhook delivery that can cause double charges. (Learned after a prior incident in which duplicate webhook delivery caused a double charge during a Payments API release.)
```

**A brand-new session answers from all three sources.** The question is asked under a fresh random `session_id`, so none of the earlier conversation is in scope. Each line traces to a different place the knowledge came from: the maintainer and database from the remembered document, the release rule from the distilled lesson, and the function from the code graph.

```text theme={null}
Answer in a fresh session:
- Maintainer: Alice
- Database: PostgreSQL
- Release rule: Run the replay test before deploying every Payments API release (to prevent duplicate webhook delivery)
- Function: payments.charge_once
```

## Before You Start

* Complete [Quickstart](/getting-started/quickstart) to understand basic operations
* Ensure you have [LLM Providers](/setup-configuration/llm-providers) and [Embedding Providers](/setup-configuration/embedding-providers) configured — text ingestion, the session turns, distillation, and the final answer are all live model calls
* Code extraction downloads the Enola binary automatically on first use; see [Code Graph](/guides/code-graph) for how that pipeline works and how to pin the binary yourself
* The code step needs an embedding provider but makes no LLM call: extraction itself is deterministic, and `index_vectors=True` embeds the extracted symbols so `GRAPH_COMPLETION` can retrieve them later
* Run it from a checkout of the cognee repo: the script loads your `.env` with `load_dotenv()`, writes its sample module beside itself, and defaults its data, system, cache, and log directories into `.cognee-readme-demo` next to the script
* Storage variables are set with `setdefault`, so a `DATA_ROOT_DIRECTORY` (or any sibling) already in your environment wins and the demo writes into your existing instance instead
* The script sets `CACHING=true` and `AUTO_FEEDBACK=true` itself — distillation depends on the per-turn analysis those enable, so they are not optional here
* Nothing is deleted: the demo only adds to memory, and re-running it adds again

## How It Works

### Stage 1: Pin Storage Beside the Script

```python theme={null}
    root = Path(__file__).resolve().parent / ".cognee-readme-demo"
    for variable, directory in (
        ("DATA_ROOT_DIRECTORY", "data"),
        ("SYSTEM_ROOT_DIRECTORY", "system"),
        ("CACHE_ROOT_DIRECTORY", "cache"),
        ("COGNEE_LOGS_DIR", "logs"),
    ):
        os.environ.setdefault(variable, str(root / directory))
    # Feedback analysis captures durable guidance during the scripted session.
    os.environ["CACHING"] = "true"
    os.environ["AUTO_FEEDBACK"] = "true"
```

This runs before `import cognee`, which is what makes it effective — cognee reads these on first import. The `setdefault` calls keep the demo self-contained without overriding a real instance you have already configured, while `CACHING` and `AUTO_FEEDBACK` are forced on because the session lesson in Stage 4 has nothing to distill without them.

### Stage 2: Remember the Written Fact

```python theme={null}
    print("1. Remember the document.", flush=True)
    await cognee.remember(DOCUMENT, dataset_name=DATASET, self_improvement=False)
```

One sentence — "Alice maintains the payments API. The payments API uses PostgreSQL." — becomes graph memory. `self_improvement=False` skips the enrichment pass, which is wasted work on a single short document and keeps the demo's first step fast.

### Stage 3: Build and Query the Code Graph

```python theme={null}
async def index_code(cognee, root):
    repo = root / "payments-example"
    repo.mkdir(parents=True, exist_ok=True)
    (repo / "payments.py").write_text(CODE)
    print("\nIndexing the sample code:", flush=True)
    # index_vectors writes CodeSymbol embeddings too, so the final
    # GRAPH_COMPLETION answer can reach the code alongside text and lessons.
    await cognee.remember(str(repo), dataset_name=DATASET, content_type="code", index_vectors=True)
    facts = await cognee.search(
        query_type=cognee.SearchType.CODE,
        query_text="",
        datasets=[DATASET],
        code_query={"operation": "query_facts", "kinds": ["symbol"], "limit": 10},
    )
    print(json.dumps(facts, indent=2, default=str))
```

The script writes a two-function module — a `charge_once` duplicate guard and the `replay_test` that exercises it — and hands the folder to `remember(content_type="code")`, which routes it through the deterministic Enola pipeline rather than LLM extraction. The `query_facts` call reads the symbols straight back out, which is how you confirm the graph was built. `index_vectors=True` is what makes Stage 6 possible: by default the code facts live only in the graph index, reachable through `SearchType.CODE` but invisible to every semantic retriever.

### Stage 4: State a Rule Inside a Session

```python theme={null}
    print("3. Learn a release rule during a session.", flush=True)
    session_id = f"readme-learning-{uuid4().hex}"
    await cognee.recall(
        "Who maintains the payments API?",
        query_type=cognee.SearchType.RAG_COMPLETION,
        datasets=[DATASET],
        session_id=session_id,
    )
    await cognee.recall(
        LESSON,
        query_type=cognee.SearchType.RAG_COMPLETION,
        datasets=[DATASET],
        session_id=session_id,
    )
```

Two `recall()` calls share one `session_id`, which is what makes them a conversation rather than two unrelated queries. The first is an ordinary question; the second states the lesson — always run the replay test before a payments API release, because duplicate webhook delivery once caused a double charge — as a turn in that conversation. With `AUTO_FEEDBACK` on, the turn analysis recognizes it as durable guidance.

### Stage 5: Distill the Session into Permanent Memory

```python theme={null}
    print("4. Distill the session into permanent memory.", flush=True)
    distilled = await cognee.session.distill_session(session_id, dataset=DATASET)
    print(f"Distillation: {distilled.status}; {len(distilled.documents)} lesson documents")
    for document in distilled.documents:
        print(document)
    if distilled.status != "completed" or not distilled.documents:
        raise RuntimeError(
            "No new lesson was published. Inspect the distillation status and provider logs. "
            "An existing equivalent lesson can also cause the curator to reject a duplicate."
        )
```

`distill_session` turns the conversation's guidance into lesson documents in the graph, so the rule survives the session that produced it. Distillation is model-dependent and a curator can reject a lesson it considers a duplicate of one already stored, so the script fails loudly rather than letting the final answer quietly miss the rule.

### Stage 6: Answer from a Fresh Session

```python theme={null}
async def recall_saved_memory(cognee):
    print("\nAnswer in a fresh session:", flush=True)
    print_answers(
        await cognee.recall(
            QUESTION,
            query_type=cognee.SearchType.GRAPH_COMPLETION,
            datasets=[DATASET],
            session_id=f"readme-verification-{uuid4().hex}",
        )
    )
```

The one question that needs all three sources is asked under a brand-new random `session_id`, so none of the earlier conversation is in scope. Anything the answer gets right came from permanent memory — which is the whole point of the previous five stages. The retriever matters here: `GRAPH_COMPLETION` builds its search list from every indexed node type, so it reaches the embedded `CodeSymbol` names. `RAG_COMPLETION` reads document chunks only and would miss the code entirely.

## Run It

```bash theme={null}
uv run python examples/demos/company_brain/company_brain_demo.py
```

## Running One Part at a Time

Two mutually exclusive flags shorten the loop once memory exists:

```bash theme={null}
uv run python examples/demos/company_brain/company_brain_demo.py --recall-only
uv run python examples/demos/company_brain/company_brain_demo.py --code-only
```

`--recall-only` skips straight to Stage 6 and re-asks the question against whatever is already stored, which is the cheapest way to confirm the memory persisted across processes. `--code-only` runs just Stage 3, so you can check that Enola installed and extracted symbols without spending any LLM calls — it does embed them, so an embedding provider is still required.

<Columns cols={2}>
  <Card title="Session Distillation" icon="graduation-cap" href="/guides/session-distillation">
    How a stated rule becomes a permanent lesson, and what the curator accepts.
  </Card>

  <Card title="Code Graph" icon="code" href="/guides/code-graph">
    The Enola pipeline behind `content_type="code"` and the `code_query` operations.
  </Card>

  <Card title="Sessions" icon="message-square" href="/guides/sessions">
    Session ids, the session cache, and how turns become conversational memory.
  </Card>

  <Card title="Remember" icon="brain" href="/core-concepts/main-operations/remember">
    The write operation behind both ingestion steps, including `self_improvement`.
  </Card>
</Columns>
