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

# App Connectors

> Sync Gmail, Google Drive, Slack, Notion, Obsidian and other apps into Cognee memory incrementally, with deletions forgotten on the next sync

An app connector turns one account, folder, channel or vault of an external app into Cognee memory. Each connector is a function, such as `gmail_source()` or `slack_source()`, that returns a [dlt](https://docs.cognee.ai/integrations/dlt-integration.md) resource you pass straight to `remember()`. Every connector syncs the same way: the first run loads everything, later runs pick up only what changed, and items deleted in the app are forgotten. This page explains that shared mechanism once, then gives each connector's setup, code and specifics in [Connectors](#connectors).

> [!NOTE]
>
> This page drives connectors from your own script, with credentials you hold. To let users connect their own accounts to a running Cognee server through OAuth instead, see [Integrations](https://docs.cognee.ai/integrations/index.md): Gmail, Google Drive, Google Calendar, Dropbox, Linear, Notion and Slack also run that way.

## Available Connectors

| Connector | Function | One document is | Install extra |
| - | - | - | - |
| [Apollo](#apollo-connector) | `apollo_source()` | One contact, account or sequence | none |
| [Asana](#asana-connector) | `asana_source()` | One task, or one selected project | none |
| [Dropbox](#dropbox-connector) | `dropbox_source()` | One file | none |
| [Evernote](#evernote-connector) | `evernote_source()` | One note | `cognee[evernote]` |
| [Gmail](#gmail-connector) | `gmail_source()` | One message | `cognee[gmail]` |
| [Google Calendar](#google-calendar-connector) | `google_calendar_source()` | One event | `cognee[google-calendar]` |
| [Google Drive](#google-drive-connector) | `google_drive_source()` | One file | `cognee[google-drive]` |
| [Granola](#granola-connector) | `granola_source()` | One meeting note | none |
| [Linear](#linear-connector) | `linear_source()` | One issue with its comments, or one project | none |
| [Notion](#notion-connector) | `notion_source()` | One page (a database row is a page too) | none |
| [Obsidian](#obsidian-connector) | `obsidian_source()` | One note | none |
| [OneNote](#onenote-connector) | `onenote_source()` | One page | `cognee[scraping]` (or `pip install beautifulsoup4`) |
| [Slack](#slack-connector) | `slack_source()` | One thread, or one UTC day of messages without replies | none |
| [Telegram](#telegram-connector) | `telegram_source()` | One message with text or a caption | none |
| [Vercel](#vercel-connector) | `vercel_source()` | The project, one deployment, or the build output of one failed deployment | none |

## How a Connector Sync Works

### 1. Set Up Access to the App

Open your app's section under [Connectors](#connectors) and follow its **Setup** steps first. They cover what the connector needs before it can read anything: the install extra, if any, the account or app to create, the scopes or permissions to grant, and the credentials and environment variables the example script reads. Some apps need a few minutes of work in their own console, such as a Google Cloud OAuth client or a Slack app invited to the channel.

### 2. Build the Source

```python theme={null}
from cognee.tasks.ingestion.connectors import slack_source

source = slack_source(
    access_token=token,
    team_id=team_id,
    channel_id=channel_id,
    resource_name=f"slack_channel_{channel_id.lower()}",
)
```

A source reads one scope of one account: a mailbox label, a folder, a channel, a vault. The credentials and scope come from the Setup step. Every connector takes a `resource_name`, which names the staging table that holds dlt's copy of the data and the sync state that makes later runs incremental. Keep it the same across runs, and use one per account and scope: two sources must never share one.

Nothing is fetched when you build a source. The connector reads the app only when `remember()` runs it.

### 3. Sync It With remember()

```python theme={null}
await cognee.remember(
    source,
    dataset_name="slack_channel",
    primary_key="id",
    write_disposition="merge",
    max_rows_per_table=0,
    self_improvement=False,
)
print("Sync stats:", source.cognee_sync_stats)
```

Pass the same arguments on every sync:

* **`primary_key="id"`** keys each item by its id in the app (a message id, a file id, a note's path).
* **`write_disposition="merge"`** upserts items by that key. Every connector's resource declares `merge`, and leaving the argument out keeps it (on Cognee before 1.6.8, pass it explicitly). Never pass `"replace"`: it keeps only what the latest run fetched, and an incremental run fetches only what changed, so the rest of the synced data would be lost.
* **`max_rows_per_table=0`** makes explicit what Cognee always does for a connector: it reads the whole staging table back, whatever `max_rows_per_table` or `DLT_MAX_ROWS_PER_TABLE` says, so the deletion check compares against everything synced so far.
* **`self_improvement=False`** skips the automatic [Improve](https://docs.cognee.ai/core-concepts/main-operations/improve.md) step after the sync. It is optional.

Each item becomes one document: its title and text go through graph extraction like any text you pass to `remember()`. Use a dataset per connector and scope, so it is easy to inspect, query and remove.

`source.cognee_sync_stats` reports what the run did, such as how many items were read, skipped, deleted or failed. The keys differ per connector.

### 4. Sync Again

Run the same source and `remember()` call again, for example on a schedule. The connector uses its saved sync state (a cursor, a token, or a fingerprint of each item) to fetch only what changed, and Cognee builds the graph only for new or changed documents. A run with nothing changed upstream extracts nothing. This relies on `incremental_loading`, which is on by default; passing `incremental_loading=False` re-runs graph extraction on every document in the dataset.

Several connectors cap the work of one run with a request or time budget. A run cut short keeps the state it reached and reports a `failed_<reason>` key, such as `failed_budget` or `failed_rate_limit`, in `cognee_sync_stats`. Run the sync again and it continues where it stopped.

### 5. Deletions Are Forgotten

An item deleted in the app, or moved out of the synced scope, is removed from memory on a later sync: its document, graph and vectors. Two conditions apply to every connector:

* **The ingestion runs in the foreground.** `cognee.add(..., run_in_background=True)` skips the deletion pass. `remember(run_in_background=True)` still forgets deletions, because it runs `add()` in the foreground inside its background task.
* **You can delete from the dataset.** With write permission only, the sync stores new items but keeps the deleted ones.

When a connector forgets depends on how it reads the app. Some forget only after a run that walked the whole scope, and a capped or interrupted run forgets nothing. Each connector's section says which.

### 6. Ask the Synced Data

```python theme={null}
answer = await cognee.recall(
    query_text="What did the channel decide recently?",
    datasets=["slack_channel"],
)
```

Synced items are ordinary Cognee memory. Scope [`recall()`](https://docs.cognee.ai/core-concepts/main-operations/recall) to the connector's dataset. Connectors that tag each document with node sets, such as a Slack channel or an Obsidian tag, also let you narrow recall with `node_name`.

### 7. Start Over or Remove the Data

`cognee.forget()` and `cognee.prune` remove what Cognee built, but not dlt's staged copy or the connector's sync state. The next sync reads the staged copy back, so every item returns to memory and goes through graph extraction again. Leave `prune` calls out of real syncs. To remove a connector's data for good, forget the dataset and drop the staged copy with `drop_dlt_dataset`, as described in [Cleaning Up dlt's Staging Data](https://docs.cognee.ai/integrations/dlt-integration.md#cleaning-up-dlt’s-staging-data).

## Connectors

> [accordion] Apollo connector
>
> The Apollo connector syncs one Apollo.io team's contacts, accounts, and sequences into cognee memory, incrementally, and forgets records when they are deleted in Apollo. `apollo_source()` returns a dlt resource you hand directly to `cognee.remember()`, so it takes the [document-mode path](https://docs.cognee.ai/integrations/dlt-integration.md#connector-modes) (its source tag is `apollo`): each record becomes a document that goes through chunking and LLM entity extraction. It reads your team's own CRM records, never Apollo's enrichment database, and never creates, changes, or deletes anything in Apollo.
>
> > [!WARNING]
> >
> > This connector reads personal data about people outside your organisation. It is strictly opt-in — nothing is fetched until you construct a source and call `remember()`. During cognify the rendered text is sent to your configured LLM and embedding providers like any other document, so check that you may send third-party prospect data there, or use local models. Anyone with read access to the dataset can see the names it holds, so keep it in its own dataset and share it only with people allowed to see the CRM.
>
> #### Setup
>
> Nothing to install. The Apollo connector is bundled with the Cognee SDK and needs **no extra**: its REST client uses `requests`, which dlt (a core dependency) already requires.
>
> Create an API key in Apollo under **Settings > Integrations > API**. A master key works. A scoped key needs the endpoints below, and only those of the kinds you sync:
>
> | Endpoint | Needed by |
> | - | - |
> | `api/v1/contact_stages/index` | every run: it names contact stages and carries the team id |
> | `api/v1/contacts/search`, `api/v1/contacts/show` | contacts |
> | `api/v1/account_stages/index` | accounts |
> | `api/v1/accounts/search`, `api/v1/accounts/show` | accounts |
> | `api/v1/emailer_campaigns/search` | sequences, and contacts (they name their sequences) |
> | `api/v1/labels/index` | contacts and accounts |
> | `api/v1/fields/index` | only with `custom_field_ids` |
>
> `contacts/show` and `accounts/show` are read only to check a record that stopped appearing. Apollo answers HTTP 403 for a team or plan without API access to an endpoint, and the run stops with an `ApolloAccessError` that names it. That access comes with a paid plan or a trial, not a free plan; the connector has not been tested against a live account yet. A 403 on `contacts/show` or `accounts/show` does not stop the run: the record is kept and counted in `failed_access`.
>
> #### Example
>
> ```python theme={null}
> import cognee
> from cognee.tasks.ingestion.connectors import apollo_source
>
> await cognee.remember(
>     apollo_source(api_key="<apollo api key>", resource_name="apollo_sales"),
>     dataset_name="apollo_crm",
>     primary_key="id",
>     write_disposition="merge",   # the resource's default; incremental upserts and deletes
>     max_rows_per_table=0,        # 0 = no row cap; orphan cleanup must see the whole corpus
> )
>
> answer = await cognee.recall(
>     "Which contacts at Acme are in an active sequence?", datasets=["apollo_crm"]
> )
> ```
>
> #### Parameters
>
> `apollo_source()` accepts these keyword-only parameters:
>
> | Parameter | Default | Description |
> | - | - | - |
> | `resource_name` | — (required) | Names this connection: it keys the sync state and the cleanup of deleted records. One per Apollo team. |
> | `api_key` | `None` | Apollo API key. Required unless you pass `service`. A malformed key is refused when the source is built, without echoing it. |
> | `service` | `None` | A pre-built client, from `build_apollo_service(api_key)`. A client of your own must accept `request(method, path, *, body, params, check_active)` and call `check_active` before each attempt it makes, retries and waits included. |
> | `include` | all three | Which kinds to sync: `"contacts"`, `"accounts"`, `"sequences"`. Must be a non-empty subset. |
> | `contact_stage_ids`, `contact_label_ids` | no filter | Only contacts in these stages or lists. |
> | `account_stage_ids`, `account_label_ids` | no filter | Only accounts in these stages or lists. |
> | `custom_field_ids` | none | Custom fields to render, as `GET /fields?source=custom` lists their ids: `contact.<id>` or `account.<id>`. An id that list does not return stops the run with an `ApolloSourceError`. Not picklist or multi-select fields, see below. |
> | `max_requests` | `500` | Budget of API calls in one run; a call the client retries counts once. |
> | `check_active` | `None` | Optional callable run before every API request; raising from it aborts the sync. |
>
> The returned resource is preconfigured with `primary_key="id"`, `write_disposition="merge"`, and a `_deleted` hard-delete column.
>
> Labels are what Apollo's UI calls lists. Every argument that takes ids takes a list or tuple of id strings; anything else, a bare string included, is refused. Changing a filter, `include`, or `custom_field_ids` changes what is selected or rendered: records that leave the selection are forgotten, and changing `custom_field_ids` re-ingests every record whose rendered text changes as a result.
>
> Stage and list filters are checked against Apollo's own lists on every run. An id Apollo does not list (a typo, a deleted stage, or a list `GET /labels` does not return, such as another user's private list) stops the run with an `ApolloSourceError` that names the ids, before anything is emitted or forgotten — a filter that matched nothing would otherwise make every synced record look deleted.
>
> > [!WARNING]
> >
> > **One connection per Apollo team.** The first run stores the team id Apollo reports, and a run under another team's key with the same `resource_name` is refused, because it would forget the first team's records. Give every Apollo team its own `resource_name`, even in one dataset. A host that keeps one connection per team can read the id with one request:
> >
> > ```python theme={null}
> > from cognee.tasks.ingestion.connectors.apollo import apollo_team_id, build_apollo_service
> >
> > team_id = apollo_team_id(build_apollo_service("<apollo api key>"))
> > ```
>
> #### What Is Ingested
>
> Rows are flat `{id, title, content, url, _deleted, cognee_node_set}` documents whose ids are prefixed by kind:
>
> | Row | Id | Title | Content |
> | - | - | - | - |
> | Contact | `contact:<id>` | name | a sentence with its account and job title, then its account, contact stage, lists, listed custom fields, and sequences |
> | Account | `account:<id>` | name, else domain, else "Unnamed account" | a sentence with its domain, then its account stage, lists, and listed custom fields |
> | Sequence | `sequence:<id>` | name | a sentence with its status (active, inactive, archived), then its number of steps |
>
> Every text opens with one sentence that names its kind, and the rest is `Label: value` lines:
>
> ```text theme={null}
> Apollo contact Dana Whitfield works at Acme as Chief Financial Officer.
> Account: Acme (acme.com)
> Contact stage: Interested
> Sequences: Q4 Outreach (active); Renewals (paused)
> ```
>
> A contact names its account by the account's own title from the accounts listing, and falls back to its own `organization_name` when that account is not synced or names nothing. An account with no name is titled by its domain, else "Unnamed account", so accounts with neither a name nor a domain share one entity in the graph. Renaming an account changes its text and that of every one of its contacts, so each is extracted again. The stage lines say `Contact stage` and `Account stage` so that a stage with the same name on both does not merge into one entity. Ids and stages are written as names. **Never rendered**: emails, phone numbers, and social profile links (Apollo's search returns them; the connector drops them before rendering), anything from Apollo's enrichment data, the dates and steps of a contact's sequence activity, a sequence's open and reply rates, and who owns a record. The activity feed, attachments, notes, tasks, and calls are not read.
>
> Each row's `cognee_node_set` is `["apollo:<team id>:<kind>"]`, with `<kind>` one of `contacts`, `accounts`, or `sequences`, so the record's document, chunks, and entities belong to that node set. Scope a recall to Apollo, or to one kind, with `node_name`:
>
> ```python theme={null}
> from cognee.tasks.ingestion.connectors.apollo import apollo_team_id, build_apollo_service
>
> team_id = apollo_team_id(build_apollo_service("<apollo api key>"))
> await cognee.recall(
>     "Which contacts at Acme are in an active sequence?",
>     datasets=["apollo_crm"],
>     node_name=[f"apollo:{team_id}:contacts"],
> )
> ```
>
> > [!NOTE]
> >
> > The node set and the wording of the text are part of each document's identity, and are fixed: changing either would give every record a new document and one more extraction on your LLM key. A tombstone carries no node set.
>
> **Custom fields are not rendered unless you list them in `custom_field_ids`**, because teams keep phone numbers and personal emails in them. Do not list picklist or multi-select fields: Apollo returns option ids for them, not labels.
>
> #### How Sync and Forget-on-Delete Work
>
> * **Fingerprints**: Apollo has no change feed and no deleted flag, so each run lists every included kind in full and emits only the records whose rendered text changed, using a hash kept in dlt's per-resource state.
> * **Deleted records**: a contact or account that stops appearing in a complete listing is read once more before it is forgotten. It is forgotten when Apollo answers 404 or its legacy "this contact has been deleted" text (HTTP 422), or when it still exists but left the selected stages or lists. Any other answer, a 403 or 5xx included, keeps it. A sequence gone from the sequence list is forgotten at once.
> * **Deselected kinds**: leaving a kind out of `include` forgets its records on the next run.
> * **Capped listings**: Apollo search returns at most 50,000 records per listing. A bigger selection must be narrowed with stage or list filters; until then the run reports `failed_cap` and **never detects deletions**, because a capped listing is incomplete.
> * **Back-off**: a record whose deletion check keeps failing (no access, or an error Apollo does not call "deleted") is left alone for ten cycles after five failed checks in a row, then tried again. It stays in memory the whole time and is counted in `held_back`.
> * **Rate limits**: a run never waits out a rate limit. When Apollo answers 429, fewer than 10 calls are left in any minute, hour, or day window of the endpoint it is about to call, or `max_requests` is spent, the run stops cleanly, keeps its progress, and resumes at the same page next time. A key rejected after rows were emitted ends the run the same way (`failed_auth`); one rejected before any row raises `ApolloAuthError`, and dlt drops that run's state. The windows are read from every answer that carries them, error answers included, and kept per endpoint (`/contacts/search` and `/contacts/{id}` are two), so what another endpoint has left does not matter. An answer without them leaves the windows last seen for its endpoint; it is not confirmed that Apollo sends them on a 404 or 422, and if it does not, record reads that only get those answers are stopped by `max_requests` or a 429 alone.
> * **Refused listings raise**: an HTTP 403 on a search or lookup raises `ApolloAccessError` naming the endpoint instead of cutting the run, so the next run lists again and nothing is forgotten.
> * **Redirects are errors**: a 3xx answer raises `ApolloAPIError` and is never followed, because the API key travels in a header `requests` would send to the new host.
> * **Record ids are checked before a deletion check**: an id with anything but letters and digits is never requested; the check counts as failed and the record is kept.
>
> A run costs a few lookup requests (stages, lists, the sequence list), one request per 100 records of each included kind, and one per record that stopped appearing; a large workspace takes several runs.
>
> #### Sync Stats
>
> After a run, the `cognee_sync_stats` dict on the returned resource holds counts only: `scanned`, `skipped`, `deleted`, `failed`, `requests` (API calls made; a retried call counts once), and `held_back` (records in back-off when the run started — not a failure and not part of `failed`), plus the reason a run or a record failed:
>
> * `failed_rate_limit`, `failed_budget`: the run stopped early and resumes next time.
> * `failed_auth`: Apollo rejected the key. After rows were emitted the run stops early and resumes next time; before any row it raises, and the next run starts the cycle over.
> * `failed_cap`: a listing hit the 50,000-record limit, so deletions were not detected.
> * `failed_deletion_check`: the check of one record failed (a 5xx, or an answer cognee cannot read).
> * `failed_access`: the key or plan cannot call an endpoint (HTTP 403). On a record read, that one record is kept; on a listing or lookup, the run raised.
>
> A run that raises, or is cut short, also adds one to `failed`.
>
> #### Privacy and `forget()`
>
> dlt state stores the Apollo team id, each record's id with a fingerprint, and `account_names` — each synced account's title and domain, which contacts use to name their account (about 72 bytes per account). It stores no other names or text. dlt's staging database for the dataset (`dlt_database_<dataset>`) holds the full rendered text of every record. dlt's load packages, with the rendered text of each row they load, live in its data directory (`~/.dlt` of the server process unless `DLT_DATA_DIR` moves it); cognee has dlt delete them once loaded unless you set `LOAD__DELETE_COMPLETED_JOBS` yourself (see [Cleaning Up dlt's Staging Data](https://docs.cognee.ai/integrations/dlt-integration.md#cleaning-up-dlt’s-staging-data)), but a failed package stays for the retry. Logs and errors carry counts, statuses, and endpoints; record ids are replaced by `{id}` and the key is never logged or stored.
>
> > [!WARNING]
> >
> > **`cognee.forget()` alone doesn't erase a prospect for good.** `forget()` removes the documents, graph, and vectors, but not the staged copy of the rendered text or the dlt state, so the next sync under the same `resource_name` rebuilds every document — also after `forget(dataset=...)`. To erase a prospect, delete it in Apollo (or move it out of the selected stages or lists) and sync: that removes its staged row, and dlt deletes each load package once it has loaded, though a failed package keeps its text until the retry. To erase a whole dataset, call [`drop_dlt_dataset`](https://docs.cognee.ai/integrations/dlt-integration#cleaning-up-dlt’s-staging-data) after `forget(dataset=...)`.
>
> #### Limitations
>
> * Needs API access to the search endpoints (a paid plan or trial).
> * At most 50,000 records per kind and filter selection.
> * Emails, phone numbers, and social profiles are never ingested; attachments, notes, tasks, and calls are not read.
> * Only a 404 or Apollo's legacy 422 "deleted" text counts as a deletion.

> [accordion] Asana connector
>
> The Asana connector syncs the tasks of the Asana projects you select into cognee memory, incrementally, and forgets a task when it leaves those projects. `asana_source()` returns a dlt resource you hand directly to `cognee.remember()`, so it takes the [document-mode path](https://docs.cognee.ai/integrations/dlt-integration.md#connector-modes) (its source tag is `asana`): each task and each selected project becomes a document that goes through chunking and LLM entity extraction. One source is one access token and one selection of projects. It never changes anything in Asana.
>
> #### Setup
>
> Nothing to install. The Asana connector is bundled with the Cognee SDK and needs **no extra**: its REST client uses `requests`, which dlt (a core dependency) already requires.
>
> 1. Create a personal access token in the Asana developer console, or use an OAuth access token. The token needs read access to the projects and their tasks, comments, subtasks, and events; a personal access token has the access of the user who created it. The connector never refreshes a token.
> 2. Collect the gids of the projects to sync (the number in a project's URL). There is no "whole workspace" mode: a workspace-wide sync is a list of its project gids, so an empty selection can never mean everything.
>
> The connector has not been tested against a live Asana workspace yet.
>
> #### Example
>
> ```python theme={null}
> import cognee
> from cognee.tasks.ingestion.connectors import asana_source
>
> await cognee.remember(
>     asana_source(
>         resource_name="asana_website",
>         access_token="<personal access token>",
>         project_gids=["1201234567890123"],
>     ),
>     dataset_name="asana",
>     primary_key="id",
>     write_disposition="merge",   # the resource's default; incremental upserts and deletes
>     max_rows_per_table=0,        # 0 = no row cap; orphan cleanup must see the whole corpus
>     self_improvement=False,      # skip the improve() pass after each sync
> )
>
> answer = await cognee.recall("Who is working on the launch post?", datasets=["asana"])
> ```
>
> #### Parameters
>
> `asana_source()` accepts these keyword-only parameters:
>
> | Parameter | Default | Description |
> | - | - | - |
> | `resource_name` | — (required) | Names this connection: it names the staging table and keys the sync state. A non-blank string that does not start with `_dlt_`. Two connections in one dataset need two names, or each sync forgets the other's tasks. |
> | `project_gids` | — (required) | The projects to sync: a non-empty list or tuple of gid strings. It is sorted and deduplicated. A bare string, an empty list, or a gid with anything but letters and digits raises `ValueError`. |
> | `access_token` | `None` | Asana personal access token or OAuth access token. Required unless you pass `service`. Never read from the environment. |
> | `service` | `None` | A pre-built client, from `build_asana_service(access_token)`. A client of your own must accept `request(method, path, *, params, check_active)` and call `check_active` before each attempt it makes. |
> | `max_requests` | `1500` | Budget of all API calls in one run: the listing, the task reads (three per task), and the checks of missing tasks. An int of at least `3`. A call the client retries counts once. |
> | `check_active` | `None` | Optional callable run before every attempt of every request, retries included; raising from it stops the run. |
>
> The returned resource is preconfigured with `primary_key="id"`, `write_disposition="merge"`, and a `_deleted` hard-delete column.
>
> #### What Is Ingested
>
> Rows are flat `{id, title, content, url, _deleted, cognee_node_set}` documents whose ids are prefixed by kind:
>
> | Row | Id | Title | Content |
> | - | - | - | - |
> | Task | `task:<gid>` | task name | completed or not (and the day it was completed), assignee, due date, the selected projects it is in with its section, custom fields, description, subtasks, comments |
> | Project | `project:<gid>` | project name | project description |
>
> ```text theme={null}
> Completed: yes
> Completed on: 2026-10-14
> Assignee: Ada
> Due: 2026-10-20
> Project: Website launch (section: In progress)
> Priority: High
>
> Draft, then review with marketing.
>
> Subtasks:
> - [x] Outline
> - [ ] Screenshots
>   Assignee: Grace
>
> Comments:
> - Grace: Looks good
> ```
>
> A task is one document holding its comments (oldest first) and one level of subtasks. A task in two selected projects is one document that names both; projects outside the selection are never named. Nothing volatile is rendered (no `modified_at`, no time of day), so an unchanged task keeps its content hash and is not extracted again. `Completed on:` is the UTC day of Asana's `completed_at`; reopening the task removes the line. People are names, not entities, and no email address is requested.
>
> Every row carries a node set: a task gets `asana:<gid>` for every selected project it is in, sorted, and a project row gets `asana:<its own gid>`. Scope a recall to one project with `node_name`:
>
> ```python theme={null}
> await cognee.recall(
>     "Who is working on the launch post?",
>     datasets=["asana"],
>     node_name=["asana:1201234567890123"],
> )
> ```
>
> > [!NOTE]
> >
> > Node sets use project gids, never names, so renaming a project changes no node set. The row ids, node set names, and rendered text are fixed: changing them would give every task a new document and one more extraction on your LLM key. A tombstone carries no node set.
>
> #### How Sync and Forget-on-Delete Work
>
> * **Finding changes**: every run lists each selected project's tasks with their `modified_at` and reads a task again when it is new or its `modified_at` changed. What `modified_at` does not show (a new or edited comment, a renamed or removed subtask, a renamed project or section) comes through the Events API, with one sync token per project. A renamed or removed subtask refreshes its parent, also when the subtask is in a selected project and is a document of its own. An expired sync token (HTTP 412) re-reads the whole project.
> * **Forgetting**: a task is forgotten only when a complete listing of the selected projects lacks it **and** a check of its memberships (`GET /tasks/{gid}`, one request) confirms it is gone: a 403 or 404, or no selected project left. It was deleted in Asana, moved out of the selection, or its project was deselected. A run that fails or is cut inside the listing forgets nothing.
> * **Unreadable tasks are kept**: a task that is still listed but answers 403, 404, 5xx, nothing, or a body of the wrong shape keeps its old document, is counted in `failed`, and is asked again on the next run (`state["retry"]`). It is never given up on.
> * **Unresolved projects**: a project that answers 403 or 404 is skipped for the run, the others sync, and its row and tasks are kept. It is asked again on every run and counted in `unresolved`. A deleted project or a mistyped gid looks the same, so its documents stay until you remove it from the selection.
> * **Changing the selection**: a project you add is read in full. A project you remove forgets its project row and the tasks that were only in it; tasks also in a kept project are read again so the removed project's line leaves their text.
> * **Runs that stop**: a rate limit (HTTP 429), a spent `max_requests`, three tasks in a row answering 5xx or nothing, or a token rejected (HTTP 401) once the listing is complete ends the run cleanly. It never sleeps and does not read `Retry-After`. Progress is kept: tasks not reached go to `state["pending"]`, and a listing cut partway resumes at the page it stopped at (`state["listing"]`), so a large selection finishes over several runs.
> * **Expired page offsets**: if Asana refuses the stored offset a cut listing resumes from (any 4xx on that first page other than 401, 403, or 429), that project is listed again from its first page, once per run. The tasks already listed for it are dropped, the other projects of the pass are kept, and the run keeps the fresh offset. An error on the restarted listing raises instead of restarting it again; a rate limit or a spent `max_requests` cuts it cleanly like any listing.
> * **Errors**: a token rejected inside the listing raises `AsanaAuthError`, and so does a token rejection that stops a run which kept nothing (for example a resumed pass whose first task read is the run's first request), since the next run would stop at the same place. Any other failing answer outside a task read raises `AsanaAPIError` with its status; a missing-task check that answers 403 or 404 forgets the task instead, and one that answers 5xx or nothing keeps it, counted in `failed` like a read that failed. An answer of the wrong shape in a listing, the events feed, a project read, or a missing-task check raises `AsanaResponseError`, and so does a listing page without `next_page` (`null` marks the last page) or an events page without `has_more`: neither is read as the end. A run whose budget is too small to make any progress raises `AsanaSourceError`, giving the numbers. dlt drops the state of a run that raises, so the next run starts from the last good state and forgets nothing.
>
> #### Sync Stats
>
> After a run, the `cognee_sync_stats` dict on the returned resource holds counts only:
>
> | Key | Meaning |
> | - | - |
> | `scanned` | tasks listed |
> | `skipped` | listed tasks that did not need reading |
> | `deleted` | tombstones emitted |
> | `failed` | tasks that could not be read, plus one for the request that stopped a stopped run or for a run that raises |
> | `kept` | the retry queue the run committed (not part of `failed`) |
> | `pending` | the pending queue the run committed (not part of `failed`) |
> | `requests` | API calls the run started (a retried call counts once; a request `check_active` refused before sending still counts) |
> | `unresolved` | selected projects Asana answered 403 or 404 for this run |
>
> A run that stopped carries exactly one of `failed_rate_limit`, `failed_budget`, `failed_unavailable`, or `failed_auth`. A run that raises carries `failed_auth` for a rejected token or `failed_cap` for a budget too small to cover the selection (the next run would stop at the same place; Cognee 1.6.11 and earlier report `failed_budget` here), and no reason key otherwise.
>
> #### Limitations
>
> * **Budget**: a listing costs about `projects × (1 + event pages + ceil(tasks / 100))` requests, and a run reads about `(max_requests - listing) / 3` tasks. A first sync of 3,000 tasks in one project takes about seven runs at the default budget. Deselecting a big project costs one check per task.
> * **Lock hold time**: a run holds the dlt staging lock of its dataset and pipeline while it walks, for at most `max_requests` requests plus the client's retries (three attempts, backing off 1 s then 2 s). There is no wall-clock deadline.
> * **Renaming a project or section** changes the text of every task in it, so each is read and extracted again.
> * **Not read**: subtasks of subtasks, attachments, task history other than comments, tags, followers, and dependencies.
> * **Offsets that keep expiring**: a project whose stored offsets keep expiring, in a selection whose runs are always cut (by the budget or a 429) before that project lists to its end, never finishes its pass, so no task is read or forgotten until a run lists it in one go or Asana accepts an offset again; until then a changed selection is not applied either. The stats show only an ordinary `failed_budget` or `failed_rate_limit` cut.
> * If the token loses access to every task but the listing still works, a run ends with no reason key; only `failed` and `kept` show it.
>
> #### Privacy and `forget()`
>
> The connector reads task names, descriptions, comments with their authors' names, assignee names, due dates, section and project names, subtasks, custom field values, and project descriptions of the selected projects. That text goes to your configured LLM and embedding providers during cognify, like any document — including whatever people typed into comments and descriptions. Anyone with read access to the dataset can read all of it.
>
> The token lives in the client object only. Leading and trailing whitespace is stripped, and a token with whitespace, control, or non-ASCII characters inside it is refused without being echoed. Errors carry the HTTP status and an endpoint with ids replaced (`/tasks/{gid}`); neither the token nor any task id is logged. dlt state holds ids, timestamps, and page offsets, never text.
>
> > [!WARNING]
> >
> > `cognee.forget()` removes the documents, graph, and vectors, but not dlt's staged copy of the rendered text (`dlt_database_<dataset>`) or the sync state, so the next sync under the same dataset and `resource_name` rebuilds the documents. To keep a task out, delete it in Asana or take its project out of the selection, and sync. dlt deletes each load package once it has loaded, but a failed package (under `~/.dlt` of the server process unless `DLT_DATA_DIR` moves it) keeps its text until the retry. To erase a whole dataset, call [`drop_dlt_dataset`](https://docs.cognee.ai/integrations/dlt-integration#cleaning-up-dlt’s-staging-data) after `forget(dataset=...)`.

> [accordion] Dropbox connector
>
> `dropbox_source()` syncs one Dropbox folder and its subfolders, or the whole Dropbox, into Cognee memory. Each text, Markdown, CSV or PDF file and each Paper doc becomes one document, keyed by its Dropbox file id. Files deleted or moved out of the folder are forgotten.
>
> #### Setup
>
> There is no extra to install: the connector's client is `httpx`, a core dependency.
>
> 1. Create a Dropbox app at [dropbox.com/developers/apps](https://www.dropbox.com/developers/apps) with the scopes `files.metadata.read`, `files.content.read` and `account_info.read`.
> 2. Generate an access token for your account on the app's settings page. It lasts about four hours.
> 3. Set `DROPBOX_ACCESS_TOKEN` to that token.
> 4. Set `DROPBOX_FOLDER_ID` to the folder's id, the `id` that Dropbox's `/2/files/get_metadata` returns for the folder's path, like `id:a4ayc_80_OEAAAAAAAAAXw`. Leave it empty to sync the whole Dropbox.
>
> To connect an account over OAuth to a running Cognee server instead, and for what gets indexed and the sync's limits, see the [Dropbox integration](https://docs.cognee.ai/integrations/dropbox-integration.md).
>
> #### Example
>
> This script syncs the folder into the `my_dropbox` dataset and asks a question about it.
>
> ```python theme={null}
> import asyncio
> import os
>
> import cognee
> from cognee.tasks.ingestion.connectors import dropbox_account_id, dropbox_source
>
>
> async def main():
>     token = os.environ["DROPBOX_ACCESS_TOKEN"]
>     folder_id = os.environ.get("DROPBOX_FOLDER_ID", "")
>
>     source = dropbox_source(
>         folder_id=folder_id,
>         # Binds the sync state to the account, so another account can never reuse it.
>         account_id=dropbox_account_id(token),
>         token=token,
>         # One name per folder and account: it names the staging table and the cursor.
>         resource_name="dropbox_example",
>     )
>     await cognee.remember(
>         source,
>         dataset_name="my_dropbox",
>         primary_key="id",
>         write_disposition="merge",
>         max_rows_per_table=0,
>     )
>     print("Sync counts:", source.cognee_sync_stats)
>
>     answer = await cognee.recall("What did I decide about the Q4 plan?", datasets=["my_dropbox"])
>     print(answer[0].text if answer else "No answer.")
>
>
> if __name__ == "__main__":
>     asyncio.run(main())
> ```
>
> `dropbox_account_id(token)` looks up the token's account so the sync state is tied to it, and another account can never reuse it. `resource_name` names the staging table and the cursor that make later runs incremental, so use one name per folder and account.
>
> #### Parameters
>
> `resource_name` must start with `dropbox_` and hold only lowercase letters, digits and single underscores (at most 63 characters), or `dropbox_source()` raises `ValueError`.
>
> #### Checking a Sync
>
> A normal return alone does not prove the sync finished, so check `source.cognee_sync_stats`: a run is complete when `failed == 0` and `complete == 1`.

> [accordion] Evernote connector
>
> `evernote_source()` reads the notes of one Evernote account. Each note becomes one document holding its notebook, its tags and its text, and a note is read again only when it changes. Documents carry the source tag `evernote`.
>
> > [!WARNING]
> >
> > This connector reads your personal notes. The note text goes to your configured LLM and embedding providers, and anyone with read access to the dataset can read it. Encrypted note sections are replaced by `[encrypted content]` and attachments by their type.
>
> #### Setup
>
> 1. Install the extra, which adds Evernote's Thrift client (`evernote-plus` and `thrift`):
>
>    ```bash theme={null}
>    pip install "cognee[evernote]"
>    ```
>
>    The extra is imported only when a sync makes its first call, so importing `cognee.tasks.ingestion.connectors` loads nothing. Without it, that first call raises an `ImportError` that names the install command, which `remember()` surfaces wrapped in a `DLTIngestionError`.
> 2. Get a token: a **developer token** for your own account, or an **OAuth 1.0a access token** your application already obtained from Evernote. The connector runs no OAuth flow and never reads the token from the environment, so pass it as `token`. The example reads it from `EVERNOTE_TOKEN`:
>
>    ```bash theme={null}
>    export EVERNOTE_TOKEN="S=s1:U=...:H=..."
>    ```
>
> The Evernote connector is **SDK-only**. Evernote authorizes third-party applications with OAuth 1.0a, and Cognee Cloud connects providers through OAuth 2 only, so there is no Cloud connect flow for Evernote.
>
> #### Example
>
> This script syncs one account into the `evernote_demo` dataset, asks a question, then syncs and asks again.
>
> ```python theme={null}
> import asyncio
> import os
>
> import cognee
> from cognee.tasks.ingestion.connectors import evernote_source
>
> # One dataset per Evernote account, so it is easy to inspect and forget.
> DATASET_NAME = "evernote_demo"
>
> QUESTION = "What did I plan to do next week?"
>
>
> async def sync_and_ask() -> None:
>     source = evernote_source(
>         # One name per account: it names the staging table and the sync state.
>         resource_name="evernote_notes",
>         token=os.environ["EVERNOTE_TOKEN"],
>         # notebook_names=["Work"],   # optional: only these notebooks, by name
>     )
>     # Pass the same arguments on every later sync.
>     await cognee.remember(
>         source,
>         dataset_name=DATASET_NAME,
>         primary_key="id",
>         # The resource declares "merge", so leaving it out keeps it too.
>         # Never pass "replace": it would wipe the synced notes on the next sync.
>         write_disposition="merge",
>         # Read the whole staging table back, so a deletion is seen.
>         max_rows_per_table=0,
>         self_improvement=False,
>     )
>     # A run cut by Evernote's rate limit says so here; the next run continues where it stopped.
>     print("Sync stats:", source.cognee_sync_stats)
>
>     answer = await cognee.recall(query_text=QUESTION, datasets=[DATASET_NAME])
>     print(f"Q: {QUESTION}\nA: {answer}\n")
>
>
> async def main() -> None:
>     await sync_and_ask()
>     # Nothing changed at Evernote: the second sync reads no note and extracts nothing.
>     await sync_and_ask()
>
>
> if __name__ == "__main__":
>     asyncio.run(main())
> ```
>
> Uncomment `notebook_names` to sync only some notebooks. With nothing changed at Evernote, the second sync reads no note and extracts nothing. The script is also in the Cognee repository as [`examples/guides/evernote.py`](https://github.com/topoteretes/cognee/blob/dev/examples/guides/evernote.py).
>
> #### Parameters
>
> `evernote_source()` accepts these keyword-only parameters:
>
> | Parameter | Default | Description |
> | - | - | - |
> | `resource_name` | — (required) | Stable name of this connection. It names the staging table and scopes the sync state, so two accounts must never share one. Must already be a dlt table name (`work_notes`, not `Work Notes`) and must not start with `_dlt_`. |
> | `token` | `None` | Developer token or OAuth 1.0a access token. Required unless `service` is given. |
> | `sandbox` | `False` | Use `sandbox.evernote.com` instead of `www.evernote.com`. A `service` built for the sandbox needs `sandbox=True` here too. |
> | `notebook_names` | `None` | Notebooks to sync, by name. `None` or empty: every notebook. |
> | `tag_names` | `None` | Only notes carrying one of these tags, by name. `None` or empty: any note. |
> | `service` | `None` | A pre-built client, `build_evernote_service(token, *, sandbox=False)`, for tests and hosts. |
> | `full_resync` | `False` | Read the whole account again and forget what is no longer there. |
> | `max_notes_per_run` | `None` (no limit) | Note bodies fetched per run at most. A run stopped by it continues on the next run. |
> | `check_active` | `None` | Host checkpoint, called before each request attempt. What it raises stops the run as it is. |
>
> A source is bound to one account and environment (`production:<user id>` or `sandbox:<user id>`). A run whose stored state belongs to another account or environment raises.
>
> #### What Is Ingested
>
> * **One document per note.** Rows are `{id, title, content, _deleted}`, with `id` being `note:<guid>`. There is no `url` column.
> * **Content**: a `Notebook: <name>` line, a `Tags: <names>` line (tags sorted case-insensitively), then the note's ENML as text: headings as `#`, list items as `- `, to-dos as `[x]` / `[ ]`, and table cells joined by `|`.
> * **Attachments are not read.** An attachment becomes `[attachment: <mime type>]` and an encrypted section `[encrypted content]`; attachment bodies, resources, and note links are not fetched.
> * A note with no text uses its title, and a note with neither is not stored.
>
> #### How Sync Works
>
> Evernote numbers every change in an account with an update sequence number (USN). Each run first compares the account's current USN with the stored one, and when they match it only reads the retry list (see Limits and Retries). Otherwise it reads the account in two passes: pass 1 lists the changed notes, notebooks, tags, and expunged notes 250 entries at a time, and pass 2 fetches the body of every changed note in the selection. Progress is saved after every chunk and every note, so a run cut by a rate limit, an outage, or `max_notes_per_run` continues where it stopped.
>
> A full pass (reading the whole account) runs on the first sync, when the selection changes or its names resolve to other notebooks or tags, when a notebook was expunged, with `full_resync=True`, when the account's current USN is below the stored one, and when Evernote's `fullSyncBefore` is newer than the last sync.
>
> #### Deletions
>
> Deletions are emitted as `_deleted` tombstones only for notes this resource emitted, and only on evidence: a **complete** pass 1, or a body read that finds the note gone or empty. A cut or failed pass 1 never deletes. A note is forgotten when it is trashed or expunged, moved out of the selected notebooks or tags, not found when its body is read, edited to have no text and no title, or (on a full pass) no longer live and selected. When a notebook is expunged, the run does a full pass and forgets every emitted note it no longer lists.
>
> `cognee.forget()` does not reach Evernote: a note forgotten by hand comes back on the next sync while it still exists at Evernote, because its staging row is kept.
>
> #### Sync Stats
>
> After a run, `source.cognee_sync_stats` holds `emitted` (note documents), `deleted` (tombstones), `failed`, `failed_rate_limit`, `failed_auth`, and `failed_unavailable`; every key is present on every exit. A cut by `max_notes_per_run` is not a failure.
>
> #### Limits and Retries
>
> * **Rate limit**: Evernote limits calls per API key and user per hour and does not publish the number. A `RATE_LIMIT_REACHED` is waited out while the waits of one call stay within 30 seconds; a longer one ends the run cleanly with `failed_rate_limit`, and the next run continues.
> * **Outages**: transport errors are retried three times, after 1, 2 and 4 seconds. Transport errors that outlast the retries and Evernote system errors end the run cleanly with `failed_unavailable`, and the next run continues.
> * **Retry list**: a note Evernote will not hand over, or that answers unavailable, is counted in `failed` and kept on a retry list; the sync moves on and the note's old document stays. Every run reads the retry list after the pass is stored, so failing notes never hold back new notes and edits.
> * **Tokens and permissions**: a rejected token (`INVALID_AUTH`, `AUTH_EXPIRED`) sets `failed` and `failed_auth`, and a `PERMISSION_DENIED` on any call but a note's body sets `failed` alone. Before any row is emitted they raise instead (`EvernoteAuthError`, `EvernotePermissionError`, which `remember()` surfaces wrapped in a `DLTIngestionError`); after rows, the run ends cleanly and keeps what was emitted.
> * **First sync cost**: one listing call per 250 changed entries plus one call per note in the selection, then cognify of every note.
>
> #### Known Limitations
>
> * **Selection by name.** Renaming a selected notebook or tag fails the next run with a message that names the missing name; update `notebook_names` / `tag_names`.
> * **Renamed notebooks and tags stay in the text.** The `Notebook:` and `Tags:` lines carry names, so after a rename a note keeps the old name until the note itself changes.
> * **SDK only**: there is no Cloud connect flow (see Setup).

> [accordion] Gmail connector
>
> `gmail_source()` syncs the messages in one Gmail mailbox, or the labels you select, into Cognee memory. Each message becomes one document with its subject, searchable headers and plain-text body. The connector is bundled with the Cognee SDK (from `v1.6.1`) and supersedes the standalone `cognee-community-connector-gmail` package.
>
> > [!WARNING]
> >
> > This connector reads the **content** of your email. Nothing is fetched until you construct a source and call `remember()`. Scope what you ingest with `label_ids`, keep the OAuth token file (`token.json`) private, and use a dedicated dataset so you can wipe it with a single `cognee.forget(...)`.
>
> #### Setup
>
> Install the extra:
>
> ```bash theme={null}
> pip install "cognee[gmail]"
> ```
>
> Or with uv: `uv pip install "cognee[gmail]"`. The `gmail` extra pulls in `google-api-python-client`, `google-auth`, and `google-auth-oauthlib`. They are imported lazily: importing `cognee.tasks.ingestion.connectors` works without the extra, and the `ImportError` naming it is raised only when the Gmail client is built, during the `remember()` call.
>
> The connector authenticates through the OAuth2 **installed-app** (Desktop app) flow with the read-only scope `https://www.googleapis.com/auth/gmail.readonly`, so it never modifies your mailbox. Set it up once in the [Google Cloud Console](https://console.cloud.google.com/):
>
> 1. Create a project, or select an existing one.
> 2. Open the [Gmail API](https://console.cloud.google.com/apis/library/gmail.googleapis.com) page and click **Enable**.
> 3. Open [Google Auth Platform](https://console.cloud.google.com/auth/overview) and click **Get started**. Enter an app name and your email, choose **External** as the audience, and finish the wizard. Google Auth Platform isn't in the left menu by default; you can also reach it through **☰ → APIs & Services → OAuth consent screen**.
> 4. Open [Audience](https://console.cloud.google.com/auth/audience). If it shows **User type: External** and **Publishing status: Testing**, click **Add users** under **Test users** and add the Google account whose mailbox you want to sync. If the user type is **Internal** (a Google Workspace organization) or the app is **In production**, there is no **Test users** section and you can skip this step.
> 5. Under [Data Access](https://console.cloud.google.com/auth/scopes), click **Add or remove scopes**, filter for `gmail.readonly`, tick `.../auth/gmail.readonly`, click **Update**, then **Save**.
> 6. Under [Clients](https://console.cloud.google.com/auth/clients), click **Create client**, choose **Desktop app**, and click **Create**. Click **Download JSON** in the dialog that follows. A **Web application** client, such as the one from the [Gmail integration](https://docs.cognee.ai/integrations/gmail-integration.md), fails at sign-in with `Error 400: redirect_uri_mismatch`.
> 7. Save the downloaded file as `credentials.json` in the folder you run the script from (or pass `credentials_path`), or point the script at it in your shell or in your `.env`:
>
>    ```bash theme={null}
>    export GMAIL_CREDENTIALS_PATH=/path/to/client_secret_XXXX.json
>    # optional; defaults to token.json in the folder you run the script from
>    export GMAIL_TOKEN_PATH=/path/to/gmail-token.json
>    ```
>
>    Use absolute paths in `.env`, which doesn't expand `~`.
>
> The first run opens a browser for consent and caches the user token at `token.json` (`token_path`) with owner-only (`0600`) permissions. Later runs reuse and silently refresh that token. To let users connect their mailboxes through Cognee's API instead of a local token file, see the [Gmail integration](https://docs.cognee.ai/integrations/gmail-integration.md).
>
> #### Example
>
> This script loads the 25 newest messages in `INBOX` and asks a question about them.
>
> ```python theme={null}
> import asyncio
> import os
>
> import cognee
> from cognee.tasks.ingestion.connectors import gmail_source
>
> # Keep the inbox in its own dataset so it is easy to inspect and forget.
> DATASET_NAME = "gmail_inbox"
>
> # Routing kwargs for remember(). Pass the same ones on every later sync.
> #   write_disposition="merge" is what the resource declares, so leaving it out
> #     keeps it too (pass it on Cognee before 1.6.8). Never pass "replace": it
> #     would wipe the whole synced inbox on the next sync.
> #   max_rows_per_table=0 guarantees no per-table read cap applies (even if
> #     DLT_MAX_ROWS_PER_TABLE is set), so orphan-cleanup (forget-on-delete)
> #     compares against the *entire* synced corpus.
> #   incremental_loading is left at its default (True) so a re-sync only builds
> #     the graph for new or changed messages instead of the whole inbox again.
> GMAIL_REMEMBER_KWARGS = {
>     "primary_key": "id",
>     "write_disposition": "merge",
>     "max_rows_per_table": 0,
>     "self_improvement": False,
> }
>
>
> async def main():
>     credentials_path = os.environ.get("GMAIL_CREDENTIALS_PATH", "credentials.json")
>     token_path = os.environ.get("GMAIL_TOKEN_PATH", "token.json")
>
>     if not os.path.exists(credentials_path):
>         print(
>             f"Gmail OAuth client secrets not found at '{credentials_path}'.\n"
>             "See the setup steps in this file's docstring, then re-run."
>         )
>         return
>
>     # Start from a clean slate so the demo is reproducible.
>     await cognee.prune.prune_data()
>     await cognee.prune.prune_system(metadata=True)
>
>     # Build the source. Scope it to INBOX and, for the demo, load only the 25
>     # newest messages so the first run is quick. Drop ``max_results`` to load
>     # the whole label; Gmail's quota allows roughly 250 messages a minute.
>     source = gmail_source(
>         credentials_path=credentials_path,
>         token_path=token_path,
>         label_ids=["INBOX"],
>         max_results=25,
>     )
>
>     # ── Sync: load the newest messages ────────────────────────────────────
>     print("\n=== Gmail sync ===")
>     result = await cognee.remember(
>         source,
>         dataset_name=DATASET_NAME,
>         **GMAIL_REMEMBER_KWARGS,
>     )
>     print(result)
>     print("Sync stats:", source.cognee_sync_stats)
>
>     answer = await cognee.recall(
>         query_text="Summarize the most important emails in my inbox.",
>         query_type=cognee.SearchType.GRAPH_COMPLETION,
>         datasets=[DATASET_NAME],
>     )
>     print(answer[0].text)
>
>
> if __name__ == "__main__":
>     asyncio.run(main())
> ```
>
> `max_results=25` keeps the first run quick, but a capped run saves no cursor, so it never syncs only the changes; drop it for real syncs, as described in Loading the Whole Inbox below. If `credentials.json` is missing, the script prints a message and exits. Remove the `prune` calls before syncing a mailbox you want to keep: they don't clear the saved cursor or dlt's staged copy of your mail (the `dlt_database_<dataset>` staging database), so the next sync brings every previously synced message back through graph extraction.
>
> #### Parameters
>
> `gmail_source()` accepts these keyword-only parameters:
>
> | Parameter | Default | Description |
> | - | - | - |
> | `credentials_path` | `"credentials.json"` | Path to the OAuth client-secret JSON (Desktop app). |
> | `token_path` | `"token.json"` | Where the cached user token is read and written. |
> | `label_ids` | `None` | Restrict to messages carrying **all** of these Gmail label ids (e.g. `["INBOX"]`). `None` covers the whole mailbox except Spam and Trash. |
> | `max_results` | `None` | Load only the newest N messages (handy for demos and tests). Each capped run starts again from the newest message and saves no incremental cursor, so later runs don't sync only the changes. `None` = no cap. |
> | `resource_name` | `"gmail_messages"` | dlt resource (and staging table) name. Give each mailbox its own name when several share one dataset or pipeline, so their cursors stay separate. |
> | `service` | `None` | A pre-built Gmail API client, used instead of the local OAuth flow. `build_gmail_service_from_access_token(token)` builds one from an access token you already hold. |
> | `check_active` | `None` | Optional callable run during extraction; raising from it aborts the sync (the integrations API uses it to stop when a connection is revoked mid-sync). |
> | `quota_units_per_minute` | `5000` | Gmail API quota budget. See Loading the Whole Inbox below. |
>
> The `query` and `include_spam_trash` parameters of the community package are gone. The returned resource (named `resource_name`) is preconfigured with `primary_key="id"`, `write_disposition="merge"`, and a `_deleted` hard-delete column, so it performs idempotent upserts by Gmail message id.
>
> #### What Gets Ingested
>
> Each message becomes one document. The subject is its title, the headers worth searching are folded into the text, and the body follows after a blank line:
>
> ```text theme={null}
> # Q3 planning notes
>
> From: Ada <ada@example.com>
> To: you@example.com
> Cc: sam@example.com
> Date: Tue, 15 Jul 2025 09:12:03 +0200
> Received: 2025-07-15T07:12:03+00:00
> Labels: INBOX, IMPORTANT
> Thread: 1980b0f2c4a1d3e7
>
> Here are the notes from this morning...
> ```
>
> * **`Received`** is Gmail's `internalDate` as a UTC ISO timestamp, alongside the sender's own `Date` header.
> * **Empty fields are left out.** A message with no `Cc` has no `Cc:` line; a message with no subject gets no `#` heading.
> * **The body is the message's first `text/plain` part**, found anywhere in the MIME tree. HTML-only mail has none, so those messages fall back to Gmail's `snippet`, a short preview rather than the full text. That keeps raw markup out of entity extraction, but expect HTML newsletters to be represented thinly.
>
> This is the text `recall()` searches and graph extraction runs on, so anything not in it (attachments, HTML bodies, other headers) can't be asked about.
>
> #### How Incremental Sync Works
>
> The connector decides how to sync from what it saved last time:
>
> * **No saved cursor** (the first sync): it lists the label from the newest message down and fetches each one. If the run wasn't capped with `max_results` and finished, it saves the mailbox `historyId` as a cursor in dlt's per-resource state.
> * **Saved cursor**: it calls `users.history.list(startHistoryId=...)` and fetches only new or changed messages. If nothing changed, no messages are downloaded.
>
> The cursor only carries over when:
>
> * the previous sync ran **without `max_results` and finished**. An interrupted sync saves nothing, so the next one starts over.
> * later syncs use the **same `dataset_name` and `label_ids`**. Changing the set of `label_ids` makes the next run do a full backfill of the new scope, so older messages that now match are picked up; reordering the same labels keeps the cursor.
> * you **don't delete the connector's saved state**. The cursor lives in dlt's pipeline state under `~/.dlt/pipelines/`.
> * you sync **at least about once a week**. Gmail expires history after roughly a week; on the resulting `404` the connector loads every message in the label again instead of stalling.
>
> **Capped syncs never switch to incremental.** A run with `max_results` always starts from the newest message and stops after that many. It doesn't remember where it stopped, so the next capped run starts from the top again instead of continuing to older mail. Messages you already have are requested from Gmail again and count against your quota, but they aren't processed into the graph again.
>
> #### When Deletions Are Forgotten
>
> * Messages the History API reports as deleted or trashed are emitted with the `_deleted` hard-delete marker and forgotten. On incremental runs, a message that leaves the scope (for example, trashed `INBOX` mail) is forgotten the same way.
> * A backfill after a `label_ids` change forgets every previously synced message outside the new scope, so narrowing `label_ids` removes the mail that no longer matches.
> * A message fetch that returns `404` or `410` means the message is gone: it counts under `skipped` and is forgotten like any other deletion.
> * A backfill capped by `max_results`, or one that fails midway, forgets nothing.
>
> #### Loading the Whole Inbox
>
> Drop `max_results` and let one sync run to completion:
>
> ```python theme={null}
> source = gmail_source(label_ids=["INBOX"])
> await cognee.remember(source, dataset_name="gmail_inbox", **GMAIL_REMEMBER_KWARGS)
> ```
>
> * **It takes a while.** Gmail allows 6,000 quota units per user per minute, and fetching one message costs 20. The connector paces itself to 5,000 units a minute by default, about 250 messages, so 10,000 messages take around 40 minutes to download. Lower the budget with `gmail_source(quota_units_per_minute=...)` if other apps use the same account.
> * **Sources for one mailbox share the budget.** Sources with the same `resource_name` (`gmail_messages` unless you set one) in one process, such as two `gmail_source()` syncs of the same mailbox running at once, share one budget. The first `quota_units_per_minute` set for that name is the one used, and later values are ignored until the process restarts. Google's per-user quota also counts traffic this process can't see, like other syncs, tenants or apps on the same account and Cloud project.
> * **Every message goes through graph extraction**, so expect at least one LLM call per message. Try a smaller label first to estimate time and cost.
> * **Let it finish.** An interrupted sync saves no cursor, so the next run starts from the beginning.
>
> #### Errors and Retries
>
> * **Message fetches**: only a `404`/`410` from Gmail means the message is genuinely gone. Anything else (a rate limit, a 5xx, a dropped connection) is first retried up to six times by the Google client. If a quota rejection (a `429`, or a `403` with reason `rateLimitExceeded` or `userRateLimitExceeded`) is still there after those retries, the connector logs a warning, waits one full 60-second quota window and tries again, up to five times, so it waits out a quota rejection for up to about five minutes before the sync fails. Any other error, or a quota rejection that outlasts the five windows, is raised, which ends the sync before the cursor advances. The next run picks up from the same point instead of mistaking a transient error for a deleted message.
> * **History API calls**: only a real `404` (not `410`) means the cursor expired, which triggers the full reload described above. Quota rejections get the same five one-minute waits as message fetches. Anything else (a 5xx, a dropped connection, or a quota rejection that outlasts those waits, after the Google client's retries) ends the sync with the saved cursor untouched, so the next run resumes from the same point instead of reloading the whole label.
>
> `source.cognee_sync_stats` counts `scanned` messages fetched from Gmail, `deleted` messages forgotten, and `skipped` / `failed` fetches.

> [accordion] Google Calendar connector
>
> `google_calendar_source()` syncs the calendars you select into Cognee memory. Each event becomes one document with its title, time, location, organizer, attendees and their responses, and description, so the same person is linked across meetings. The connector is bundled with the Cognee SDK and replaces the cognee-community Google Calendar package; it takes the [document-mode path](https://docs.cognee.ai/integrations/dlt-integration.md#connector-modes) with the source tag `google_calendar`.
>
> > [!WARNING]
> >
> > This connector reads personal data from the calendars you select. Nothing is fetched until you construct a source and call `remember()`. Event text becomes ordinary Cognee documents, so during cognify it is sent to your configured LLM and embedding providers like any other data; use local models if that matters to you. Prefer a dedicated dataset so you can wipe it with a single `cognee.forget(...)`. The token file holds a refresh token and is written with mode `0600`. Never commit it; revoke access any time at [myaccount.google.com/permissions](https://myaccount.google.com/permissions) and delete the file.
>
> #### Setup
>
> Install the extra:
>
> ```bash theme={null}
> pip install "cognee[google-calendar]"
> ```
>
> The `google-calendar` extra pulls in `google-api-python-client`, `google-auth`, and `google-auth-oauthlib`. They are imported lazily: importing `cognee.tasks.ingestion.connectors` works without the extra, and the `ImportError` naming it is raised only when the Calendar client is built.
>
> The connector uses the OAuth2 **installed-app** (Desktop app) flow with the read-only scope `https://www.googleapis.com/auth/calendar.readonly` only. It never creates, changes, or deletes anything in Google Calendar. Set it up once in the [Google Cloud Console](https://console.cloud.google.com/):
>
> 1. Create a project, or select an existing one.
> 2. Open the [Google Calendar API](https://console.cloud.google.com/apis/library/calendar-json.googleapis.com) page and click **Enable**.
> 3. Open [Google Auth Platform](https://console.cloud.google.com/auth/overview) and click **Get started**. Enter an app name and your email, choose **External** as the audience, and finish the wizard. Google Auth Platform isn't in the left menu by default; you can also reach it through **☰ → APIs & Services → OAuth consent screen**.
> 4. Open [Audience](https://console.cloud.google.com/auth/audience). If it shows **User type: External** and **Publishing status: Testing**, click **Add users** under **Test users** and add the Google account whose calendar you want to sync. If the user type is **Internal** (a Google Workspace organization) or the app is **In production**, there is no **Test users** section and you can skip this step.
> 5. Under [Data Access](https://console.cloud.google.com/auth/scopes), click **Add or remove scopes**, filter for `calendar.readonly`, tick `.../auth/calendar.readonly`, click **Update**, then **Save**.
> 6. Under [Clients](https://console.cloud.google.com/auth/clients), click **Create client**, choose **Desktop app**, and click **Create**. Click **Download JSON** in the dialog that follows. A **Web application** client, such as the one from the [Google Calendar integration](https://docs.cognee.ai/integrations/google-calendar-integration.md), fails at sign-in with `Error 400: redirect_uri_mismatch`.
> 7. Point the connector at the downloaded file, in your shell or in your `.env`:
>
>    ```bash theme={null}
>    export GOOGLE_CALENDAR_CREDENTIALS_PATH=~/Downloads/client_secret_XXXX.json
>    # optional; defaults to ~/.cognee_google_calendar_token.json
>    export GOOGLE_CALENDAR_TOKEN_PATH=~/.cognee_google_calendar_token.json
>    ```
>
>    Remove `GOOGLE_CALENDAR_ACCESS_TOKEN` and `GOOGLE_CALENDAR_REFRESH_TOKEN` from your shell and your `.env` if they are set. Either one takes precedence over the file above, and values in `.env` override the shell.
>
> The first run opens a browser for consent and caches the token, written with mode `0600`; later runs reuse and refresh it. To sign in once ahead of a sync and see which calendar ids you can sync:
>
> ```python theme={null}
> import os
>
> from cognee.tasks.ingestion.connectors.google_calendar import (
>     build_calendar_service,
>     list_calendars,
> )
>
> # Caches the token in the second file, written with mode 0600.
> service = build_calendar_service(
>     os.path.expanduser(os.environ["GOOGLE_CALENDAR_CREDENTIALS_PATH"]),
>     os.path.expanduser(os.environ["GOOGLE_CALENDAR_TOKEN_PATH"]),
> )
> print(list_calendars(service))  # the calendar ids you can sync
> ```
>
> Apps left in **Testing** get refresh tokens that expire after 7 days. Publish the app, or sign in again, for longer use.
>
> **Headless or hosted:** instead of the browser flow, set `GOOGLE_CALENDAR_REFRESH_TOKEN` with `GOOGLE_CALENDAR_CLIENT_ID` and `GOOGLE_CALENDAR_CLIENT_SECRET`, or pass a ready-made access token (`access_token=` or `GOOGLE_CALENDAR_ACCESS_TOKEN`), which is never refreshed. `build_calendar_service_from_access_token(token)` builds a client from a token you already hold. When several are set, an access token wins, then the refresh token, then the installed-app flow. A source built with no credentials at all raises a `ValueError` right away, before any pipeline work starts. To let users connect their calendars through Cognee's API instead of a local token file, see the [Google Calendar integration](https://docs.cognee.ai/integrations/google-calendar-integration.md).
>
> #### Example
>
> This script syncs your primary calendar, asks a question about it, and syncs again.
>
> ```python theme={null}
> import asyncio
>
> import cognee
> from cognee.tasks.ingestion.connectors import google_calendar_source
>
> DATASET_NAME = "google_calendar_demo"
> CALENDARS = ["primary"]
>
> # "merge" is required: it makes re-runs incremental and propagates deleted
> # events through orphan cleanup.
> REMEMBER_KWARGS = {
>     "dataset_name": DATASET_NAME,
>     "primary_key": "id",
>     "write_disposition": "merge",
> }
>
>
> async def main():
>     print("=== Initial sync ===")
>     # Your own calendar. Pass other ids, like "team@group.calendar.google.com",
>     # to sync more; GOOGLE_CALENDAR_* env vars supply the credentials.
>     source = google_calendar_source(CALENDARS)
>     await cognee.remember(source, **REMEMBER_KWARGS)
>     print("Sync stats:", source.cognee_sync_stats)
>
>     answer = await cognee.recall(
>         "Who do I meet with most often, and what are those meetings about?",
>         datasets=[DATASET_NAME],
>     )
>     print("Recall:", answer[0].text if answer else "nothing found")
>
>     print("\n=== Incremental re-sync (only new, changed or deleted events) ===")
>     source = google_calendar_source(CALENDARS)
>     await cognee.remember(source, **REMEMBER_KWARGS)
>     print("Sync stats:", source.cognee_sync_stats)
>
>
> if __name__ == "__main__":
>     asyncio.run(main())
> ```
>
> The script syncs your primary calendar only; pass other calendar ids to sync more. The first sync reads every event in it, past and future, and cognifies each one with your LLM, so it takes a while: a few hundred events can take 15 minutes or more. The second sync fetches only new, changed or deleted events through Google's sync token, so it is fast.
>
> #### Parameters
>
> | Parameter | Setting (env var) | Default | Description |
> | - | - | - | - |
> | `calendar_ids` | `GOOGLE_CALENDAR_IDS` (comma-separated) | `primary` | Calendars to sync. An empty list is refused, because it would forget every synced event. `primary` and the real id of the primary calendar are the same calendar and give one set of documents. |
> | `settings` | `GOOGLE_CALENDAR_CLIENT_ID`, `_CLIENT_SECRET`, `_REFRESH_TOKEN`, `_CREDENTIALS_PATH`, `_TOKEN_PATH` | read from the environment | A `GoogleCalendarSettings` object. `token_path` defaults to `~/.cognee_google_calendar_token.json`. |
> | `access_token` | `GOOGLE_CALENDAR_ACCESS_TOKEN` | `None` | A ready-made token for hosts and quick tries; never refreshed. |
> | `resource_name` | — | `"google_calendar_events"` | dlt resource (and staging table) name. Give each account its own name when several sync into one dataset, so their state stays separate. |
> | `check_active` | — | `None` | Optional callable run before every API request; raising from it aborts the sync. |
> | `service` | — | `None` | A pre-built Calendar client, mainly for tests. |
>
> All parameters except `calendar_ids` are keyword-only. The returned resource is preconfigured with `primary_key="id"`, `write_disposition="merge"`, and a `_deleted` hard-delete column.
>
> #### What Is Read
>
> * From the selected calendars only: title, calendar name, start and end with time zone, location, organizer, attendees with name, email, and response, the recurrence rule, status, event type, the Google Meet link, the description, and the event link.
> * Not read: attachments, conference details beyond the Meet link, reminders, colors, and other calendars. `workingLocation` events are skipped.
> * **Recurring events**: a series is one document with its `RRULE`, and a changed single occurrence is its own document.
> * **All-day events** show their last day: a one-day event reads `all day, 2026-11-08`, a three-day one `all day, 2026-11-08 to 2026-11-10`.
> * dlt state stores each calendar's id, its sync token, and its event ids, not titles or descriptions. Logs and errors carry counts and HTTP statuses only; calendar ids and request URLs are left out.
>
> #### How Incremental Sync Works
>
> * **Sync tokens**: the first run lists every event of each calendar; the sync-token API allows no date window, so the full history is read. Later runs pass that calendar's `nextSyncToken` and get only what changed. The token is saved in dlt state once the whole round has finished.
> * **Expired sync token**: a `410 Gone` lists that calendar again and reconciles it like a snapshot, so events deleted in the meantime are still forgotten.
>
> #### When Deletions Are Forgotten
>
> * **Deleted events** come back as cancelled and are forgotten if they ever reached memory. A cancelled single occurrence forgets only that occurrence; deleting a whole series also forgets its changed occurrences. An event created and deleted between two syncs is neither stored nor counted.
> * **Removed calendars**: removing a calendar from `calendar_ids` forgets its events. A calendar is also forgotten when it was synced before and has left the account's calendar list. A `404` for a calendar that is still listed, or that was never synced (most likely a typo), is a failure, not a deletion.
>
> #### Failures
>
> A calendar that fails keeps its old state and forgets nothing; it is retried on the next run, while the other calendars finish and save theirs. The run raises only when no calendar finished. A `401`, a `429`, or a `403` with a rate-limit reason ends the run early, since the remaining calendars would fail the same way; any other `403` (lost access) fails only its own calendar. This holds for HTTP responses only: a transport error, or an auth error raised by the Google client library before any HTTP call (such as google-auth's `RefreshError`), ends the whole run.
>
> `source.cognee_sync_stats` holds counts only, never titles or content: `scanned`, `skipped`, `deleted`, `calendars`, and `failed`, plus `failed_auth` (HTTP 401), `failed_rate_limit` (HTTP 429, or 403 with a rate-limit reason), or `failed_calendar_sync` (anything else) for the reason a calendar failed.

> [accordion] Google Drive connector
>
> `google_drive_source()` syncs one Google Drive folder and, by default, its subfolders into Cognee memory. Each supported file becomes one document, keyed by its Drive file ID: Google Docs, Sheets and Slides, PDFs, text files (any `text/*` type, plus JSON and XML), and Office and document files (`.docx`, `.xlsx`, `.pptx`, `.odt`, `.ods`, `.odp`, `.rtf`, `.html`, `.epub`, and the legacy `.doc`, `.xls`, `.ppt`).
>
> #### Setup
>
> Install the extra:
>
> ```bash theme={null}
> pip install "cognee[google-drive]"
> ```
>
> Office files, `.rtf` and `.epub` need a document loader: install `cognee[docling]` (or `cognee[docs]`, which brings the `unstructured` loader) alongside the connector extra. Legacy `.doc`, `.xls` and `.ppt` files also need LibreOffice (`soffice` on `PATH`, or the macOS app in `/Applications`); without it they are counted as `failed_loader_unavailable`.
>
> Called with no arguments, `google_drive_source()` takes the auth mode, credentials, token path, and folder ID from `GOOGLE_DRIVE_*` environment variables. Set `GOOGLE_DRIVE_FOLDER_ID` to the folder's Drive ID, taken from its URL. Then, once in the [Google Cloud Console](https://console.cloud.google.com/):
>
> 1. Create a project, or select an existing one.
> 2. Open the [Google Drive API](https://console.cloud.google.com/apis/library/drive.googleapis.com) page and click **Enable**.
>
> Set up **one** of these auth modes, in your shell or in your `.env`. Use absolute paths in `.env`, which doesn't expand `~`.
>
> **Service account** (recommended, no browser step):
>
> 1. Open [Service Accounts](https://console.cloud.google.com/iam-admin/serviceaccounts) and click **Create service account**. Enter a name, skip the optional permission steps, and click **Done**. The account needs no roles.
> 2. Click the new account, open the **Keys** tab, click **Add key → Create new key**, choose **JSON**, and click **Create**. The key file downloads. If your organization blocks key creation, use OAuth instead.
> 3. Copy the account's email (`...@....iam.gserviceaccount.com`). In Google Drive, share the folder with that address as **Viewer**.
> 4. Point the script at the key:
>
>    ```bash theme={null}
>    export GOOGLE_DRIVE_AUTH_MODE=service_account
>    export GOOGLE_DRIVE_CREDENTIALS_PATH=/path/to/service-account-key.json
>    ```
>
> **OAuth user credentials** (for a folder in your own My Drive):
>
> 1. Open [Google Auth Platform](https://console.cloud.google.com/auth/overview) and click **Get started**. Enter an app name and your email, choose **External** as the audience, and finish the wizard. Google Auth Platform isn't in the left menu by default; you can also reach it through **☰ → APIs & Services → OAuth consent screen**.
> 2. Open [Audience](https://console.cloud.google.com/auth/audience). If it shows **User type: External** and **Publishing status: Testing**, click **Add users** under **Test users** and add the Google account whose Drive folder you want to sync. If the user type is **Internal** (a Google Workspace organization) or the app is **In production**, there is no **Test users** section and you can skip this step.
> 3. Under [Data Access](https://console.cloud.google.com/auth/scopes), click **Add or remove scopes**, filter for `drive.readonly`, tick `.../auth/drive.readonly`, click **Update**, then **Save**.
> 4. Under [Clients](https://console.cloud.google.com/auth/clients), click **Create client**, choose **Desktop app**, and click **Create**. Click **Download JSON** in the dialog that follows. A **Web application** client, such as the one from the [Google Drive integration](https://docs.cognee.ai/integrations/google-drive-integration.md), fails at sign-in with `Error 400: redirect_uri_mismatch`.
> 5. Point the script at the downloaded file:
>
>    ```bash theme={null}
>    export GOOGLE_DRIVE_AUTH_MODE=oauth
>    export GOOGLE_DRIVE_CREDENTIALS_PATH=/path/to/client_secret_XXXX.json
>    # caches the token; without it, every run opens the browser again
>    export GOOGLE_DRIVE_TOKEN_PATH=/path/to/drive-token.json
>    ```
>
>    The first run opens a browser for one-time consent; later runs reuse the cached, auto-refreshed token. For headless or CI use, authorize the token file once on a machine with a browser.
>
> To let users connect their own Drive account to a running Cognee backend over a web OAuth consent instead, use the [Google Drive integration](https://docs.cognee.ai/integrations/google-drive-integration.md). It is configured with a different set of `GOOGLE_DRIVE_*` variables (`GOOGLE_DRIVE_CLIENT_ID`, `GOOGLE_DRIVE_REDIRECT_URI`, and so on) and syncs over its own REST endpoints.
>
> #### Example
>
> This script syncs the folder, asks a question about it, and syncs again.
>
> ```python theme={null}
> import asyncio
>
> import cognee
> from cognee.tasks.ingestion.connectors import google_drive_source
>
>
> async def main():
>     drive_source = google_drive_source()  # reads GOOGLE_DRIVE_* env vars
>
>     print("=== Initial sync ===")
>     result = await cognee.remember(
>         drive_source,
>         dataset_name="google_drive_demo",
>         primary_key="id",
>         # "merge" makes re-runs incremental and propagates deletions via
>         # orphan cleanup. It is the resource's own default, so leaving it out
>         # keeps it (pass it on Cognee before 1.6.8). Never pass "replace".
>         write_disposition="merge",
>         # The DLT ingestion default caps a table at 50 rows; Drive folders
>         # commonly exceed that, so lift the cap.
>         max_rows_per_table=0,
>     )
>     print(result)
>
>     answer = await cognee.recall("Summarize what's in the Drive folder.")
>     print("Recall:", answer)
>
>     print("\n=== Incremental re-sync (only changed/removed files are processed) ===")
>     result = await cognee.remember(
>         google_drive_source(),
>         dataset_name="google_drive_demo",
>         primary_key="id",
>         write_disposition="merge",
>         max_rows_per_table=0,
>     )
>     print(result)
>
>
> if __name__ == "__main__":
>     asyncio.run(main())
> ```
>
> The second `remember()` call uses a fresh source with the same dataset, key, and write disposition, and processes only files added or changed since the first run. The script's comment about a 50-row default is out of date. Google Drive is a document source, so Cognee always reads its whole staging table, whatever `max_rows_per_table` or `DLT_MAX_ROWS_PER_TABLE` says; the argument is harmless but changes nothing.
>
> #### What Gets Synced
>
> * Drawings, Forms, images, audio, video and archives are skipped.
> * A Google Sheet contributes its first sheet only, which is all Drive's export returns.
> * There is no file size limit by default, because downloads are streamed to a temporary file. Set one with `GOOGLE_DRIVE_MAX_FILE_SIZE_MB`.
> * File content is fetched on 8 threads in parallel, with rate-limit and server errors retried. `GOOGLE_DRIVE_MAX_WORKERS` changes the thread count.
>
> See [What gets indexed](https://docs.cognee.ai/integrations/google-drive-integration.md#what-gets-indexed) for the full table: the hosted connector reads files through the same code path.
>
> #### Syncing Again
>
> A re-sync processes only files that were added or changed since the previous run, and files deleted or trashed in Drive, or removed from the folder, are forgotten.
>
> After a Cognee upgrade that adds supported formats, the next run lists the folder in full once to pick up unchanged files the older version skipped. Files it already read are not downloaded again (an upgrade from Cognee 1.6.5 or earlier downloads them once, since those versions recorded no file versions). No reset is needed.

> [accordion] Granola connector
>
> The Granola connector syncs the meeting notes a Granola API key can see in one scope (all notes, one folder, or one space) into cognee memory, incrementally, and forgets notes Granola confirms are deleted or moved out of the scope. `granola_source()` returns a dlt resource you hand directly to `cognee.remember()`, so it takes the [document-mode path](https://docs.cognee.ai/integrations/dlt-integration.md#connector-modes): each note becomes a text document that goes through normal chunking and LLM graph extraction.
>
> #### Setup
>
> The Granola connector is bundled with the Cognee SDK. It needs no extra: the client uses `requests`, which dlt already brings. It needs a core with [`DOCUMENT_SYNC_VERSION`](https://docs.cognee.ai/integrations/dlt-integration#connector-modes) `3` or later and raises a `RuntimeError` on an older one.
>
> Auth is a **Granola API key** (`grn_...`, created in Granola under Settings, Connectors, API keys). Granola's REST API is available on Business and Enterprise plans, and has no OAuth. A personal key and a workspace key both work. The key is sent as `Authorization: Bearer` through a requests auth object, so a `~/.netrc` entry for `public-api.granola.ai` never replaces it. Proxy and CA bundle settings (`HTTPS_PROXY`, `REQUESTS_CA_BUNDLE`) still apply. The key is never read from the environment: pass it as `api_key`.
>
> #### Example
>
> ```python theme={null}
> import cognee
> from cognee.tasks.ingestion.connectors import granola_source
>
> source = granola_source(
>     scope="fol_...",  # "all", a folder id (fol_...) or a space id (spa_...)
>     api_key="grn_...",
>     resource_name="granola_notes_acme_planning",  # one per connection and scope
> )
> await cognee.remember(
>     source,
>     dataset_name="granola_acme",
>     write_disposition="merge",  # the resource's own default; never "replace", which wipes earlier syncs
>     primary_key="id",
>     max_rows_per_table=0,
>     self_improvement=False,
> )
> print(source.cognee_sync_stats)
> ```
>
> Pass the same `scope`, `resource_name`, and `remember()` arguments on every sync. To sync several scopes into one dataset, build one source with its own `resource_name` per scope.
>
> #### Parameters
>
> `granola_source()` accepts these keyword-only parameters:
>
> | Parameter | Default | Description |
> | - | - | - |
> | `scope` | required | `"all"` (every note the key sees, unfiled ones included), a folder id `fol_...` (child folders included), or a space id `spa_...`. Anything else raises `ValueError` when the source is built. |
> | `resource_name` | required | Names the staging table and the sync state, one per connection and scope. Two keys or two users must never share one: a shared name shares the state, and one sync tombstones the other's notes. The state remembers its scope, so a different scope on the same name is refused before any request (a `ValueError`, wrapped by dlt in `PipelineStepFailed`). |
> | `api_key` | `None` | The Granola API key. Builds the client when `service` is omitted; surrounding whitespace is stripped. |
> | `service` | `None` | A pre-built client from `build_granola_service(api_key)`. A client of your own must accept `get(path, params, *, check_active, time_left)` and call `check_active` before each attempt. |
> | `key_revision` | `None` | Any string that changes when the key is replaced. A change starts the walk over (a new key may see older notes) and deletes nothing by itself. |
> | `include_transcript` | `True` | `False` never asks Granola for transcripts and renders notes without their `Transcript:` block. Changing it from the previous sync lists the whole scope again, so every synced note is re-rendered with or without its transcript. |
> | `check_active` | `None` | Host checkpoint, called before every request attempt and around every row. What it raises stops the run as it is. |
> | `max_requests`, `deadline_seconds`, `max_rows` | `200`, `240`, `200` | Bounds of one run. A run that reaches one stops with `failed_budget`, keeps what it emitted, and the next run resumes. |
>
> Pass `api_key` or `service`; without either the source raises `ValueError` when built.
>
> **Hosts.** The connector is registered as the `granola` provider in `_PROVIDERS` (`cognee.modules.integrations.ingestion`), with the table prefix `granola`. Row ids, rendered text, and node sets match the Cognee Cloud pod's Granola source, but the table names differ, so a host moving from the pod source syncs each connection once more from the start.
>
> #### What Is Ingested
>
> * **One document per note.** Rows are `{id, title, content, url, cognee_node_set}`.
> * **`id`** is the note id (`not_...`). **`title`** is the note's title, or `Untitled meeting`. **`url`** is the note's `web_url`, only when it starts with `https://notes.granola.ai/`.
> * **`content`** is the title, `Meeting date: <created_at>`, the summary (Markdown, else text), and, with `include_transcript=True`, a `Transcript:` block with one `<speaker>: <text>` line per transcript part.
> * **Node set**: each row carries `cognee_node_set` `["granola:<scope>"]`, so a `recall()` can be scoped to one scope with `node_name=["granola:fol_..."]`.
> * Private scratch notes, attachments, owners, and attendee emails are never read into a row.
>
> #### How It Works
>
> * **Incremental walk**: each run lists notes changed since the last completed walk (with a 5-minute overlap) and reads each one. A run cut by a bound or an error resumes at the unread note. A note that fails on its own gets 3 attempts before it is given up (`skipped_unavailable`) until an edit lists it again.
> * **Deletions**: a note listed with `deleted_at` is tombstoned at once. At most once every 24 hours, after a complete walk, the connector lists the whole scope. Each known note missing from that listing is read by id and tombstoned only when Granola confirms it: a 404, `deleted_at`, or a membership that places it outside the scope. A note whose membership cannot place it either way stays in memory (`reconcile_unconfirmed`). A note whose read fails is kept too (counted in `skipped`) and asked again at the next reconcile. The same listing imports notes that were shared or moved into the scope without an edit.
> * **Errors**: no Granola API failure during a sync raises. The run stops, keeps what it emitted and its state, and the next run resumes.
>
> #### Sync Stats
>
> After a run, `cognee_sync_stats` holds counts, with every key present: `scanned`, `skipped`, `deleted`, `failed`, `skipped_unavailable`, `transcript_too_large` (notes imported with their summary but without a transcript over the 2,000,000-character cap), `reconcile_unconfirmed`, `retry_after_seconds`, `requests`, and one reason key per stop: `failed_auth` (401), `failed_rate_limit` (429), `failed_access` (a 403 on every request, such as an inactive subscription or an IP allowlist, or a complete reconcile listing that came back empty while notes are known; nothing is deleted), `failed_unavailable` (5xx or no answer, twice), `failed_budget` (a run bound was reached), and `failed_listing` (a listing Granola refused or answered malformed).
>
> #### Privacy and `forget()`
>
> The note text goes to your configured LLM and embedding providers during cognify. The key is never stored in the dlt state, a row, an error, or a log line, and logs never name a note, folder, or URL. `forget()` removes memory but not the staging copy or the state, so the next sync brings back what Granola still lists. To erase a note, delete it in Granola or narrow the scope.
>
> #### Limitations
>
> * Overlapping scopes (a folder and its space, or two folders sharing a note) import a note once per table.
> * A note moved to Granola's trash may stay listed, and in memory, until Granola purges it (up to 30 days).
> * This connector has not been run against a live Granola account; its tests use a fake API.
>
> For the full request list, sync state, and limits, see the [connector README](https://github.com/topoteretes/cognee/blob/dev/cognee/tasks/ingestion/connectors/granola.md).

> [accordion] Linear connector
>
> `linear_source()` reads one Linear team's issues, comments and projects. An issue, with its comments, becomes one document, and so does a project; documents carry the source tag `linear`. The connector does not forget deletions yet (see Deletions).
>
> > [!WARNING]
> >
> > This connector reads the **content** of your Linear workspace. It is strictly opt-in — nothing is fetched until you construct a source and call `remember()`. The token's visibility is the scope, so private teams it can see are included, and anyone with read access to the target dataset can see what was ingested from them. Prefer a dedicated dataset so you can wipe it with a single `cognee.forget(...)`.
>
> This is the connector you drive from your own code with a token you already hold. It is **not** the [Linear integration](https://docs.cognee.ai/integrations/linear-integration.md), which installs Cognee into a workspace as an OAuth agent.
>
> #### Setup
>
> Nothing to install: the Linear connector needs **no extra**, since dlt is a core Cognee dependency, so `cognee.tasks.ingestion.connectors` carries it out of the box. All you need is an access token: an OAuth access token or a personal `lin_api_...` API key.
>
> The source takes a plain access token and **never refreshes it**; a host that owns the OAuth flow passes a fresh token per run. OAuth tokens are sent as `Bearer`, personal API keys (`lin_api_...`) are sent as is. Surrounding whitespace is stripped, and a token that is empty or contains spaces, non-ASCII, or non-printable characters is refused when the source is built, without echoing the value.
>
> #### Example
>
> This syncs one team into the `linear` dataset.
>
> ```python theme={null}
> import cognee
> from cognee.tasks.ingestion.connectors import linear_source
>
> await cognee.remember(
>     linear_source(
>         team_id="<team uuid>",
>         access_token="<oauth token or lin_api_... key>",
>     ),
>     dataset_name="linear",
>     primary_key="id",
>     write_disposition="merge",   # the resource's own default; passing it is harmless
>     max_rows_per_table=0,        # 0 = no row cap
> )
> ```
>
> Pass the team's **id** (the uuid), not its key. One source is one team, so give each team its own `linear_source()` call. The resource declares `merge`, so leaving `write_disposition` out keeps it. Don't pass `"replace"`: the second sync would drop and reload the table instead of upserting into it.
>
> #### Parameters
>
> `linear_source()` accepts these keyword-only parameters:
>
> | Parameter | Default | Description |
> | - | - | - |
> | `team_id` | — (required) | The Linear team's id — the uuid, not the team key. |
> | `access_token` | `None` | An OAuth access token or a personal `lin_api_...` API key. Required unless you pass `service`. |
> | `service` | `None` | A pre-built Linear client used instead of building one from `access_token`. `build_linear_service(token)` builds one; mainly an injection point for tests and hosts. A client of your own must accept `execute(query, variables, *, check_active)` and call `check_active` before each attempt it makes, retries and waits included. |
> | `resource_name` | derived from `team_id` | dlt resource (and staging table) name. Defaults to `linear_` followed by the lowercased team id with runs of non-alphanumeric characters replaced by `_`. Keep the `linear_` prefix if a host tracks the table by it. |
> | `check_active` | `None` | Optional callable run before each request; raising from it aborts the sync (hosts use it to stop when a connection is revoked mid-sync). |
> | `include_archived` | `True` | Include archived issues, projects, and comments. Linear archives closed issues automatically, so leaving this on keeps most of a team's history. Trashed issues are always skipped. |
> | `page_size` | `50` | Rows per page, and also the maximum — larger values are clamped. A page of issues with their nested comments has to stay under Linear's 10,000-point per-query complexity limit. |
> | `max_requests` | `1500` | Request budget for a single run. A bigger team finishes over several runs. |
>
> The returned resource is preconfigured with `primary_key="id"`, `write_disposition="merge"`, and a `_deleted` hard-delete column.
>
> #### What Is Ingested
>
> Rows are flat `{id, title, content, url, _deleted}` documents whose ids are prefixed by kind:
>
> | Row | Id | Title | Content |
> | - | - | - | - |
> | Issue | `issue:<uuid>` | `ENG-12 Title` | state, assignee, priority, labels, project, parent, description, and the issue's comments |
> | Project | `project:<uuid>` | project name | status, lead, start and target dates, description, content |
>
> A comment is part of its issue's document rather than a row of its own, so asking about a discussion finds the issue it belongs to.
>
> * **Sub-teams are not included.** Select the sub-team itself to ingest its issues.
> * **An issue moved to another team stays in the old team's table.**
> * **A project shared by several teams is ingested once per selected team.**
>
> #### Deletions
>
> Deletions are not propagated yet. Trashed issues are skipped, but anything already ingested stays in memory: the `_deleted` column is declared and always `False`. A comment deleted in Linear is hard-deleted there, so it is never seen again and stays in the issue's document until the issue changes next.
>
> #### How It Works
>
> * **Incremental by `updatedAt`**: Linear sorts newest first and has no change feed, so each of the three streams — issues, comments, projects — keeps its own floor, plus the ids seen exactly at that floor, in dlt's per-resource state. A run with no changes yields nothing.
> * **Comments are their own stream**: an edited comment does not reliably bump its issue's `updatedAt`, so changed comments are read separately and their parent issues are re-rendered.
> * **A run is bounded**: `max_requests` (1,500 by default) caps one run. Linear allows 5,000 requests and 2,000,000 complexity points per hour for an OAuth app user (2,500 and 3,000,000 for a personal API key), shared with everything else that user does.
> * **It stops cleanly rather than raising or sleeping**: on a Linear rate limit (a gateway HTTP 429 counts as one), remaining quota below a reserve, a spent request budget, or a token that expires after progress was made, the source stops where it is, keeps the state it reached, and records it in `cognee_sync_stats`: `failed`, plus `failed_rate_limit`, `failed_budget`, or `failed_auth`. Raising would make dlt roll the run's state back, so a team too big for one hour of quota would never finish; sleeping would hold the dlt staging lock of its dataset and pipeline.
> * **The next run resumes from the cut point**, down to the page cursor it stopped at, so even a large group of rows sharing one timestamp is read across several runs.
> * **Errors that do raise**: a token rejected before any progress was made, a team that cannot be found, a pagination response that does not advance, and other API failures raise `LinearAuthError`, `LinearTeamNotFoundError`, or `LinearAPIError`. Their messages carry codes only — never the token, the query variables, or a response body.

> [accordion] Notion connector
>
> The Notion connector syncs the Notion pages and database rows you choose into cognee memory, incrementally and with forget-on-delete. `notion_source()` returns a dlt resource you hand directly to `cognee.remember()`, so it takes the [document-mode path](https://docs.cognee.ai/integrations/dlt-integration.md#connector-modes) (its source tag is `notion`): each page becomes a text document that goes through normal chunking and LLM graph extraction. On a self-hosted Cognee backend, users can connect a workspace over OAuth and pick pages in a picker instead of calling `notion_source()` by hand. See the [Notion integration](https://docs.cognee.ai/integrations/notion-integration.md), which runs this connector for each selected root.
>
> > [!WARNING]
> >
> > This connector reads the **content** of your Notion pages. It is strictly opt-in — nothing is fetched until you construct a source and call `remember()`, and only the roots you name (plus everything nested under them) are read. Prefer a dedicated dataset so you can wipe it with a single `cognee.forget(...)`.
>
> #### Setup
>
> Nothing to install. The Notion connector talks to the Notion REST API over `httpx`, a core cognee dependency, so like Linear it needs **no extra** and ships in `cognee.tasks.ingestion.connectors` with a plain `cognee` install.
>
> 1. Create a Notion **internal integration** and copy its token.
> 2. Share every page or database you want synced with that integration (`... > Connections > Add connection`).
> 3. Set `NOTION_API_KEY`, or pass `token=` directly, plus your `LLM_API_KEY` as for any other cognee run.
>
> #### Example
>
> ```python theme={null}
> import cognee
> from cognee.tasks.ingestion.connectors import notion_source
>
> await cognee.remember(
>     notion_source(
>         root_page_ids=["<page id from the page URL>"],
>         resource_name="notion_<connection id>",
>     ),
>     dataset_name="my_notion_space",
>     primary_key="id",
>     write_disposition="merge",   # incremental upsert + tombstones
>     max_rows_per_table=0,        # 0 = no row cap
> )
> ```
>
> A database (or one of its data sources) works the same way:
>
> ```python theme={null}
> notion_source(root_data_source_ids=["<database or data source id>"])
> ```
>
> #### Parameters
>
> `notion_source()` accepts these parameters:
>
> | Parameter | Default | Description |
> | - | - | - |
> | `token` | `None` | Notion integration token. Falls back to the `NOTION_API_KEY` environment variable; with neither, a `ValueError` is raised. |
> | `root_page_ids` | `None` | Page ids to walk, plus everything nested under them. |
> | `root_data_source_ids` | `None` | Data source ids to sync, plus everything nested under their rows. A **database** id is also accepted and resolved into that database's data sources. At least one of `root_page_ids` / `root_data_source_ids` is required, or a `ValueError` is raised. |
> | `workspace_id` | `None` | Stable workspace id used in each row's node set. When omitted it is resolved once from the integration's bot user (`users/me`); the sync fails rather than emitting untagged rows if it cannot be determined. |
> | `resource_name` | `"notion_pages"` | dlt resource name — also the staging table and the key of the incremental state. See the warning below. |
> | `check_active` | `None` | Optional callable run during extraction; raising from it aborts the sync (hosts use it to stop when a connection is revoked mid-sync). |
> | `http_client` | `None` | A pre-built `httpx` client, mainly a test-injection point; when omitted one is built for the sync. |
>
> The returned resource is preconfigured with `primary_key="id"`, `write_disposition="merge"`, and a `_deleted` hard-delete column. Counts-only diagnostics (never titles or content) are exposed in the `cognee_sync_stats` dict on the returned resource, including `pages_incomplete` and `deletions_withheld` (see [Blocks the API cannot read](#blocks-the-api-cannot-read) below).
>
> > [!WARNING]
> >
> > Every Notion source that syncs into the same dataset needs **its own `resource_name`**. Two sources sharing one share state, so each run tombstones and forgets the other's pages. A run refuses to continue when the stored state belongs to a different workspace, but two root sets in one workspace under one name cannot be told apart from an edited selection. Renaming a source starts it over, and documents synced under the old name are **not** cleaned up.
>
> #### What Is Ingested
>
> * **One document per page.** Rows are `{id, title, content, url, _deleted}`. A database row is a page too: its properties (rich\_text, select, multi\_select, status, date, people, number, checkbox, url, email, relation ids) are rendered as `Name: value` lines at the top of its content. Relation and people values stay raw ids/names in that text; they are not resolved into graph edges.
> * **Nested content is followed**: sub-pages, databases embedded in pages, and content inside columns, toggles, callouts, lists, and synced blocks, at any depth. A synced block that copies another page's original is not searched; its sub-pages are only synced when the original's page is under a selected root. Archived and trashed pages are skipped.
> * **Node sets**: each row carries `cognee_node_set = ["notion:<workspace_id>:<root_id>"]` — always ids, never titles — so the page's document and chunks belong to the root you configured it under. When a page is reachable from two selected roots, the nearest root wins.
> * **Structure**: each row also carries `cognee_structure` (see [Connector Modes](https://docs.cognee.ai/integrations/dlt-integration.md#connector-modes)). A sub-page lists its parent page, even when it sits inside a column or toggle: the parent is the page that holds it, not the block. A database row lists its data source, its database, and the page the database sits on; under a root you passed as a database or data source id, the page is not listed. A root has an empty list. After each cognify, these become `child_of` edges: page to parent page, database row to data source, data source to database, and database to its page. Databases and data sources become `StructureContainer` nodes, and the graph visualization treats `child_of` as a structural edge. A parent outside the selected roots, or one that was forgotten, gets no edge. Deleting a page leaves its children where they are, and a database disappears with its last row (on a graph that does not store its own provenance, at the next cognify).
> * **Attachments** (file, image, PDF, video blocks) become a name/caption reference line only; the binary is not downloaded.
>
> #### How It Works
>
> * **Re-walk every run**: Notion has no delete feed, so each run walks the selected trees again to rediscover what still exists. A page's content is only re-rendered when its `last_edited_time`, its root, its position in the tree, or whether it was [read completely](#blocks-the-api-cannot-read) changed since the previous run; unchanged pages are not re-ingested.
> * **Forget-on-delete**: pages that vanished (unshared, trashed, or moved out of the selected roots) are emitted as `_deleted` tombstones; dlt drops them on `merge` and cognee's `orphan_cleanup` forgets them from the graph, vector, and relational stores (not when `add()` runs in the background, see [Deletions Are Forgotten](#5-deletions-are-forgotten)). A page that vanished from below a page the API could not read completely is [withheld](#blocks-the-api-cannot-read) instead.
> * **Moving a page** between two selected roots, or changing roots so that another one reaches it, changes its node set (part of the row's identity), so it is re-ingested once under the new root. Moving a page **inside** its root keeps its document id and does not run extraction again; only its `child_of` edge changes. Renaming a database re-reads its rows once, because its title is part of their structure.
> * **Upgrading**: the first sync after upgrading to a Cognee with [`DOCUMENT_SYNC_VERSION`](https://docs.cognee.ai/integrations/dlt-integration#connector-modes) `3` re-reads every page once to record its position. That costs Notion API requests, not extraction, except for pages whose rendered text changed in the meantime.
> * **Cost**: a run makes at least one request per page even when nothing changed — a 20,000-page tree is tens of thousands of requests, hours at Notion's rate limit of about 3 requests per second. The connector does not throttle itself; HTTP 429 and 5xx responses are retried (up to 5 attempts) using `Retry-After` or exponential backoff.
>
> #### Errors
>
> A run aborts **before any tombstone is written** — so a partial walk can never look like a mass deletion — when:
>
> * a transient error (network failure, or a 429/5xx that exhausts the retries) occurs;
> * listing a readable page's blocks or querying a data source fails, or Notion reports more results without a `next_cursor` (unsupported block children are the one exception, see below);
> * Notion's answer omits a field it must carry (a listing's `results` or `has_more`, a block's `type` or `has_children`, a database's `data_sources`) or is not a JSON object — a missing field is never read as empty;
> * one of your **explicit roots** returns 403/404 (a configuration problem, not a deletion);
> * a data source has more than 10,000 rows (see limitations).
>
> A 403/404 on a page or database reached *through* the tree, by contrast, means that item is gone, and it is tombstoned.
>
> #### Blocks the API cannot read
>
> If Notion refuses a block's children with `400 validation_error` and the message `Block type <type> is not supported via the API.` (or the same message ending `for your bot type.`), the connector skips those children instead of aborting. The block's own text and the rest of the page are kept, and a warning logs the block id and type, never content. This only applies to the first request of a block's children listing. Any other wording, any other error, a failed page or table listing, or an error on a later page of a listing still aborts the run.
>
> * **Incomplete pages**: a page stored without such children is counted in `pages_incomplete` of `cognee_sync_stats`. The marker lives in the sync state, not in the row or its content hash, so the page is re-rendered when it turns incomplete or complete, not on every run. Nested text that was ingested before a block became unreadable is dropped in that run: the document holds what the API returns. A block skipped inside a synced copy is logged but does not mark the page.
> * **Withheld deletions**: a page that disappears from below an incompletely read page may only be hidden behind the unreadable block, so it is not tombstoned. It and everything below it are kept as stored and counted in `deletions_withheld`, with a warning naming the ids. The run continues and its state advances. Once the tree reads completely, pages that are really gone are forgotten. Items the run itself proved gone (403/404, archived or trashed, or a row missing from a data source it queried to the end) are never withheld.
>
> #### Limitations
>
> * **Data sources over 10,000 rows abort every run**: Notion cuts a query off there, and syncing only the first 10,000 would forget the rest.
> * **The walk holds the dlt staging lock of its dataset and pipeline**, so while a large tree syncs, every other dlt ingestion into the same dataset waits.
> * **Teamspaces are not exposed** by Notion's public REST API, so pages are grouped by selected root, never by teamspace.
> * **Text shown from other objects goes stale**: a page is only re-rendered when it changes itself, so sub-page and database titles, synced copies, and mentions stay as they were until the page is edited.
> * **Pinned to Notion API version `2025-09-03`**, the first with data sources as first-class objects.

> [accordion] Obsidian connector
>
> `obsidian_source()` syncs a local Obsidian vault (a folder of Markdown notes) into Cognee memory. Each `*.md` note becomes one document whose id is its path in the vault, and it takes the [document-mode path](https://docs.cognee.ai/integrations/dlt-integration.md#connector-modes) with the source tag `obsidian`. Unlike `cognee.remember("<vault folder>")`, which stores each note once, an edited note replaces its old document and a deleted or renamed note is forgotten on the next sync.
>
> > [!WARNING]
> >
> > This connector reads your personal notes. Nothing is read until you construct a source and call `remember()`. During cognify the note text, frontmatter included, is sent to your configured LLM and embedding providers like any other document, so check that you may send your notes there, or use local models. Anyone with read access to the dataset can read the notes, so keep a vault in its own dataset, and use `folders` to leave out what should not be read.
>
> #### Setup
>
> Nothing to install. The connector is bundled with the Cognee SDK and needs **no extra**, no account, no token, and no network access: it reads files from a folder on the machine that runs it. It is **SDK only**: there is no hosted integration for it, because nothing hosted can reach a vault on your disk.
>
> Pass your vault's folder as `vault_path`, and `folders=[...]` to read only some folders.
>
> #### Example
>
> This script builds a small vault in a temporary folder, syncs it, edits two notes and deletes another, then syncs again and asks the same question after each sync.
>
> ```python theme={null}
> import asyncio
> import tempfile
> from pathlib import Path
>
> import cognee
> from cognee.tasks.ingestion.connectors import obsidian_source
>
> # Keep the vault in its own dataset so it is easy to inspect and forget.
> DATASET_NAME = "obsidian_vault"
>
> # Routing kwargs for remember(). Pass the same ones on every later sync.
> #   write_disposition="merge" is what the resource declares, so leaving it out keeps it
> #     too (pass it on Cognee before 1.6.8). Never pass "replace": it would wipe the
> #     whole synced vault on the next sync.
> #   max_rows_per_table=0 guarantees no per-table read cap applies (even if
> #     DLT_MAX_ROWS_PER_TABLE is set), so forget-on-delete compares against the
> #     *entire* synced vault.
> #   incremental_loading is left at its default (True) so a re-sync only builds
> #     the graph for new or changed notes instead of the whole vault again.
> OBSIDIAN_REMEMBER_KWARGS = {
>     "primary_key": "id",
>     "write_disposition": "merge",
>     "max_rows_per_table": 0,
>     "self_improvement": False,
> }
>
> NOTES = {
>     "People/Ada Lovelace.md": "Ada Lovelace is the lead engineer of Project Atlas.\n",
>     "Projects/Atlas.md": (
>         "---\n"
>         "title: Project Atlas\n"
>         "tags: [engineering]\n"
>         "---\n"
>         "Project Atlas builds the routing engine. Ada Lovelace leads it.\n"
>     ),
>     "Reading list.md": "Grace Hopper wrote the compiler paper that Project Atlas cites.\n",
> }
>
> QUESTION = "Who leads Project Atlas?"
>
>
> async def sync_and_ask(vault: Path) -> None:
>     source = obsidian_source(vault_path=vault)
>     await cognee.remember(source, dataset_name=DATASET_NAME, **OBSIDIAN_REMEMBER_KWARGS)
>     print("Sync stats:", source.cognee_sync_stats)
>
>     answer = await cognee.recall(
>         query_text=QUESTION,
>         query_type=cognee.SearchType.GRAPH_COMPLETION,
>         datasets=[DATASET_NAME],
>     )
>     print(answer[0].text)
>
>
> async def main():
>     # Start from a clean slate so the demo is reproducible. WARNING: this wipes the whole
>     # cognee instance, every dataset, so use a throwaway instance.
>     await cognee.prune.prune_data()
>     await cognee.prune.prune_system(metadata=True)
>
>     with tempfile.TemporaryDirectory() as folder:
>         vault = Path(folder)
>         for name, text in NOTES.items():
>             (vault / name).parent.mkdir(parents=True, exist_ok=True)
>             (vault / name).write_text(text)
>
>         # ── First sync: every note is read and extracted ──────────────────
>         print("\n=== First sync ===")
>         await sync_and_ask(vault)
>
>         # ── Change the vault: edit one note, delete another ───────────────
>         (vault / "Projects/Atlas.md").write_text(
>             "---\n"
>             "title: Project Atlas\n"
>             "tags: [engineering]\n"
>             "---\n"
>             "Project Atlas builds the routing engine. Grace Hopper leads it now.\n"
>         )
>         (vault / "Reading list.md").unlink()
>         (vault / "People/Ada Lovelace.md").write_text("Ada Lovelace left the company.\n")
>
>         # ── Second sync: only the changed notes are extracted again ───────
>         # The edited notes replace their old documents and the deleted note
>         # is forgotten, so the old answer does not come back.
>         print("\n=== Second sync ===")
>         await sync_and_ask(vault)
>
>
> if __name__ == "__main__":
>     asyncio.run(main())
> ```
>
> The frontmatter `title` names the note and its `tags` become node sets (`obsidian:tag:engineering`). On the second sync only the two edited notes are extracted again, and the deleted note is forgotten, so the old answer (Ada Lovelace leads Project Atlas) does not come back. `prune_data()` and `prune_system(metadata=True)` wipe the whole Cognee instance, every dataset, not just this one: run the script against a throwaway instance (a scratch `SYSTEM_ROOT_DIRECTORY` and `DATA_ROOT_DIRECTORY`), and remove those two calls before pointing it at memory you want to keep.
>
> #### Parameters
>
> `obsidian_source()` accepts these keyword-only parameters:
>
> | Parameter | Default | Description |
> | - | - | - |
> | `vault_path` | — (required) | The vault folder, `~` expanded and resolved. A `ValueError` unless it is an existing directory. |
> | `resource_name` | `obsidian_<12 hex of the sha256 of the resolved vault path>` | Names this vault: it keys the staging table, the sync state, and the cleanup of deleted notes. A `ValueError` if it is not a non-empty string. |
> | `folders` | `None` | Vault-relative folders to read, written with `/`, subfolders included. `None` is the whole vault. |
> | `check_active` | `None` | Optional callable run before each note is read and before each row is published; raising from it aborts the sync. |
>
> The returned resource is preconfigured with `primary_key="id"`, `write_disposition="merge"`, and a `_deleted` hard-delete column.
>
> `folders` is a non-empty list or tuple such as `["Projects/Work", "Journal"]`, sorted and deduplicated. A bare string, an empty list, an absolute path, a folder name starting with a dot, a backslash, or surrounding spaces is a `ValueError` when the source is built, because each would select nothing and the next run would forget every note.
>
> **The default `resource_name` follows the vault path.** Moving or renaming the vault folder changes it, so the next sync ingests every note again under the new name, while documents synced under the old name stay until you forget them. Pass a `resource_name` to pin it. Two sources over the **same vault** with different `folders` share the default name, one table, and one state, so each run forgets the notes the other selected: put them in two datasets, or give each its own `resource_name`.
>
> #### What Is Ingested
>
> Only regular `*.md` files under the vault, or under the selected folders. Not read: anything whose name starts with a dot (`.obsidian`, `.trash`, `.git`, hidden files such as `._note.md`), other file types (**attachments** such as images and PDFs are ignored; an embed of one stays as the text you wrote), symbolic links (a linked folder is not entered), FIFOs, and device files. A note becomes one row:
>
> | Field | Value |
> | - | - |
> | `id` | `obsidian:<path of the note in the vault, with />` |
> | `title` | the frontmatter `title` when it is a non-empty string, else the file name without `.md` |
> | `content` | the file text exactly as read, frontmatter included |
> | `url` | empty |
> | `cognee_node_set` | `obsidian:tag:<tag>` for each frontmatter tag, only when there are any |
> | `cognee_structure` | the note's folders, nearest first, only for a note inside a folder |
>
> * **Tags** come from the frontmatter `tags` key, or the older `tag`, as a list or a single string (one tag, not split on commas). A leading `#` is dropped; non-string entries are skipped. Inline `#tags` in the body, `aliases`, and other properties are not read, and `[[wikilinks]]` stay text rather than becoming edges. Scope a recall to tagged notes with `node_name=["obsidian:tag:work"]`. Adding, removing, or renaming a tag re-ingests the note.
> * **Frontmatter** that cannot be parsed, is not a YAML mapping, or is not closed costs the note only its title and tags; it still syncs with its text unchanged.
> * **Structure**: each folder is `{"kind": "folder", "id": "<folder path>", "name": "<folder name>"}` (see [Connector Modes](https://docs.cognee.ai/integrations/dlt-integration.md#connector-modes)). After each cognify, each note gets a `child_of` edge to its folder and each folder to its parent; folders become `StructureContainer` nodes.
>
> #### How Sync and Forget-on-Delete Work
>
> * **No cursor**: every run walks the whole selection and reads every note. A note whose text did not change makes the same row, Cognee recognises its content hash, and nothing is extracted again, so a quiet sync costs file reads and no LLM calls. File times are never used.
> * **Forgotten notes**: a note an earlier run published that a complete listing no longer contains is emitted as a `_deleted` tombstone. That covers deleted notes, **renamed or moved** notes (the new path is a new document; renaming a folder does this to every note in it), and notes outside a narrowed `folders` selection.
> * **State**: dlt resource state holds the ids of the notes the last complete run published. It is written after the last row, so a run that raises keeps the old state.
>
> #### Errors
>
> The listing is complete before the first row is published, so a run aborts **before anything is synced or forgotten** when:
>
> * `vault_path` is no longer a directory when the run starts: `ObsidianVaultUnavailableError`;
> * the vault root has no entries at all (not even `.obsidian`) although an earlier run published notes. A drive or mount that did not come up looks exactly like this: `ObsidianVaultUnavailableError`. To forget everything on purpose, leave one file or folder in the vault;
> * a folder inside the vault cannot be listed: `ObsidianListingError`, naming the folder relative to the vault;
> * a selected folder is a file, or exists on disk only under another spelling (letter case, Unicode form, a symbolic link): `ObsidianListingError`.
>
> A note that cannot be read or is not valid UTF-8 is neither published nor forgotten: it keeps what memory already holds, is logged with its relative path, and is counted in `failed` and `failed_read`.
>
> `source.cognee_sync_stats` holds counts only: `synced` (notes read and published), `deleted` (tombstones), and `failed` / `failed_read` (unreadable notes; equal today). A normal return can still have skipped notes, so check `failed` after each run. An empty dict means dlt resumed a pending load without extracting this resource: build a fresh source and run again.
>
> #### Limitations
>
> * **A vault with entries but no notes forgets everything** it published before, and so does a `folders` selection whose folders are all gone from disk. A selected folder that does not exist forgets its notes without an error, because a folder deleted on purpose must forget them; once it has no notes left, every run logs a warning naming it until you remove it from `folders`.
> * The Unicode form (NFC or NFD) of a file name is part of the note id, so a sync tool that changes it re-ingests every note and forgets the old ones.
> * Only one active sync per vault and dataset is supported. A large vault is read in full on every run, one note at a time.
> * To erase a note for good, delete it in the vault (or move its folder out of `folders`) and sync: `cognee.forget()` alone leaves dlt's staged copy (`dlt_database_<dataset>`) and the dlt state, and the next sync under the same dataset and `resource_name` rebuilds it. dlt deletes each load package once it has loaded, but a failed package, under `~/.dlt` of the process, keeps its text until the retry.

> [accordion] OneNote connector
>
> The OneNote connector syncs one selected OneNote notebook (its sections, nested section groups, and pages) into cognee memory through Microsoft Graph, incrementally, and forgets a page when Graph gives proof that it was deleted. `onenote_source()` returns a dlt resource you hand directly to `cognee.remember()`, so it takes the [document-mode path](https://docs.cognee.ai/integrations/dlt-integration.md#connector-modes) (its source tag is `onenote`): each page becomes a text document that goes through normal chunking and LLM graph extraction.
>
> > [!WARNING]
> >
> > This connector reads your **personal notes**. Nothing is fetched until you construct a source and call `remember()`. During cognify the page text is sent to your configured LLM and embedding providers, like any other document, and anyone with read access to the target dataset can read it, so keep the notebook in its own dataset.
>
> #### Setup
>
> The OneNote connector is bundled with the Cognee SDK. It uses `httpx`, which a plain `cognee` install already brings, and `beautifulsoup4`, which it does not: install it with `pip install beautifulsoup4` (the `cognee[scraping]` extra also includes it). Without it, the first page the connector fetches fails with an `ImportError`, which `remember()` surfaces wrapped in a `DLTIngestionError`. It needs a core with [`DOCUMENT_SYNC_VERSION`](https://docs.cognee.ai/integrations/dlt-integration#connector-modes) `3` or later and raises a `RuntimeError` on an older one.
>
> Bring a **delegated** Microsoft Graph access token with the `Notes.Read` permission. OneNote's API does not support app-only access. The connector never signs in and never refreshes a token: pass a token string, or a zero-argument callable that returns a valid token for the same account on every call. Only the public-cloud `graph.microsoft.com` endpoint is supported.
>
> #### Example
>
> ```python theme={null}
> import cognee
> from cognee.tasks.ingestion.connectors import list_onenote_notebooks, onenote_source
>
> notebooks = list_onenote_notebooks(token)  # [{"id": ..., "displayName": ...}, ...]
>
> source = onenote_source(
>     token,
>     notebook_id="<notebook id>",
>     account_id="<stable account and tenant id, not the token>",
> )
> await cognee.remember(
>     source,
>     dataset_name="my_onenote",
>     primary_key="id",
>     write_disposition="merge",  # the resource's own default; anything else raises
>     max_rows_per_table=0,
> )
>
> # A normal return is not proof of a finished sync: read the counts.
> stats = source.cognee_sync_stats
> assert stats["failed"] == 0 and stats["complete"] == 1
> ```
>
> One source is one notebook: to sync several notebooks, build one source per notebook id. `list_onenote_notebooks(token, *, http_client=None)` reads only notebook metadata, never page content. Any `write_disposition` other than `merge` stops the sync before any request: the connector raises a `ValueError`, which `remember()` surfaces wrapped in a `DLTIngestionError`.
>
> #### Parameters
>
> `onenote_source()` accepts these parameters:
>
> | Parameter | Default | Description |
> | - | - | - |
> | `token` | — (required) | Access token string, or a zero-argument callable returning one. |
> | `notebook_id` | — (required, keyword-only) | The notebook to sync. |
> | `account_id` | — (required, keyword-only) | Stable, non-secret id of the account and tenant. Never the token or a display name. |
> | `resource_name` | `onenote_<24 hex of account_id and notebook_id>` | Names this connection: it keys the staging table, the sync state, and the cleanup of deleted pages. Normalized to dlt's snake-case table name; must not be empty. |
> | `http_client`, `service` | a client built for the run | Two names for one pre-built `httpx.Client` (tests, proxies). Give at most one. |
> | `check_active` | `None` | Host checkpoint, called before every request and before every row is published. Raising from it aborts the sync. |
> | `max_requests` | `300` | Budget of HTTP attempts in one run, retries included. |
>
> > [!WARNING]
> >
> > Every OneNote source that syncs into one dataset needs **its own `resource_name`** (the default already differs per account and notebook). A run refuses to continue when the stored state belongs to another account or notebook. Renaming a source starts it over, and documents synced under the old name are **not** cleaned up.
>
> #### What Is Ingested
>
> * **One document per page.** Rows are `{id, title, content, url, cognee_structure}`: the Graph page id (the primary key), the page title (`Untitled` when empty), the page's `oneNoteWebUrl`, and the page's HTML body as plain text.
> * **Images and attachments are not downloaded.** Images become `Image: <alt text> (<reference>)` and attachments `Attachment: <name> (<reference>)` lines; links keep their target in parentheses. Handwriting and text inside images are not read.
> * **Structure**: each row carries `cognee_structure` (see [Connector Modes](https://docs.cognee.ai/integrations/dlt-integration.md#connector-modes)), nearest parent first: the section, its section groups from the innermost out, then the notebook, each with its Graph id and name. After each cognify these become `child_of` edges, Notebook ← Section ← Page, with the containers as `StructureContainer` nodes. Renaming a notebook, section, or section group, or moving a page to another section, keeps every page's document id and runs no extraction again; only the `child_of` edges change.
> * **No node set**: rows carry no `cognee_node_set`. People named in a note are text, not typed entities.
>
> #### How It Works
>
> * **Fingerprints**: Graph has no delta feed for OneNote, so every run lists the whole notebook (metadata only) and compares each page with what the last complete run published. A page is fetched and published only when it is new or its fingerprint changed: its `lastModifiedDateTime`, title, link, or the notebook, section groups, and section above it. Unchanged pages are neither fetched nor published again, so a quiet sync extracts nothing. Renaming or moving a container costs one HTML request per page below it, but no re-extraction.
> * **All or nothing for deletions**: deletions are published only after the complete notebook was read and validated. An expected failure (a Graph error, a rate limit, a spent `max_requests` budget, malformed metadata, or an unreadable page) returns normally with `failed > 0` and `complete == 0`, deletes nothing, and checkpoints progress, so the next run resumes without repeating it. A run cut by an interruption (the `max_requests` budget, a rate limit, or a 5xx or transport error that used up its retries) still publishes the pages whose bodies it fetched and records their fingerprints, so the next run skips them and a notebook larger than the budget finishes over a few runs. Page bodies are never kept in state, so a run cut by anything else (for example, malformed metadata) publishes no pages and fetches them again next time. A failure of `check_active` or of a token callable raises unchanged.
> * **A malformed page blocks its notebook**: a page whose `id` or `lastModifiedDateTime` is missing or blank, or whose `title` is missing or not a string, fails the run before anything is published. Fix or remove the page and the next run recovers.
>
> #### Deletions
>
> A page that was synced and is missing from a complete listing is read once more. It is forgotten only when:
>
> * Graph answers 404 or 410 with code **20113** ("the resource specified in the request was deleted"), or
> * the page still exists but now belongs to another notebook (a positive move).
>
> **Code 20102 is not proof of deletion.** It also fits a page this token can no longer see, for example after a scope change. A page that answers 20102 keeps its row and its document and is counted in the `unresolved` stat; the rest of the notebook syncs normally, and the run still reports `complete == 1` and `failed == 0`. Such pages are asked about again in later runs with whatever request budget is left over. A page stops being unresolved once it is listed again or Graph answers 20113 for it. A host that must notice these pages should watch `unresolved`, because nothing else in the stats changes.
>
> Deletions are emitted as `_deleted` tombstones. A notebook you stop syncing keeps its memory.
>
> > [!NOTE]
> >
> > Which of the two codes Graph returns for a page deleted inside a notebook that still exists has not been checked against a live account; the connector has not been run against a live Microsoft account. If Graph answers 20102 for such a page, it stays in memory (counted in `unresolved`) until Graph answers 20113 for it. `cognee.forget()` only removes it until the next sync; see Privacy and `forget()` below.
>
> #### Sync Stats
>
> After a run, the `cognee_sync_stats` dict on the returned resource holds counts only: `scanned` (pages seen), `skipped` (pages unchanged since the last sync), `deleted`, `failed`, `failed_rate_limit`, `failed_budget`, `unresolved`, `requests`, and `complete` (`1` only when the whole notebook was read and published). An empty dict means dlt resumed a pending load without extracting this resource: build a fresh source and run again.
>
> #### Limits and Retries
>
> * **Request budget**: Microsoft Graph throttles OneNote at 120 requests per minute and 400 per hour per app and user. The connector makes one request at a time, and the default `max_requests=300` keeps one run under the hourly allowance. It counts every attempt, retries included, and is not an hourly limiter, so several notebooks or other apps of the same user share the 400. A very large notebook can need several runs; if listing alone spends the budget, raise `max_requests`.
> * **Retries**: a 429, 500, 502, 503, or 504 is retried up to five attempts in total with a 1, 2, 4, 8 second fallback; a `Retry-After` header is honoured when present. The total sleep of one sync is capped at 60 seconds (`RETRY_WAIT_BUDGET_SECONDS`), because the walk holds the dlt staging lock of its dataset and pipeline; once it is spent, the run stops cleanly (`failed_rate_limit` for a 429) and resumes next time.
> * **Redirects are never followed**, and every URL, paging links included, must be under `https://graph.microsoft.com/v1.0/me/onenote/`.
> * **Tokens**: a 401 stops the run with `failed > 0`; refresh the token and run again. Surrounding whitespace is stripped from the token, and a token with whitespace inside is refused before any request. The token is never logged, stored, or put in an error; errors carry a status and a Graph code, never a response body.
>
> #### Privacy and `forget()`
>
> dlt state stores a hash of the account and notebook, page ids, and a fingerprint per page, never page text. Older releases kept the parsed text of pages a cut-short run had fetched in a `pending` state entry; the first run after upgrading drops it, so those pages are fetched once more. If the staging table is deleted while the dlt state is kept, unchanged pages are not published again and stay missing until they change; forgetting the table through `empty_resource` deletes both together (see [Cleaning Up dlt's Staging Data](https://docs.cognee.ai/integrations/dlt-integration.md#cleaning-up-dlt’s-staging-data)). dlt's staging database for the dataset (`dlt_database_<dataset>`) holds the rendered text of every page. dlt's load packages, with the rendered text of each row, live under `~/.dlt` of the process; dlt deletes each one once it has loaded, but keeps a failed one for the retry.
>
> > [!WARNING]
> >
> > `cognee.forget(data_id=...)` or `forget(dataset=...)` removes the documents, graph, and vectors, but **not** the staged copy of the text or the dlt state, so the next sync under the same dataset and `resource_name` rebuilds everything. Deleting a page in OneNote and syncing removes it from the graph and the staged copy; only a failed load package keeps its text until the retry. To erase a whole dataset, call [`drop_dlt_dataset`](https://docs.cognee.ai/integrations/dlt-integration#cleaning-up-dlt’s-staging-data) after `forget(dataset=...)`.
>
> #### Limitations
>
> * One notebook per source, and one active sync per account and dataset.
> * Paging uses `$skip`, so a page created while another is deleted mid-walk can be missed for one run; the next run picks it up.
> * Images, attachments, and handwriting are not read.
> * Not yet verified against a live Microsoft account.

> [accordion] Slack connector
>
> `slack_source()` reads one channel of one Slack workspace with a bot token. A thread (a message with replies) becomes one document, and the messages without replies of one UTC day become one document for that day.
>
> > [!WARNING]
> >
> > This reads the messages of the channel, the names of their authors, and the names of attached files, never their content. The text goes to your configured LLM and embedding providers, and anyone with read access to the dataset can see it.
>
> This is the connector you drive from your own code with a bot token you hold. To ask, save and recall Cognee memory from Slack itself, see the [Slack integration](https://docs.cognee.ai/integrations/slack-integration.md).
>
> #### Setup
>
> The connector is part of the Cognee SDK (Cognee 1.6.8 or newer) and needs no extra.
>
> 1. Create a Slack app at [api.slack.com/apps](https://api.slack.com/apps) with the bot scopes `channels:history`, `channels:read` and `users:read` (`groups:history` and `groups:read` for a private channel), install it into your workspace, and copy the bot token (`xoxb-...`).
> 2. Invite the app to the channel (`/invite @YourApp`).
> 3. Export `SLACK_BOT_TOKEN`, `SLACK_TEAM_ID` (`T...`) and `SLACK_CHANNEL_ID` (`C...`).
>
> #### Example
>
> This script syncs one channel into the `slack_channel` dataset and asks it a question.
>
> ```python theme={null}
> import asyncio
> import os
>
> import cognee
> from cognee.tasks.ingestion.connectors import slack_source
>
> # Keep the channel in its own dataset so it is easy to inspect and forget.
> DATASET_NAME = "slack_channel"
>
> # Routing kwargs for remember(). Pass the same ones on every later sync.
> #   write_disposition="merge" is what the resource declares, so leaving it out keeps it
> #     too. Never pass "replace": it would wipe the
> #     synced channel on the next sync.
> #   max_rows_per_table=0 keeps every staged row in view, so forget-on-delete compares
> #     against the whole channel.
> SLACK_REMEMBER_KWARGS = {
>     "primary_key": "id",
>     "write_disposition": "merge",
>     "max_rows_per_table": 0,
>     "self_improvement": False,
> }
>
>
> async def main():
>     token = os.environ.get("SLACK_BOT_TOKEN")
>     team_id = os.environ.get("SLACK_TEAM_ID")
>     channel_id = os.environ.get("SLACK_CHANNEL_ID")
>     if not (token and team_id and channel_id):
>         print(
>             "Set SLACK_BOT_TOKEN, SLACK_TEAM_ID and SLACK_CHANNEL_ID.\n"
>             "See the setup steps in this file's docstring, then re-run."
>         )
>         return
>
>     # Start from a clean slate so the demo is reproducible.
>     await cognee.prune.prune_data()
>     await cognee.prune.prune_system(metadata=True)
>
>     # The resource name keys the staging table and the sync state: one per channel.
>     source = slack_source(
>         access_token=token,
>         team_id=team_id,
>         channel_id=channel_id,
>         resource_name=f"slack_channel_{channel_id.lower()}",
>     )
>
>     print("\n=== Slack sync ===")
>     result = await cognee.remember(source, dataset_name=DATASET_NAME, **SLACK_REMEMBER_KWARGS)
>     print(result)
>     # A run cut short by the request budget or a rate limit reports failed_budget or
>     # failed_rate_limit here; run the script again (without the prune) to continue.
>     print("Sync stats:", source.cognee_sync_stats)
>
>     answer = await cognee.recall(
>         query_text="What did the channel decide recently, and who decided it?",
>         datasets=[DATASET_NAME],
>         node_name=[f"slack:channel:{channel_id}"],
>     )
>     print(answer[0].text if answer else "No answer.")
>
>
> if __name__ == "__main__":
>     asyncio.run(main())
> ```
>
> If any of the three environment variables is missing, the script prints a message and returns before fetching anything. It starts with two `prune` calls so the demo is reproducible: remove them before you run it again, or every document synced so far goes through graph extraction again. `recall()` is scoped to the channel's node set, `slack:channel:<channel id>`.
>
> #### What a Sync Reads Again
>
> Later syncs render again only the threads and days that changed: a new message or reply, or an edited top-level message. An edited reply is read again only when the host passes its thread in `changed_roots`, a `slack_source()` argument, which the Slack integration does from Slack's message events.
>
> #### Run Budget
>
> A large channel finishes its first sync over several runs. Each run stops after `max_requests` Slack API requests (1500 by default, a `slack_source()` argument) or 600 seconds, and the next run resumes where it stopped. A run cut short by the request budget or a rate limit reports `failed_budget` or `failed_rate_limit` in `cognee_sync_stats`.
>
> #### Deletions
>
> A message deleted in Slack is forgotten on the sync that next walks the whole channel. Deletion happens only on a complete walk: a run cut short forgets nothing.

> [accordion] Telegram connector
>
> `telegram_source()` reads the messages a bot sees in the groups, supergroups and channels it is in. One source is one bot token, and each message with text or a caption becomes one document.
>
> > [!WARNING]
> >
> > This connector reads every message the bot can see in the selected chats: message text, captions, the display names and `@handles` of senders, forwarded authors and the people replied to, chat titles, and, with `include_private=True`, private chats. All of it goes to your configured LLM and embedding providers, and anyone with read access to the dataset can read it. Group members never consented to that individually: tell them the bot is there. Logs carry counts only.
>
> #### Setup
>
> The connector is part of the Cognee SDK (Cognee 1.6.9 or newer) and needs no extra and no separate package: the Bot API client uses the standard library's `urllib`. It needs a core with `DOCUMENT_SYNC_VERSION` `3` or later and raises a `RuntimeError` on an older one.
>
> Auth is a **bot token from @BotFather**. Telegram has no OAuth for bots, so there is no authorize step and no token to refresh; a token does not expire, and a revoked one surfaces as `failed_auth`. The connector never reads the token from the environment: pass it as `token`.
>
> 1. Create a **dedicated** bot with @BotFather and copy its token. Updates are read with `getUpdates`, which fails with HTTP 409 while the bot has a webhook or while another process polls it. The connector never deletes a webhook.
> 2. In @BotFather run `/setprivacy` and choose "Disable", or make the bot an admin of the chat. In groups a bot only sees what privacy mode allows: commands and replies to it. The connector logs a warning when privacy mode is on and reports it as `privacy_mode=1` in the sync stats.
> 3. Add the bot to your group, then send a few messages. A bot only sees messages sent after it joined: there is no history backfill.
> 4. Export the token: `export TELEGRAM_BOT_TOKEN="123456789:AA..."`
>
> #### Example
>
> This script syncs one page of updates into the `telegram_chat` dataset and asks the chat a question.
>
> ```python theme={null}
> import asyncio
> import os
>
> import cognee
> from cognee.tasks.ingestion.connectors import telegram_source
>
> # Keep the chat in its own dataset so it is easy to inspect and forget.
> DATASET_NAME = "telegram_chat"
>
> # Routing kwargs for remember(). Pass the same ones on every later sync.
> #   write_disposition="merge" is what the resource declares, so leaving it out keeps it too.
> #     Never pass "replace": it would wipe every message of
> #     earlier syncs on the next run, because Telegram never sends an old update again.
> #   max_rows_per_table=0 guarantees no per-table read cap applies, so orphan cleanup
> #     (forget-on-delete) compares against the entire synced corpus.
> TELEGRAM_REMEMBER_KWARGS = {
>     "primary_key": "id",
>     "write_disposition": "merge",
>     "max_rows_per_table": 0,
>     "self_improvement": False,
> }
>
>
> async def main():
>     token = os.environ.get("TELEGRAM_BOT_TOKEN")
>     if not token:
>         print(
>             "TELEGRAM_BOT_TOKEN is not set.\n"
>             "See the setup steps in this file's docstring, then re-run."
>         )
>         return
>
>     # Start from a clean slate so the demo is reproducible.
>     await cognee.prune.prune_data()
>     await cognee.prune.prune_system(metadata=True)
>
>     # chats=None syncs every group, supergroup and channel the bot is in. Pass chat ids or
>     # "@usernames" to scope it; a chat dropped from the list later is forgotten.
>     source = telegram_source(token=token)
>
>     # ── Sync: read one page of updates ────────────────────────────────────
>     print("\n=== Telegram sync ===")
>     result = await cognee.remember(
>         source,
>         dataset_name=DATASET_NAME,
>         **TELEGRAM_REMEMBER_KWARGS,
>     )
>     print(result)
>     print("Sync stats:", source.cognee_sync_stats)
>
>     answer = await cognee.recall(
>         query_text="What was discussed in the chat?",
>         query_type=cognee.SearchType.GRAPH_COMPLETION,
>         datasets=[DATASET_NAME],
>     )
>     print(answer[0].text)
>
>
> if __name__ == "__main__":
>     asyncio.run(main())
> ```
>
> It starts by wiping the whole Cognee instance, not just this dataset, so run it against a throwaway instance and remove the two `prune` calls before syncing for real. Each run reads the next page of updates. The script is also in the Cognee repository as [`examples/guides/telegram.py`](https://github.com/topoteretes/cognee/blob/dev/examples/guides/telegram.py).
>
> #### Parameters
>
> `write_disposition="merge"` is the resource's own default. Never pass `"replace"`: Telegram never sends an old update again, so it would wipe every message of earlier syncs.
>
> `telegram_source()` accepts these keyword-only parameters:
>
> | Parameter | Default | Description |
> | - | - | - |
> | `chats` | `None` | Chats to sync: a non-empty list or tuple of numeric chat ids (`-1001234567890`, or the same as a string) and `@username`s, for example `[-1001234567890, "@my_channel"]`. `None` syncs every group, supergroup, and channel the bot is in. |
> | `token` | — | The bot token, `<bot id>:<secret>`. Required unless `service` is given. |
> | `service` | built from `token` | A pre-built client from `build_telegram_service(bot_token)`. A client of your own must accept `call(method, params, *, check_active, budget)` and run `check_active` before each attempt. |
> | `resource_name` | `telegram_<bot id>` with `token`; required with `service` | Names this connection: the staging table, the dlt state, and the pipeline scope. Lowercase letters, digits, and underscores, starting with a letter. |
> | `check_active` | `None` | Host checkpoint, called before every request attempt and retry wait and around every row. What it raises stops the run as it is. |
> | `include_private` | `False` | With `chats=None`, also sync private chats (messages people send the bot). A private chat whose id is listed in `chats` is synced either way. |
>
> Pass `token` or `service`, not both. A bare string for `chats`, an empty list, a blank entry, a `t.me/` link, or a token of the wrong shape raises `ValueError` when the source is built (the token is never echoed). Building the source makes no request.
>
> A `@username` names a **chat**, not a name: the first time it is seen (or looked up with `getChat` at the start of the run), it is bound to that chat and keeps selecting it through renames, and another chat that later takes the freed username is not selected by it. A private chat is selected by id only. For the full binding and rename rules, see the [connector README](https://github.com/topoteretes/cognee/blob/dev/cognee/tasks/ingestion/connectors/telegram.md).
>
> **Hosts.** The connector is registered as the `telegram` provider in `_PROVIDERS` (`cognee.modules.integrations.ingestion`), an API-key-style provider whose service builder wraps the token the user pasted and whose error classifier (`classify_sync_error`) maps a raised run to its stats key. Key each connection by `telegram_account_id(service, check_active=...)`, the bot's id from `getMe`: a connection whose stored state belongs to another bot is refused with `failed_bot_mismatch` on every run.
>
> #### What Is Ingested
>
> * **One document per message** that has text or a caption. Rows are `{id, title, content, url, cognee_node_set, cognee_structure}`.
> * **`id`** is `<chat id>:<message id>` (message ids are only unique inside a chat). **`title`** is `<first line> (<chat> #<message id>)`, the first line shortened to 80 characters. **`url`** is `https://t.me/<username>/<id>` for a public chat, `https://t.me/c/<id>/<id>` for a private supergroup or channel, and none for a basic group or a private chat.
> * **`content`** is a header block (`Chat:`, `From:`, then `Handle:`, `Date:`, `Forwarded from:`, `Edited:`, `In reply to` when they apply), a fixed `--- message ---` line, then the text. No numeric user id or phone number is rendered. A quoted reply is cut at 200 characters.
> * **Media is not downloaded.** A media message is its caption, prefixed with its kind (`[photo] ...`). Service messages (joins, pins) and media without a caption are skipped.
> * **Node set and structure**: each row carries `cognee_node_set` `["telegram:chat:<root chat id>"]`, so a `recall()` can be scoped to one chat with `node_name=["telegram:chat:-1001234567890"]`, and `cognee_structure` with the chat as its container, so each message gets a `child_of` edge to a chat `StructureContainer`. Both use the root of the chat's upgrade chain, so a group upgraded to a supergroup stays one chat.
>
> #### How It Works
>
> * **One page per run**: a run calls `getMe`, `getChat` once per selected `@username` not bound yet, and then `getUpdates` once, for up to 100 updates (the Bot API maximum). Asking for the next page confirms the previous one, so a run never asks for a second page: its updates are confirmed by the next run, whose offset comes from the state dlt saved with this run's rows. A run that stops or raises saves no state, and the next run reads the same page, so nothing is lost.
> * **Edits** arrive with the same message id and replace the row. An edit that removes the text (a caption deleted from a photo) tombstones the message.
>
> #### Deletions
>
> Forget-on-delete is per chat. Only three things forget data: the bot being removed from a group, supergroup, or channel; an edit that takes the text away; and a chat leaving your selection (`chats` narrowed, or `include_private` turned off). A user blocking the bot in a private chat forgets nothing.
>
> Deleted messages and deleted chats stay in memory. The Bot API sends a bot no event when a message is deleted, and none is known for a deleted chat. Remove such data yourself: take the chat out of `chats`, remove the bot from the chat, or `forget` it.
>
> `cognee.forget(data_id=...)` removes one message from memory, but its staging row stays and the next sync builds it again; remove the chat from the selection, or the bot from the chat, instead. For Telegram the staging table is the only copy of the corpus, since Telegram never delivers an update twice, so `forget(dataset=...)` followed by a sync rebuilds every message as of the last sync. To erase a whole dataset, call [`drop_dlt_dataset`](https://docs.cognee.ai/integrations/dlt-integration#cleaning-up-dlt’s-staging-data) after `forget(dataset=...)`.
>
> #### Sync Stats
>
> After a run, `source.cognee_sync_stats` holds counts only, with every key present:
>
> * `scanned` (message rows emitted), `deleted` (tombstones), and `skipped` (updates that became no row, always the sum of the four reason keys that follow).
> * `skipped_unselected` (messages of a chat outside the selection), `skipped_unsupported_type` (a message of a kind other than text with no caption), `skipped_empty_content` (a service message or a blank text), `skipped_unread_update` (an update of a type the connector does not ask for).
> * `privacy_mode`: `1` when `getMe` returns `can_read_all_group_messages` as JSON `false`. It is meaningful only on a run with `failed` 0, since a run that fails before or at `getMe`, or with `failed_bot_mismatch`, leaves it 0.
> * `backlog`: `1` when the run read a full page and more updates may be waiting.
> * `gap`: update ids that may have been lost, counted only when the last update the connection saw is more than 24 hours old.
> * `failed`, and one reason key per failure: `failed_auth` (token rejected), `failed_conflict` (HTTP 409: a webhook or another poller), `failed_rate_limit`, `failed_unavailable` (5xx or no answer after retries), `failed_provider` (any other Telegram-side failure; the run raises), `failed_unexpected` (a defect of the source, raised as `TelegramUnexpectedError`), and `failed_bot_mismatch` (the state belongs to another bot).
>
> A run that stops keeps its cursor: the next sync reads the same page.
>
> #### Limits and Retries
>
> * **Throughput**: one page per run means at most 100 updates per run per bot, and Telegram drops undelivered updates after about 24 hours. Sync at least hourly for chats with more than 100 messages a day; a daily sync keeps up with 100. A run that read a full page reports `backlog=1` and logs a warning; when it repeats, sync more often or updates will be lost. A nonzero `gap` is a possible loss, not proof.
> * **Retries**: each request makes up to 5 attempts, with Telegram's `retry_after` on a 429 and a 1, 2, 4, 8 second backoff on a 5xx, no answer, or a 429 without a usable `retry_after` (NaN, a negative value, or anything that is not a number). A `retry_after` beyond the largest float (Infinity included) fits no budget, so the run stops with `failed_rate_limit`. The total sleep of one run is capped at 60 seconds, because the walk holds the dlt staging lock of its dataset and pipeline; a wait that does not fit stops the run with `failed_rate_limit` (`failed_unavailable` for a 5xx) and delays the sync without dropping anything. Each request has a 30 second socket timeout.
> * **One bot, one connection**: two connections polling the same bot steal each other's updates. Several bots in one chat each need their own `resource_name` (the default already differs per bot), and synced into one dataset they give one document per message per bot.
>
> #### Limitations
>
> * No history backfill: a bot sees only messages sent after it joined.
> * Deleted messages and chats are not forgotten (Bot API limit).
> * Media files are never downloaded.
> * This port has not been run against a live bot; the community connector it was ported from was.

> [accordion] Vercel connector
>
> `vercel_source()` reads one Vercel project: the project, each of its deployments and, if you ask for it, the build output of its failed deployments. Each one becomes a document, with a deployment's environment, state, branch, commit sha, commit message, author login and error code in its first lines. It never changes anything in Vercel.
>
> > [!WARNING]
> >
> > Project settings are read by name only: environment variables, deploy hooks, protection bypass keys, trusted IPs, build commands and every email address are never copied. Build logs are off by default because they can contain secrets: a build prints whatever it prints, and Vercel redacts only secret values of 32 characters or more. With `include_build_logs=True`, their text goes to your LLM and embedding providers along with the rest of what is read, and anyone with read access to the dataset can read it.
>
> #### Setup
>
> The connector is bundled in the Cognee SDK (Cognee 1.6.9 or newer) as `from cognee.tasks.ingestion.connectors import vercel_source` and needs no extra.
>
> It is also its own package on PyPI, `cognee-connector-vercel`. The base install has no Cognee runtime, and the `cognee` extra adds Cognee (`cognee>=1.6.5,<2`) to ingest into it. It supports Python 3.10 to 3.14:
>
> ```bash theme={null}
> pip install cognee-connector-vercel
> # To ingest into Cognee:
> pip install "cognee-connector-vercel[cognee]"
> ```
>
> The package imports as `from cognee_connector_vercel import vercel_source`. It needs a Cognee host with `DOCUMENT_SYNC_VERSION` `3` or later (Cognee 1.6.6rc1 or newer). The `cognee` extra still accepts Cognee 1.6.5, so upgrade an existing 1.6.5 install. On an older host it raises a `RuntimeError` before it contacts Vercel. The package exports `vercel_source`, `build_vercel_service`, and `CONNECTOR`. Hosts discover `CONNECTOR` through the `cognee.connectors` entry point and `vercel_source` through `cognee.sources`. `CONNECTOR` describes an API-key connector: there is no OAuth flow, no credential store, and no `cognee.integrations` entry point, and it does not list projects. You supply the token and name the project and its team or account yourself.
>
> To run the example:
>
> 1. Create a Vercel access token at [vercel.com/account/tokens](https://vercel.com/account/tokens), scoped to the team, with an expiry.
> 2. Find the project id (`prj_...`) under the project's **Settings → General**.
> 3. Export the credentials the script reads:
>
>    ```bash theme={null}
>    export VERCEL_TOKEN="..."
>    export VERCEL_PROJECT_ID="prj_..."
>    export VERCEL_TEAM_ID="team_..."      # or VERCEL_ACCOUNT_ID=<your user id> on Hobby
>    ```
>
> #### Example
>
> This script syncs one project into the `vercel_demo` dataset, asks which deploy failed and why, then syncs and asks again. Run it after a failed deploy to see the error in the answer.
>
> ```python theme={null}
> import asyncio
> import os
>
> import cognee
> from cognee.tasks.ingestion.connectors import vercel_source
>
> # One dataset per Vercel team (or personal account), so it is easy to inspect and forget.
> DATASET_NAME = "vercel_demo"
>
> QUESTION = "Which production deployment failed most recently, with what error, and which commit?"
>
>
> async def sync_and_ask() -> None:
>     project_id = os.environ["VERCEL_PROJECT_ID"]
>     source = vercel_source(
>         # One name per user and project: it names the staging table and the sync state.
>         resource_name=f"vercel_{project_id.lower()}",
>         project_id=project_id,
>         team_id=os.environ.get("VERCEL_TEAM_ID"),
>         account_id=os.environ.get("VERCEL_ACCOUNT_ID"),
>         access_token=os.environ["VERCEL_TOKEN"],
>     )
>     # Pass the same arguments on every later sync.
>     await cognee.remember(
>         source,
>         dataset_name=DATASET_NAME,
>         primary_key="id",
>         # The resource declares "merge", so leaving it out keeps it too.
>         # Never pass "replace": it would wipe the synced project on the next sync.
>         write_disposition="merge",
>         # Read the whole staging table back, so a deletion is seen.
>         max_rows_per_table=0,
>         self_improvement=False,
>     )
>     print("Sync stats:", source.cognee_sync_stats)
>
>     answer = await cognee.recall(
>         query_text=QUESTION,
>         query_type=cognee.SearchType.GRAPH_COMPLETION,
>         datasets=[DATASET_NAME],
>     )
>     print(f"Q: {QUESTION}\nA: {answer}\n")
>
>
> async def main() -> None:
>     await sync_and_ask()
>     # Nothing changed at Vercel: every row is skipped and nothing is extracted again.
>     await sync_and_ask()
>
>
> if __name__ == "__main__":
>     asyncio.run(main())
> ```
>
> Pass `team_id` for a team project, or `account_id` with your user id for a personal (Hobby) account. Because the state, error code and commit are in each deployment's text, the answer can name the failed deploy and the commit behind it. On the second run nothing changed at Vercel, so every row is skipped and nothing is extracted again.
>
> #### Parameters
>
> `write_disposition="merge"` is the resource's own default; passing it is harmless (with the standalone package on Cognee before 1.6.8, pass it). To sync several projects of one team into the same dataset, use one source per project, each with its own `resource_name`, and keep one dataset per team (or personal account).
>
> `vercel_source()` accepts these keyword-only parameters:
>
> | Parameter | Default | Description |
> | - | - | - |
> | `resource_name` | — (required) | Stable name of this connection and project. It names the staging table and scopes the sync state. |
> | `project_id` | — (required) | The project id (`prj_...`), never its name. |
> | `team_id` | `None` | The team that owns the project, sent as `teamId` on every call. Leave it out for a personal account. |
> | `account_id` | `team_id` | The account the project must belong to. A personal account passes its user id. One of `team_id` and `account_id` is required. |
> | `access_token` | `None` | A Vercel personal access token, or the OAuth access token of a Vercel Integration. |
> | `service` | `None` | A pre-built client to use instead of `access_token` (see `build_vercel_service`). |
> | `check_active` | `None` | Host checkpoint, called before every request attempt and retry wait and around each row. |
> | `max_requests` | `None` (no limit) | Request budget for one run. `0` defers the run without any request, and `1` is refused with a `ValueError`. |
> | `lookback_days` | `None` (every deployment) | Only read deployments created in this many days. A deployment that leaves the window keeps its document and is no longer checked for deletion. |
> | `include_build_logs` | `False` | Also read the build output of failed deployments. |
>
> #### Sync and Deletions
>
> A re-sync extracts only the deployments whose text changed, so an unchanged project costs no LLM calls. A deployment Vercel deletes leaves memory on the next sync; it is never forgotten just for being old.
>
> For the documents and fields it reads, how a sync resumes, deletion handling, sync stats, and error handling, see the [package README](https://github.com/topoteretes/cognee/tree/dev/cognee-connectors/connectors/vercel).

> [card] [dlt (Data Load Tool)](https://docs.cognee.ai/integrations/dlt-integration.md)
>
> How dlt sources, write dispositions and document-mode rows work

> [card] [Integrations](https://docs.cognee.ai/integrations/index.md)
>
> Connect accounts to a running Cognee server through OAuth

> [card] [Remember](https://docs.cognee.ai/core-concepts/main-operations/remember.md)
>
> All `remember()` parameters, including the dlt options

> [card] [Forget](https://docs.cognee.ai/core-concepts/main-operations/forget.md)
>
> Remove a synced dataset when you are done


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.