cognee.add()
Description
Ingest data into a dataset, ready forcognify() to turn into memory.
add() is the staging step of the memory API: one call takes text, files, folders,
uploads, web pages, code repositories or database tables, and leaves each one as a
stored document in the dataset, with its original, its text, its metadata and a
stable data_id. It builds no graph and computes no embeddings; cognify() does that
over what add() stored, and remember() runs add() + cognify()
(and improve()) in one call. Call add() directly to stage data before a separate
cognify(), or for the options remember() does not forward (skip_connection_test,
and column_value_columns as a bare keyword argument; remember() takes it inside dlt_config).
What add() handles for you:
- Dataset and permissions: the dataset is looked up among the user’s own datasets
by name (or by
dataset_id, which also reaches a dataset shared with the user), and the user must have write permission on it. A name that does not exist yet creates the dataset and gives its creator read, write, delete and share permission on it. Adataset_idyou cannot write to, including one that matches no dataset, raisesPermissionDeniedError. - Loading: folders are expanded (subfolders included) and every item is handed to
the loader registered for its type, so the dataset holds the item’s text next to its
original;
preferred_loaderssteers that choice. - Storage and identity: originals and text are stored under Cognee’s data root
(local or S3). Items are matched by content hash within the dataset, so adding the
same content again returns the stored document’s
data_idinstead of duplicating it. - Run tracking: ingestion is a pipeline run on the dataset (
add_pipeline), recorded and reported like cognify’s runs. It takes the same per-dataset lock, so within one process add, cognify and forget on one dataset run one after another.
cognee.serve(),
add() sends only data and dataset_name to that server and drops the other options.
branch is the exception: it raises ValueError instead of being dropped.
Prerequisites:
- LLM_API_KEY:
add()stages data and makes no LLM call of its own, so its provider preflight never checks the LLM half — a missing key is not an error here for any input, including a file whose loader has not been resolved yet. Embedding configuration is checked either way. Whether a key is needed is decided where the LLM is actually used: the graph build that follows needs one unless it runs on thegliner_demoextractor, which is what theautodefault resolves to when no key is configured; and image, audio, and video files need one during ingestion itself, because their loaders transcribe or describe the file with the LLM. A media file added with no usable LLM raisesLLMAPIKeyNotSetErrorfrom the loader — before it reads the file — rather than from the preflight. See Loaders for the message and Recall Without an LLM Key for the keyless path. - Database Setup: Relational and vector databases must be configured
- User Authentication: Uses default user if none provided (created automatically)
- Text strings: Direct text content (str) - any string that is not a
file://,s3://,http://orhttps://URL and does not point to an existing local file. An absolute-looking string that is not an existing file (for example"/remember to call the dentist") is ingested as text content on every platform, including Windows, while local file paths are accepted. With ACCEPT_LOCAL_FILE_PATH=false, a string that is only a path (“/etc/passwd”) raises IngestionError whether or not it exists. - File paths: Local file paths as strings in these formats:
- Absolute paths: “/path/to/document.pdf” (treated as a file reference only when the file exists)
- File URLs: “file:///path/to/document.pdf” or “file://relative/path.txt”
- S3 paths: “s3://bucket-name/path/to/file.pdf”
- Upload objects: Objects exposing
.fileand.filename(for example FastAPIUploadFile). In the default blocking mode, a plain file handle such asopen("file.pdf", "rb")is not accepted and raisesIngestionError: Data type not supported— pass the path as a string instead. - Code repository URLs:
"https://github.com/<owner>/<repo>"(or agitlab.comproject, or anyhttp(s)URL ending in.git) is shallow-cloned and ingested as ONE code-repo item thatcognify()runs through the enola code graph pipeline (cross-file edges), plus the repository’s documents — the same result as adding a local code project directory. RequiresgitonPATH; allowed by default from the SDK and CLI, while an API server needsALLOW_HTTP_REQUESTS=true. Passbranchto clone a branch other than the remote’s default. See Code repository URLs below. - Web URLs:
"https://example.com/page"is fetched and ingested as a page, through Tavily whenTAVILY_API_KEYis set, else Keenable whenKEENABLE_API_KEYis set, else the built-in crawler. API calls needALLOW_HTTP_REQUESTS=trueon the server; the refusal comes before any work starts, also withrun_in_background=True. - Database connection strings:
"postgresql://...","mysql://...","sqlite:///path/to/file.db"and the other supported schemes are read through dlt. The SDK, CLI and MCP server ingest them by default; the API server refuses them unlessALLOW_DATABASE_INGESTION=true(see the note under Supported Input Types). - Lists: Multiple files or text strings in a single call
ACCEPT_LOCAL_FILE_PATH=true; the SDK and CLI accept them by default. See
Local File System Access.
Supported File Formats:
- Text files (.txt, .md); CSV files are read through dlt as table rows
- PDFs (.pdf)
- Images (.png, .jpg, .jpeg) - transcribed via vision models, with an optional local OCR pass
- Audio files (.mp3, .wav) - transcribed to text
- Code files (.py, .js, .ts, etc.) - stored as code, so cognify builds a code graph from
them without an LLM;
preferred_loaders=["text_loader"]treats one as a plain document - Office documents (.docx, .pptx) - with the
docsordoclingextra
- Checks before any write: remote-fetch permission, server-path screening, provider config, and the dataset’s write permission (creating the dataset if it is new).
- Source expansion: database connection strings and dlt resources become individual items.
- Changed-file check: a file the dataset holds with other content refuses the whole call (see Changed files are refused), before any item is written; folders are checked file by file.
- Ingestion: the pipeline expands folders, repository URLs and CSV files, then each
item is loaded, stored and recorded as a
Datarow of the dataset, tagged withnode_setandimportance_weight.
- Single text string: “Your text content here”
- Absolute file path: “/path/to/document.pdf” (must exist; otherwise the string is ingested as text, unless ACCEPT_LOCAL_FILE_PATH=false refuses it)
- File URL: “file:///absolute/path/to/document.pdf” or “file://relative/path.txt”
- S3 path: “s3://my-bucket/documents/file.pdf”
- List of mixed types: [“text content”, “/path/file.pdf”, “file://doc.txt”]
- Upload object exposing
.fileand.filename(a plainopen(..., "rb")handle raisesIngestionError: Data type not supported; pass the path instead) - url: A web link url (https or http); a GitHub/GitLab repository URL is
cloned and indexed as a code graph instead of fetched as a page
dataset_name: Name of the dataset to store data in. Defaults to “main_dataset”.
Create separate datasets to organize different knowledge domains.
user: User object for authentication and permissions. Uses default user if None.
Default user: “default_user@example.com” (created automatically on first use).
Users can only access datasets they have permissions for.
node_set: Optional NodeSet names to tag these documents with. cognify() links their
documents and chunks to those NodeSet nodes, so
recall(node_name=...)/search(node_name=...)can scope retrieval to them. Not an access-control mechanism. Re-adding an existing document withoutnode_setkeeps its stored tags;[]clears them. vector_db_config: Optional configuration for vector database (for custom setups). graph_db_config: Optional configuration for graph database (for custom setups). dataset_id: Optional specific dataset UUID to use instead of dataset_name; the way to write to a dataset another user shared with you. An id you cannot write to, including one that matches no dataset, raisesPermissionDeniedError. preferred_loaders: Loader names to try first, each optionally with that loader’s options, as a dict{"dlt_csv_loader": {...}}or a list["csv_loader"]/[{"dlt_csv_loader": {...}}](strings and dicts may be mixed; a loader named twice keeps its last options). Web-page extraction rules go here too, with thescrapingextra:{"beautiful_soup_loader": {"extraction_rules": ...}}. importance_weight: The documents’ importance, 0 to 1 (default 0.5). The hybrid retriever (the default search type) scales a chunk’s ranking score by a factor from 0.75 (weight 0) to 1.25 (weight 1). extraction_rules / tavily_config / soup_crawler_config: accepted and ignored. Pass extraction rules throughpreferred_loaders(above); Tavily is configured byTAVILY_API_KEY. branch: Branch to clone for the GitHub/GitLab repository URL(s) indata, instead of the remote’s default. Each branch is cloned into its own directory, so adds on different branches never touch each other’s clone. A dataset holds one branch of a URL at a time: adding it on another branch re-indexes the code graph, but the documents ingested from the previous branch stay. A missing branch raisesCodeRepositoryError; not supported while connected to a remote instance.
- Pipeline run ID for tracking
- Dataset ID where data was stored
- Processing status and any errors
data_ids: the id of every data item this call stored (or found already present with identical content). Use these for laterupdate()/datasets.delete_data()calls instead of working ids out from the content. They do not line up with the inputs: a directory yields one id per file, and duplicates and items that failed are left out.Nonewithrun_in_background=True, since the items are not stored yet whenadd()returns- Execution timestamps and metadata
cognify() to process the ingested content:
- LLM_API_KEY: API key for your LLM provider (OpenAI, Anthropic, etc.). add() needs it only for images, audio and video; when unset, the cognify() that follows runs on local models (GLiNER extraction, fastembed embeddings).
- LLM_PROVIDER: “openai” (default), “anthropic”, “gemini”, “ollama”, “mistral”, “bedrock”
- LLM_MODEL: Model name (default: “openai/gpt-6-luna”)
- DEFAULT_USER_EMAIL: Custom default user email
- DEFAULT_USER_PASSWORD: Custom default user password
- VECTOR_DB_PROVIDER: “lancedb” (default), “pgvector”
- GRAPH_DATABASE_PROVIDER: “ladybug” (default), “neo4j”
- TAVILY_API_KEY: YOUR_TAVILY_API_KEY
- KEENABLE_API_KEY: YOUR_KEENABLE_API_KEY
- COGNEE_REPOS_DIR: Directory that repository URLs are shallow-cloned into
(default:
~/.cognee/repos)
Changed files are refused
add() creates documents; it never updates one. A file that already exists in the dataset — the same local path, or the same filename for an upload — with different content raises DocumentUpdateRequiredError (HTTP 409 on POST /api/v1/add). The error names every such file with its data_id and tells you how to replace it: the SDK message gives the exact cognee.update(data_id=..., data=..., dataset_id=...) call, and the HTTP message gives the PATCH /api/v1/update?data_id=...&dataset_id=... request. update() keeps the document’s id and replaces its graph in place.
- The whole request is refused. The check runs once over every item before ingestion starts, so a batch with one changed file writes nothing.
- Identical content is still a no-op, as before.
- Raw text never conflicts: a text string is named by its content hash, so changed text is a new document.
- Pinned items are exempt: DLT and code-repository manifests, and
update()’s own re-add, name their document explicitly. - Only your own files match: the lookup is scoped to the dataset, owner, and tenant, and
s3://objects and repository URLs are not checked.
Parameters
Data to ingest. Accepts text strings, file paths (local, S3, or URLs), upload objects exposing
.file/.filename, DataItem objects, or lists of any of these. A plain open(..., "rb") file handle is not accepted and raises IngestionError: Data type not supported — pass the path as a string instead. Over a serve() connection it is the reverse: a path string is uploaded as literal text, so pass an open file object to upload a file.DataItem is a lightweight wrapper that lets you attach per-item metadata, human-readable label, and an optional stable data_id. Import it from cognee.tasks.ingestion.data_item:label and external_metadata are stored on the relational Data record. label is not propagated into the knowledge graph automatically.With incremental loading on (the default), re-adding a document the dataset already holds is skipped, so its label, external_metadata and node_set stay as they are; change them with update(). When an existing document is ingested again (update()’s full rebuild, or add() with both incremental_loading=False and data_cache=False), these fields are treated as a PATCH: a field you do not pass keeps its stored value, an explicit empty value (label="", external_metadata={}, node_set=[]) clears it, and a value replaces it. The call-level node_set and the item’s own count together. Metadata derived from the content always refreshes, and _cognee.source_uri takes the new content’s location; new content without one (an upload, raw text) drops the old one. update() follows the same rule.Pass literal_text=True (default False) to force a string data value to be stored verbatim as a text document instead of being resolved as a locator: with the flag set, a value such as "https://example.com/report" or "/tmp/report.pdf" is ingested as that text rather than fetched or read from disk. Use it for text you did not author — a synced document’s body, for instance — where a value that happens to look like a URL or path must not be followed. The flag holds on every storage path: the default add() path and its incremental pre-save, items with a pinned data_id, and cognee.update().One check still runs ahead of it: the changed-file refusal above resolves a string as a local path without consulting literal_text, so a literal string without a pinned data_id that names an existing local file, or a directory containing one, that the dataset already holds with different content can still raise DocumentUpdateRequiredError.external_metadata is copied onto every chunk the item produces at chunking time, so it travels with the chunk on both the graph node and the vector payload. It is never embedded and never part of the chunk id, so it stays invisible to matching and ranking — you cannot search by a metadata value. What it enables is surfacing: HYBRID_COMPLETION can return allowlisted keys alongside the passages it retrieves. Because the copy is stamped when chunks are created, items ingested before this behavior existed carry no metadata on their chunks until they are updated with cognee.update() — re-adding unchanged content is a no-op.Use node_set when you need tags that flow into the graph and can be used for scoped queries.Name of the dataset to add data to. The name is looked up among your own datasets, and you need write permission on it; a name that does not exist yet creates the dataset and gives you read, write, delete and share permission on it. To write to a dataset another user shared with you, pass its
dataset_id.List of node set names to associate with the data.
cognify() links the documents and their chunks to those NodeSet nodes, so recall(node_name=...) / search(node_name=...) can scope retrieval to them. Re-adding an existing document without node_set keeps its stored tags; [] clears them. Must be None or a list of non-empty strings — pass ["projectA"] even for a single name. Any other shape (a string, an empty or whitespace-only entry, a non-string entry, or a name that cannot be encoded) raises InvalidNodeSetError (HTTP 400, from cognee.modules.engine.models.node_set) before anything is stored. The same rule applies, item by item, to a DataItem’s own node_set and to a node_set key in its external_metadata; with incremental loading (the default), other items in the same call may already be stored when one item is rejected, and an item skipped as already added is not checked at all.UUID of an existing dataset to add data to. Alternative to dataset_name, and the way to write to a dataset another user shared with you (you need write permission on it). An id you cannot write to, including one that matches no dataset, raises
PermissionDeniedError.Loader names to try first, each optionally with that loader’s options: a dict
{"dlt_csv_loader": {...}}, or a list ["csv_loader"] / [{"dlt_csv_loader": {...}}]. A dict is treated as a one-entry list, so {"dlt_csv_loader": {...}} and [{"dlt_csv_loader": {...}}] are equivalent. Strings and dicts may be mixed in a list, and a loader named twice keeps its last options. Web-page extraction rules go here too, with the scraping extra: [{"beautiful_soup_loader": {"extraction_rules": ...}}]. The extraction_rules, tavily_config and soup_crawler_config keyword arguments are accepted and ignored; Tavily is configured by TAVILY_API_KEY.If true, skip data that has already been ingested. The skip runs whenever this or
data_cache is true, so re-ingesting an already-stored item requires both to be False. See Incremental loading and deduplication.Companion flag to
incremental_loading — either one being true enables the already-processed skip for a data item.LLM settings to install into the current async context for this ingestion operation. When omitted, Cognee uses the active context config or global LLM config. Import
LLMConfig from cognee.infrastructure.llm.config.Embedding settings to install into the current async context for this ingestion operation. When omitted, Cognee uses the active context config or global embedding config. Import
EmbeddingConfig from cognee.infrastructure.databases.vector.embeddings.config.The documents’ importance, 0 to 1. Stored on the
Data record and carried to its chunks; applied uniformly to all items in the call. The hybrid retriever (the default search type) scales a chunk’s ranking score by 0.75 + 0.5 × weight, so from 0.75 (weight 0) to 1.25 (weight 1).Branch to clone for the repository URL(s) in
data, instead of the remote’s default. Applies only to repository URLs; see Code Repository URLs for the errors an invalid or missing branch raises.Column name for primary key when ingesting dlt resources or database connection strings. Auto-detected if not specified. Also reaches CSV files: cognee folds it into the
dlt_csv_loader entry of preferred_loaders, and setting it in both places raises ValueError. Can also be given inside dlt_config.Options that apply only to dlt sources (connection strings, dlt resources, CSV files), grouped in one dict:
primary_key, write_disposition, query, max_rows_per_table, column_value_columns, temporal_columns. An unknown key raises a pydantic ValidationError. The bare keyword arguments are still accepted, but an option given both in dlt_config and as a keyword argument raises ValueError. temporal_columns ({table: [column, ...]}, "*" wildcards, default {"*": ["*"]} from DLT_TEMPORAL_COLUMNS) selects which date cells become Timestamp edges; {} turns them off. column_value_columns (same shape, default {"*": ["*"]} from DLT_COLUMN_VALUE_COLUMNS) selects which cells become shared ColumnValue nodes: every non-key cell by default, except a date cell that already becomes a Timestamp edge; {} turns them off. See Column Value Nodes and DLT Options.If true, start ingestion asynchronously and return immediately. Background runs skip dlt orphan cleanup, so upstream deletions only propagate after a successful foreground run.
Skip the first-run LLM and embedding connection checks for this call only. A later pipeline that needs the LLM or embeddings still runs them.
How to handle existing data for dlt sources: “replace” (drop and recreate), “merge” (upsert on
primary_key), or “append” (always insert). When omitted, a document source whose resources all declare “merge” (every bundled connector) keeps “merge”; other sources run as “replace”. Any other value raises InvalidDLTArgumentError. This controls dlt’s staging snapshot only — a growing source also needs the ingestion skip turned off, see Re-ingesting a source that keeps growing.SQL query that filters what is ingested when using a database connection string as input. Accepts
SELECT ... FROM <table> [WHERE ...], where the FROM target may be schema-qualified and may carry a table alias. A WHERE clause that references the alias, and a FROM clause containing JOIN, raise a ValueError — see Database Connection String for the accepted shapes, the rewrites, and the two detection caveats.Supported Input Types
The SDK reads a DB connection string while
ALLOW_DATABASE_INGESTION is unset. false refuses it, and the HTTP API refuses it unless the variable is true. Connection strings that point at Cognee’s own databases are always refused. See Database Connection-String Ingestion.Web Page URLs
Anhttp(s) URL that is not a code repository is fetched and stored as an .html file named by the page’s content hash, so the document’s name is text_<md5>, not the URL. The full URL is kept in the document’s external_metadata under _cognee.source_uri; s3://, file:// and local-path inputs record their location there too.
To keep the URL on the document as a readable label, wrap the URL in a DataItem (see Parameters) and set label. name stays text_<md5>; the label is stored in its own label field (returned as data_label), and the URL is still recorded in _cognee.source_uri:
external_metadata={"source_uri": "..."} on a DataItem records that value as _cognee.source_uri in place of the detected location.
Code Repository URLs
A string that names a whole git repository is recognised by shape and handled as code rather than as a web page: Cognee shallow-clones it (git clone --depth 1) and hands cognify() one code-repo item, which takes the CODE_REPO route (a single enola pass with cross-file edges) alongside the repository’s own documents. This is the same graph you get from adding a local code project directory.
branch selects the branch to clone. A branch the remote does not have raises CodeRepositoryError (Branch '<name>' was not found in '<url>'.); this is checked before cloning, so a tag with the same name is never checked out instead. An invalid branch name (empty, starting with -, HEAD, containing .. or a space, …) raises ValueError before anything is written, branch is ignored for a local code project directory (it is indexed as currently checked out), and branch is not supported while connected to a remote instance (call cognee.disconnect() first).
A dataset holds one branch of a URL at a time: adding the same URL to the dataset on another branch re-indexes its code graph for that branch, but documents ingested from the previous branch stay in the dataset; remove them with forget().
Recognised as a repository:
https://github.com/<owner>/<repo>— a repository root ongithub.comhttps://gitlab.com/<group>/<repo>— a project ongitlab.com, nested groups included- Any
http(s)URL whose last path segment ends in.git, on any host
.git suffix, trailing slash, www. prefix, query string, or fragment is tolerated and stripped before cloning.
Not recognised (these stay on the ordinary web-page path):
- Deeper forge URLs such as
/blob/,/tree/,/issues,/pull/, and GitLab’s/-/pages - Forge site pages such as
https://github.com/topics/rustorhttps://gitlab.com/explore git@…andssh://…specs — pass these explicitly throughremember(..., content_type="code")
gitmust be on the server’sPATH, and outbound requests must be allowed: SDK, CLI and MCP calls may clone unlessALLOW_HTTP_REQUESTSis set to a value other thantrue,1,yesoron; requests to the API server needALLOW_HTTP_REQUESTS=truethere. A refused repository URL raisesSSRFProtectionError(HTTP 403) naming the setting before any work starts (remember(..., content_type="code")raises it as aCodeRepositoryError) — see Outbound HTTP Requests- Git LFS is disabled for every git command Cognee runs: LFS files are not downloaded and stay small pointer files, and LFS pointers of documents are not ingested
- Clones land under
COGNEE_REPOS_DIR(default~/.cognee/repos) and are reused across calls — budget disk space accordingly. The default branch’s clone is refreshed with a best-effortgit pull --ff-only. A chosenbranchgets its own clone directory beside it (one clone per branch), refreshed withgit fetchof that branch plusgit reset --hard, so a rebased or force-pushed branch still refreshes. A failed refresh reuses the existing clone with a warning, unless the chosenbranchno longer exists on the remote, which raisesCodeRepositoryError - Cloning is credential-free. For a private repository, use
remember(url, content_type="code", repo_credentials="<token>"), described in Code Graph - A
node_setpassed with a repository (URL or local code project directory) tags every code graph node, theCodeRepositorynode included, not only the repository’s documents — see Code Graph
Supported File Formats
See Loaders for how to override the default loader selection or register custom loaders.
Examples
For a complete guide on structured data ingestion with dlt, see the dlt integration page.
Reading the ids of added data
data_ids is None and what each entry contains. Over a serve() connection the ids come back as strings, and the server must be on a version that reports them.