> ## 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.

# recall()

> Query memory with the v1.0 retrieval API

# cognee.recall()

```python theme={null}
async def recall(
    query_text: str,
    query_type: SearchType | None = None,
    *,
    datasets: list[str] | None = None,
    dataset_ids: list[UUID] | None = None,
    top_k: int = 15,
    auto_route: bool = True,
    scope: str | list[str] | None = None,
    # plus the keyword-only options listed under "Additional keyword options"
) -> list[RecallResponse]
```

## Description

`recall()` is the main retrieval entry point in Cognee v1.0.

* It auto-routes queries by default when you do not specify `query_type`. Routing is rule-based (no LLM call) and falls back to `GRAPH_COMPLETION` when no cue matches — see [Auto-routing behavior](/core-concepts/main-operations/recall#examples-and-details) for the full cue-to-search-type mapping and when to override.
* It can search the permanent graph, session memory, or both.
* It returns `RecallResponse` items sourced from graph retrieval, session retrieval, or both depending on the request.

For the full behavior walkthrough, see [Recall](/core-concepts/main-operations/recall) and [Search Basics](/guides/search-basics).

## Prerequisites

`recall()` only reads from memory that already exists — it does not initialize anything on its own. Populate memory first with [`remember()`](/python-api/remember) (or the legacy [`add()`](/python-api/add) + [`cognify()`](/python-api/cognify) sequence). The first ingestion run creates the relational, vector, and graph databases and the default user.

```python theme={null}
import cognee

await cognee.remember("Einstein was born in Ulm.")  # creates databases + ingests
results = await cognee.recall("Where was Einstein born?")
```

<Warning>
  Calling `recall()` before any data has been ingested raises `RecallPreconditionError` (a `CogneeValidationError`, HTTP 422) with the message *"Recall prerequisites not met: no database/default user found."* It is triggered by the underlying `DatabaseNotCreatedError` (*"The database has not been created yet. Please call `await setup()` first."*) or `UserNotFoundError`. The fix is to run `remember()` (or `add()` + `cognify()`) first.
</Warning>

## Parameters

<ParamField path="query_text" type="str" required>
  Natural-language query to run against memory.
</ParamField>

<ParamField path="query_type" type="SearchType | None" default="None">
  Forces a specific retrieval strategy instead of using auto-routing.
</ParamField>

<ParamField path="datasets" type="list[str] | None" default="None">
  Restricts graph retrieval to the named datasets. Dataset names are resolved only against datasets owned by the current user. **When both `datasets` and `dataset_ids` are omitted, retrieval spans every dataset the current user has `read` access to** — not just a single default dataset. Pass this to narrow the search to specific datasets.
</ParamField>

<ParamField path="dataset_ids" type="list[UUID] | None" default="None">
  Restricts graph retrieval by dataset UUIDs instead of names. Use this for shared datasets that the current user can access but did not create. When provided, this takes precedence over `datasets` and the name-to-UUID lookup is skipped. Leaving both `datasets` and `dataset_ids` unset searches all of the user's readable datasets.
</ParamField>

<ParamField path="top_k" type="int" default="15">
  Maximum number of results to return.
</ParamField>

<ParamField path="auto_route" type="bool" default="True">
  When `True`, Cognee chooses a retrieval strategy automatically if `query_type` is not set, using the rule-based query router. Set it to `False` to always use `GRAPH_COMPLETION`. An explicit `query_type` always takes precedence over routing.
</ParamField>

<ParamField path="scope" type="str | list[str] | None" default="None">
  Controls whether retrieval uses `session`, `graph`, or the default automatic combination logic.
</ParamField>

## Additional keyword options

| Option                      | Type              | What it does                                                                                                                                                                                                                                                                                         |
| --------------------------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `system_prompt`             | `str`             | Overrides the system prompt used for completion-style answers.                                                                                                                                                                                                                                       |
| `system_prompt_path`        | `str`             | Loads the system prompt from a file path.                                                                                                                                                                                                                                                            |
| `node_name`                 | `list[str]`       | Restricts retrieval to matching node names or node sets.                                                                                                                                                                                                                                             |
| `node_name_filter_operator` | `str`             | Controls how `node_name` filters are combined.                                                                                                                                                                                                                                                       |
| `only_context`              | `bool`            | Returns retrieved context without generating the final LLM answer.                                                                                                                                                                                                                                   |
| `session_id`                | `str`             | Enables session-aware retrieval and session-cache lookup.                                                                                                                                                                                                                                            |
| `wide_search_top_k`         | `int`             | Expands the candidate set used before final ranking in graph retrieval.                                                                                                                                                                                                                              |
| `triplet_distance_penalty`  | `float`           | Adjusts ranking for triplet-based retrieval paths.                                                                                                                                                                                                                                                   |
| `feedback_influence`        | `float`           | Applies stored feedback weights during ranking where supported.                                                                                                                                                                                                                                      |
| `verbose`                   | `bool`            | Returns additional retrieval details from lower-level search flows.                                                                                                                                                                                                                                  |
| `retriever_specific_config` | `dict`            | Passes advanced configuration directly to the selected retriever.                                                                                                                                                                                                                                    |
| `response_model`            | `type \| None`    | Default `None`. Pydantic model class for structured completion output — see [Structured output](#structured-output-with-response_model) below.                                                                                                                                                       |
| `include_references`        | `bool`            | Default `False`. When set to `True`, appends a deterministic `Evidence:` block to completion-style answers, assembled in-process (no extra LLM call) from the retrieved chunks or graph context. The response schema is unchanged and the block is omitted silently when no usable references exist. |
| `user`                      | `object`          | Runs retrieval under a specific user context.                                                                                                                                                                                                                                                        |
| `llm_config`                | `LLMConfig`       | LLM settings to install into the current async context for this retrieval operation. Uses the active context config or global LLM config when omitted. Import from `cognee.infrastructure.llm.config`.                                                                                               |
| `embedding_config`          | `EmbeddingConfig` | Embedding settings to install into the current async context for this retrieval operation. Uses the active context config or global embedding config when omitted. Import from `cognee.infrastructure.databases.vector.embeddings.config`.                                                           |

<Warning>
  `recall()` accepts **only** the parameters documented above — it has no catch-all `**kwargs`. Passing an unsupported keyword such as `node_type` raises `TypeError: recall() got an unexpected keyword argument 'node_type'`. To restrict retrieval to specific nodes or node sets, use `node_name` (a `list[str]`). `node_type` is a [legacy `search()`](/python-api/search) parameter and is not exposed on `recall()`.
</Warning>

### Structured output with `response_model`

Pass a Pydantic model class to get a validated, parsed answer instead of free text — each result carries the validated payload as a dict in its `structured` field. All completion-style search types support it (`GRAPH_COMPLETION` and its variants except `GRAPH_SUMMARY_COMPLETION`, `RAG_COMPLETION`, `TRIPLET_COMPLETION`, `HYBRID_COMPLETION`, `TEMPORAL`, `AGENTIC_COMPLETION`):

```python theme={null}
from pydantic import BaseModel
import cognee
from cognee import SearchType

class NLPFacts(BaseModel):
    field_name: str
    parent_disciplines: list[str]

results = await cognee.recall(
    query_text="What is NLP and which disciplines does it belong to?",
    query_type=SearchType.GRAPH_COMPLETION,
    response_model=NLPFacts,
)

results[0].structured
# {'field_name': 'Natural Language Processing', 'parent_disciplines': [...]}
```

`response_model` is shorthand for `retriever_specific_config={"response_model": ...}` — Cognee folds the parameter into the config before dispatching, so the dict form still works. Pass it in one place: supplying the **same** model class through both is allowed, but **different** classes raise `CogneeValidationError` (HTTP 422).

<Note>
  **Remote mode.** A Python class cannot cross the HTTP boundary, so against a remote server (see [`serve()`](/core-concepts/main-operations/serve)) the SDK forwards `response_model.model_json_schema()` as the `response_schema` field of `POST /api/v1/recall`, and the server rebuilds a validation model from it. Only the schema's **structure** travels — custom validators and value constraints are not enforced server-side; rehydrate on the client (`NLPFacts.model_validate(results[0].structured)`) when you need them. See [Search & Recall — `response_schema`](/cognee-cloud/functionality/search-and-recall#structured-output-with-response_schema) for the supported schema subset and rejection rules.
</Note>

## Return value

`recall()` returns a list of `RecallResponse` items. Depending on the request, results may come from session memory, permanent graph retrieval, or both.

These items are **Pydantic objects, not plain dictionaries** — read fields with attribute access (`result.text`), not `result.get("text")` or `result["text"]`. Calling `.get()` on a result raises `AttributeError: 'ResponseGraphEntry' object has no attribute 'get'`.

The concrete type of each item is set by its `source` field (import from `cognee.modules.recall.types.RecallResponse`):

| `source`            | Type                          | Key attributes                                                                                                                                                                                          |
| ------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `"graph"`           | `ResponseGraphEntry`          | `text` (renderable answer, context, chunk text, or structured output), `kind`, `search_type`, `score`, `dataset_id`, `dataset_name`, `metadata`, `raw` (normalized payload for this item), `structured` |
| `"session"`         | `ResponseQAEntry`             | `time`, `qa_id`, `question`, `context`, `answer`, `feedback_text`, `feedback_score`                                                                                                                     |
| `"trace"`           | `ResponseAgentTraceEntry`     | session agent-trace fields                                                                                                                                                                              |
| `"session_context"` | `ResponseSessionContextEntry` | `content`, `context_profile`                                                                                                                                                                            |
| `"code"`            | `ResponseCodeEntry`           | same fields as `"graph"` entries — a deterministic code-graph fact from the `"code"` scope; only the `source` discriminator differs                                                                     |
| `"tools"`           | `ResponseToolEntry`           | `tool_name`, `question`, `text`, `success`, `error`, `structured`                                                                                                                                       |
| `"system"`          | `ResponseMarkerEntry`         | `status`, `text`, `datapoint_count`, `threshold` — a system-generated marker rather than retrieved data, see [Warming-up marker](#warming-up-marker)                                                    |

### Warming-up marker

Before running graph retrieval, `recall()` checks whether the target datasets have ever been through a Cognee pipeline. This check is a single indexed relational query — it never spins up a graph or vector engine. When no pipeline has ever run for those datasets, the graph lane returns immediately instead of running graph search plus an LLM call that could only come back empty:

```python theme={null}
# "analytics" exists, but nothing has ever been ingested into it
results = await cognee.recall("What does Cognee do?", datasets=["analytics"])

results[0].source            # "system"
results[0].status            # "memory_warming_up"
results[0].text              # "Memory is still warming up: no knowledge graph data exists yet for the requested datasets."
results[0].datapoint_count   # 0
results[0].threshold         # 1 (the configured RECALL_WARMUP_THRESHOLD)
```

If you branch on `source`, add a `"system"` case — code that previously saw an empty list for a cold dataset now sees a one-item list carrying this marker. `text` is populated so consumers that just render text still display something sensible.

Details and exceptions:

* **The marker only appears when graph is the sole source.** In a multi-source recall (for example a session-scoped call that reads both session memory and the graph), a cold graph contributes `[]` instead, so the other sources — and the `tools` `on_empty` fallback — behave exactly as if graph retrieval had returned nothing.
* **`only_context=True` bypasses the check** and always runs normal retrieval, since those callers expect context rather than a marker.
* **Populated datasets are unaffected.** Any dataset that has been through a pipeline reads as warm, including one that has only been `add()`-ed but not yet cognified.
* **The check fails open.** A probe or configuration error falls through to a normal search, so it can never block a real answer.
* **It can be turned off** with `RECALL_WARMUP_SHORTCIRCUIT=false` (or `cognee.config.set("recall_warmup_shortcircuit", False)`), which restores the previous behavior exactly. See [Recall warm-up](/setup-configuration/overview#recall-warm-up) for that variable and its two companions.

### Source provenance in `metadata`

For chunk and summary results (`CHUNKS`, `CHUNKS_LEXICAL`, `SUMMARIES`), the `metadata` dict carries stable source identifiers so you can map a result back to the data you ingested and inspect the exact cited chunk. Only the keys present in the underlying payload are included:

| `metadata` key  | Type  | Meaning                                                                                                             |
| --------------- | ----- | ------------------------------------------------------------------------------------------------------------------- |
| `data_id`       | `str` | Id of the ingested `Data` item (cognify sets `Document.id = data.id`, so a chunk's `document_id` is the `data_id`). |
| `chunk_id`      | `str` | The chunk's own node id — use it to look up the exact cited chunk.                                                  |
| `chunk_index`   | `int` | 0-based position of the chunk within its document.                                                                  |
| `document_name` | `str` | Name of the source document.                                                                                        |

Completion-style results (e.g. `GRAPH_COMPLETION`) carry an empty `metadata` dict; for those, the same ids are surfaced inline in the `Evidence:` block instead (see [`include_references`](#additional-keyword-options)). When `include_references=True`, each evidence bullet is rendered as `- chunk N of document NAME (data_id: …, chunk_id: …): "snippet"`. This is an additive response-schema change — no DB migration is required, since `document_id` is already stored on chunks.

```python theme={null}
results = await cognee.recall("What does Cognee do?")

for result in results:
    if result.source == "graph":
        print(result.text)   # answer or chunk text
        print(result.raw)    # normalized payload for this item
    elif result.source == "session":
        print(result.answer)
```

<Note>
  The `text_result`, `context_result`, and `objects_result` keys come from the legacy [`search(verbose=True)`](/python-api/search) API, which returns plain dicts. `recall()` does **not** produce those keys. For a graph-backed recall item, `result.text` is the display-ready value. `result.raw` preserves the normalized payload for that item; for completion-style searches, it is not the same thing as `objects_result`.
</Note>

For the full breakdown of session-hit shapes, graph-backed wrappers, and per-search-type payloads, see [Recall — What recall returns](/core-concepts/main-operations/recall#what-recall-returns).

## Examples

```python theme={null}
import cognee

results = await cognee.recall(
    "What does Cognee do?",
    datasets=["docs"],
    top_k=5,
)

for result in results:
    print(result)
```

<Warning>
  With backend access control enabled, `datasets=["name"]` only resolves dataset names owned by the current user. If a dataset was created by Alice and shared with Bob, Bob should query it with `dataset_ids=[shared_id]`, not `datasets=["name"]`.
</Warning>

## Related

See also [SearchType](/python-api/search-type) and [search()](/python-api/search) when you need lower-level retrieval control.
