repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
cognee | cognee/tasks/memify/global_context_index/persist.py | .py | from __future__ import annotations
from datetime import datetime, timezone
from types import SimpleNamespace
from typing import Any
from uuid import NAMESPACE_URL, UUID, uuid5
from cognee.infrastructure.databases.provenance import make_source_ref_key
from cognee.infrastructure.databases.provenance.markers import stor... | 132 | 4,616 |
cognee | cognee/tasks/memify/global_context_index/load.py | .py | from __future__ import annotations
from typing import Any
from cognee.modules.graph.cognee_graph.CogneeGraph import CogneeGraph
from cognee.modules.pipelines.models import PipelineContext
from cognee.modules.retrieval.utils.brute_force_triplet_search import get_memory_fragment
from .constants import SUMMARIZED_IN, S... | 186 | 6,151 |
cognee | cognee/tasks/memify/global_context_index/__init__.py | .py | from .load import extract_global_context_index_input
from .update import update_global_context_index
__all__ = ["extract_global_context_index_input", "update_global_context_index"]
| 5 | 182 |
cognee | cognee/tasks/memify/global_context_index/constants.py | .py | SUMMARIZED_IN = "summarized_in"
GLOBAL_CONTEXT_SUMMARY_COLLECTION = "GlobalContextSummary_text"
TEXT_SUMMARY_COLLECTION = "TextSummary_text"
SUMMARY_GRAPH_NODE_TYPES = ["TextSummary", "DocumentChunk", "GlobalContextSummary"]
| 5 | 225 |
cognee | cognee/tasks/memify/global_context_index/update.py | .py | from __future__ import annotations
import math
from dataclasses import dataclass
from numbers import Real
from typing import Any
from cognee.infrastructure.databases.unified import get_unified_engine
from cognee.modules.graph.methods.get_global_context_graph_inputs import (
get_dataset_text_summary_ids,
)
from co... | 322 | 11,321 |
cognee | cognee/tasks/memify/global_context_index/summarize.py | .py | from __future__ import annotations
import asyncio
from uuid import UUID
from cognee.infrastructure.llm.LLMGateway import LLMGateway
from cognee.infrastructure.llm.prompts import read_query_prompt
from cognee.tasks.summarization.models import GlobalContextSummary
from .ids import create_root_summary_id
from .models i... | 84 | 2,621 |
cognee | cognee/tasks/memify/global_context_index/build.py | .py | from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any
from cognee.modules.pipelines.models import PipelineContext
from cognee.tasks.summarization.models import GlobalContextSummary
from .bucketing.graph.placement import (
place_graph_summa... | 277 | 9,445 |
cognee | cognee/tasks/memify/global_context_index/bucketing_strategy.py | .py | from __future__ import annotations
from typing import Literal
BucketingStrategyName = Literal["vector", "graph"]
| 7 | 116 |
cognee | cognee/tasks/memify/global_context_index/bucketing/common.py | .py | from __future__ import annotations
from collections.abc import Iterable
from ..ids import create_bucket_id
from ..models import BucketAssignment, SummaryNode
def create_bucket_node(
child_ids: Iterable[str],
dataset_id: str,
level: int,
*,
graph_bucket_entity_ids: set[str] | None = None,
) -> Su... | 52 | 1,325 |
cognee | cognee/tasks/memify/global_context_index/bucketing/vector/placement.py | .py | from __future__ import annotations
import asyncio
from typing import Any
from cognee.infrastructure.databases.vector.exceptions import CollectionNotFoundError
from ...models import BucketAssignment, SummaryNode
from ..common import (
add_child_to_bucket,
create_bucket_node,
mark_bucket_for_persistence,
... | 237 | 7,843 |
cognee | cognee/tasks/memify/global_context_index/bucketing/graph/placement.py | .py | from __future__ import annotations
from collections.abc import Mapping
from ..common import (
create_bucket_node,
mark_bucket_for_persistence,
record_bucket_assignment,
)
from .scoring import entities_weight, weighted_jaccard
from ...ids import create_bucket_id
from ...models import BucketAssignment, Summ... | 550 | 16,778 |
cognee | cognee/tasks/memify/global_context_index/bucketing/graph/scoring.py | .py | from __future__ import annotations
import math
from collections.abc import Iterable, Mapping
def compute_idf_from_counts(
chunk_count: int,
entity_chunk_counts: Mapping[str, int],
) -> dict[str, float]:
"""
Compute entity IDF weights over the summarized chunk population.
Entities present in ever... | 56 | 1,781 |
cognee | cognee/tasks/memify/global_context_index/bucketing/graph/inputs.py | .py | from __future__ import annotations
from collections.abc import Iterable
from uuid import UUID
from sqlalchemy.ext.asyncio import AsyncSession
from cognee.modules.graph.methods.get_global_context_graph_inputs import (
load_dataset_graph_entity_input,
)
from .scoring import compute_idf_from_counts
async def loa... | 56 | 1,807 |
cognee | cognee/tasks/ingestion/resolve_data_directories.py | .py | from pathlib import Path
from urllib.parse import urlparse
from typing import List, Union, BinaryIO
from cognee.tasks.ingestion.exceptions import S3FileSystemNotFoundError
from cognee.infrastructure.files.storage.s3_config import get_s3_config
from cognee.infrastructure.files.utils.local_path_safety import resolve_loc... | 131 | 5,540 |
cognee | cognee/tasks/ingestion/dlt_schema_graph.py | .py | """Shared emitter for DLT schema graph structure.
Builds and persists SchemaTable/SchemaRelationship nodes and row-level edges
for DLT-sourced relational data. Used by both extract_dlt_source_edges
(the manifest pipeline).
"""
import json
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Optio... | 323 | 13,300 |
cognee | cognee/tasks/ingestion/utils.py | .py | import inspect
from tempfile import SpooledTemporaryFile
from types import SimpleNamespace
from typing import Any, Optional
from cognee.tasks.ingestion.data_item import DataItem
def _normalize_filename(filename: Optional[str], index: int) -> str:
if not filename:
return f"upload_{index}.bin"
normaliz... | 77 | 2,484 |
cognee | cognee/tasks/ingestion/resolve_dlt_sources.py | .py | """DLT adapter: resolve DLT resources into standard DataItem objects.
Called *before* the add pipeline so that ingest_data never sees DLT types.
A relational DLT source becomes a single manifest DataItem (one Data record
per source); the manifest is a JSON document describing every unique row,
materialized as individu... | 753 | 31,876 |
cognee | cognee/tasks/ingestion/extract_dlt_source_edges.py | .py | from typing import TYPE_CHECKING, List, Optional
from cognee.infrastructure.engine.models.DataPoint import DataPoint
from cognee.shared.logging_utils import get_logger
from cognee.tasks.ingestion.dlt_schema_graph import emit_dlt_schema_graph
from cognee.tasks.ingestion.dlt_utils import load_dlt_manifest
if TYPE_CHECK... | 111 | 4,502 |
cognee | cognee/tasks/ingestion/create_dlt_source.py | .py | import os
import re
from typing import Optional
DB_CONNECTION_PATTERNS = [
"postgresql://",
"postgres://",
"mysql://",
"mysql+pymysql://",
"sqlite:///",
"mssql://",
"oracle://",
]
def is_connection_string(data: str) -> bool:
return any(data.startswith(p) for p in DB_CONNECTION_PATTERN... | 118 | 4,090 |
cognee | cognee/tasks/ingestion/__init__.py | .py | """
Data ingestion and normalization tasks.
This module provides functionality for accepting raw data inputs
(files, URLs, streams, or external objects), transforming them into
standardized text representations, and registering them within
datasets and the relational database.
"""
from .save_data_item_to_storage impo... | 15 | 571 |
cognee | cognee/tasks/ingestion/dlt_row_data.py | .py | from dataclasses import dataclass
@dataclass
class DltRowData:
"""Carries per-row information from ingest_dlt_source back to ingest_data."""
table_name: str
primary_key_column: str
primary_key_value: str
row_data: dict
content_hash: str
schema_info: object # list[dict] for SQLite, dict f... | 18 | 471 |
cognee | cognee/tasks/ingestion/purge_stale_dlt_source_artifacts.py | .py | """Purge a DLT source's previously derived artifacts before re-emission.
Runs right after classify_documents in the DLT cognify route. A manifest's
Data id is stable (dlt_source:{dataset}:{source}), so reprocessing a changed
source re-emits its rows under the same identity — without this purge, chunks
of deleted rows ... | 60 | 2,529 |
cognee | cognee/tasks/ingestion/dlt_utils.py | .py | """Shared utilities for DLT ingestion."""
import json
from typing import Optional
# A dlt source sets this attribute to opt into the "document" ingestion path:
# each row becomes a text document that flows through normal cognify (LLM entity
# extraction), instead of the default relational schema-context path. The val... | 63 | 2,539 |
cognee | cognee/tasks/ingestion/ingest_dlt_source.py | .py | import asyncio
import hashlib
import json
import os
import re
from collections import Counter
from typing import List, Optional
from sqlalchemy import URL, text
from sqlalchemy.ext.asyncio import create_async_engine
from cognee.modules.data.models import Data
from cognee.infrastructure.databases.postgres.admin import... | 517 | 19,695 |
cognee | cognee/tasks/ingestion/data_item.py | .py | import json
from dataclasses import dataclass, field
from typing import Any, List, Optional
from uuid import UUID
from cognee.tasks.ingestion.exceptions import (
ExternalMetadataCountMismatchError,
InvalidExternalMetadataError,
InvalidLabelsError,
LabelCountMismatchError,
)
@dataclass
class DataItem:... | 136 | 5,463 |
cognee | cognee/tasks/ingestion/migrate_relational_database.py | .py | import logging
from uuid import uuid5, NAMESPACE_OID
from sqlalchemy import text
from cognee.infrastructure.databases.relational.get_migration_relational_engine import (
get_migration_relational_engine,
)
from cognee.infrastructure.databases.relational.config import get_migration_config
from cognee.tasks.storage.i... | 310 | 13,689 |
cognee | cognee/tasks/ingestion/ingest_data.py | .py | import json
import inspect
import os
from uuid import UUID, uuid4
from typing import Union, BinaryIO, Any, List, Optional
import cognee.modules.ingestion as ingestion
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from cognee.infrastructure.databases.relational import get_relational_engine
fro... | 323 | 15,393 |
cognee | cognee/tasks/ingestion/transform_data.py | .py | from llama_index.core import Document
from llama_index.core.schema import ImageDocument
from cognee.modules.ingestion import save_data_to_file
from typing import Union
async def get_data_from_llama_index(data_point: Union[Document, ImageDocument]) -> str:
"""
Retrieve the file path based on the data point typ... | 39 | 1,506 |
cognee | cognee/tasks/ingestion/get_dlt_destination.py | .py | import os
from functools import lru_cache
try:
import dlt
except ImportError:
dlt = None
from typing import Optional, Any
from cognee.infrastructure.databases.relational import get_relational_config
@lru_cache
def get_dlt_destination(dlt_db_name: str) -> Optional[Any]:
"""
Handle the propagation of ... | 57 | 2,082 |
cognee | cognee/tasks/ingestion/data_item_to_text_file.py | .py | import os
from urllib.parse import urlparse
from typing import Any, List, Tuple
from pathlib import Path
import tempfile
from cognee.infrastructure.loaders.LoaderInterface import LoaderInterface
from cognee.modules.ingestion.exceptions import IngestionError
from cognee.infrastructure.loaders import get_loader_engine
f... | 103 | 4,347 |
cognee | cognee/tasks/ingestion/config.py | .py | from functools import lru_cache
from pydantic_settings import BaseSettings, SettingsConfigDict
class IngestionConfig(BaseSettings):
# Cap on rows read per table from a DLT source; 0 (default) means
# unlimited — everything is ingested. Set a positive value (env:
# DLT_MAX_ROWS_PER_TABLE, or add(..., max_r... | 43 | 1,935 |
cognee | cognee/tasks/ingestion/save_data_item_to_storage.py | .py | import os
from pathlib import Path
from urllib.parse import urlparse
from urllib.request import url2pathname
from typing import Union, BinaryIO, Any
from cognee.modules.ingestion.exceptions import IngestionError
from cognee.modules.ingestion import save_data_to_file
from cognee.infrastructure.files.utils.local_path_sa... | 127 | 5,497 |
cognee | cognee/tasks/ingestion/exceptions/exceptions.py | .py | from cognee.exceptions import CogneeSystemError, CogneeValidationError, CogneeConfigurationError
from fastapi import status
class S3FileSystemNotFoundError(CogneeSystemError):
def __init__(
self,
name: str = "S3FileSystemNotFoundError",
status_code: int = status.HTTP_500_INTERNAL_SERVER_ER... | 85 | 2,829 |
cognee | cognee/tasks/ingestion/exceptions/__init__.py | .py | """
Custom exceptions for the Cognee API.
This module defines a set of exceptions for handling various application errors,
such as System, Validation, Configuration or TransientErrors
"""
from .exceptions import (
S3FileSystemNotFoundError,
LabelCountMismatchError,
InvalidLabelsError,
InvalidExternalM... | 15 | 376 |
cognee | cognee/tasks/ingestion/connectors/__init__.py | .py | """SaaS data-source connectors for cognee.
Connectors that pull an external source (Gmail, Slack, Notion, Google Drive,
Confluence, …) into cognee memory are distributed as **separate community
packages** under https://github.com/topoteretes/cognee-community
(``cognee-community-connector-<source>``), so core stays fre... | 21 | 919 |
cognee | cognee/tasks/summarization/models.py | .py | from __future__ import annotations
from typing import Union, Optional
from cognee.infrastructure.engine import DataPoint
from cognee.modules.chunking.models import DocumentChunk
from cognee.shared.CodeGraphEntities import CodeFile, CodePart
class GlobalContextSummary(DataPoint):
"""
Summarizes a global conte... | 56 | 1,853 |
cognee | cognee/tasks/summarization/__init__.py | .py | """
LLM-based summarization tasks.
This module provides tasks for generating structured summaries from
document chunks and code graph nodes. It produces DataPoint-based summary
objects that can be indexed and integrated into the knowledge graph.
"""
from .summarize_code import summarize_code
from .summarize_text impo... | 11 | 338 |
cognee | cognee/tasks/summarization/summarize_text.py | .py | import asyncio
from typing import Type
from uuid import uuid5
from pydantic import BaseModel
from cognee.tasks.summarization.exceptions import InvalidSummaryInputsError
from cognee.modules.chunking.models.DocumentChunk import DocumentChunk
from cognee.infrastructure.llm.extraction import extract_summary
from cognee.in... | 75 | 2,628 |
cognee | cognee/tasks/summarization/mock_summary.py | .py | from cognee.shared.data_models import SummarizedCode, SummarizedClass, SummarizedFunction
def get_mock_summarized_code() -> SummarizedCode:
"""
Return a summarized representation of mock code.
This function constructs and returns a `SummarizedCode` object that includes various
components such as file... | 52 | 1,997 |
cognee | cognee/tasks/summarization/summarize_code.py | .py | import asyncio
from typing import AsyncGenerator, Union
from uuid import uuid5
from cognee.infrastructure.engine import DataPoint
from cognee.infrastructure.llm.extraction import extract_code_summary
from .models import CodeSummary
async def summarize_code(
code_graph_nodes: list[DataPoint],
) -> AsyncGenerator[... | 40 | 1,137 |
cognee | cognee/tasks/summarization/exceptions/exceptions.py | .py | from cognee.exceptions import (
CogneeValidationError,
CogneeConfigurationError,
)
from fastapi import status
class InvalidSummaryInputsError(CogneeValidationError):
def __init__(self, detail: str):
super().__init__(
message=f"Invalid summarize_text inputs: {detail}",
name=... | 15 | 412 |
cognee | cognee/tasks/summarization/exceptions/__init__.py | .py | """
Custom exceptions for the Cognee API.
This module defines a set of exceptions for handling various data errors
"""
from .exceptions import (
InvalidSummaryInputsError,
)
| 10 | 180 |
cognee | cognee/tasks/temporal_awareness/search_graph_with_temporal_awareness.py | .py | async def search_graph_with_temporal_awareness(graphiti, query):
search_result = await graphiti.search(query)
await graphiti.close()
return search_result
| 5 | 166 |
cognee | cognee/tasks/temporal_awareness/index_graphiti_objects.py | .py | from cognee.shared.logging_utils import get_logger, ERROR
from collections import Counter
from cognee.tasks.temporal_awareness.graphiti_model import GraphitiNode
from cognee.infrastructure.databases.vector import get_vector_engine_async
from cognee.infrastructure.databases.graph import get_graph_engine
from cognee.mod... | 103 | 4,195 |
cognee | cognee/tasks/temporal_awareness/__init__.py | .py | """
Temporal awareness for graph construction and retrieval tasks.
This module provides tools for building and querying dynamic knowledge graphs.
It uses the Graphiti library to ensure that data is stored as a sequence of events (episodes),
enabling the system to understand when things happened and how facts have chan... | 11 | 512 |
cognee | cognee/tasks/temporal_awareness/build_graph_with_temporal_awareness.py | .py | import os
import logging
from typing import List
from datetime import datetime, timezone
from graphiti_core import Graphiti
from graphiti_core.nodes import EpisodeType
from cognee.infrastructure.files.storage import get_file_storage
from cognee.modules.data.models import Data
logger = logging.getLogger(__name__)
a... | 43 | 1,334 |
cognee | cognee/tasks/temporal_awareness/graphiti_model.py | .py | from cognee.infrastructure.engine import DataPoint
from typing import Optional
class GraphitiNode(DataPoint):
"""
Represent a node in a graph with optional content, name, and summary attributes.
This class extends DataPoint and includes a metadata dictionary that specifies the index
fields for the no... | 23 | 820 |
cognee | cognee/tasks/entity_completion/entity_extractors/regex_entity_extractor.py | .py | from cognee.shared.logging_utils import get_logger
from typing import List, Optional
from cognee.infrastructure.entities.BaseEntityExtractor import BaseEntityExtractor
from cognee.modules.engine.models import Entity
from cognee.root_dir import get_absolute_path
from cognee.tasks.entity_completion.entity_extractors.reg... | 73 | 3,056 |
cognee | cognee/tasks/entity_completion/entity_extractors/regex_entity_config.py | .py | import json
from cognee.shared.logging_utils import get_logger
import os
import re
from typing import Dict, List, Pattern, Any
from cognee.modules.engine.models.EntityType import EntityType
from cognee.root_dir import get_absolute_path
logger = get_logger("regex_entity_config")
class RegexEntityConfig:
"""Class... | 92 | 3,853 |
cognee | cognee/tasks/entity_completion/entity_extractors/llm_entity_extractor.py | .py | from cognee.shared.logging_utils import get_logger
from typing import List
from pydantic import BaseModel
from cognee.infrastructure.llm.prompts import render_prompt, read_query_prompt
from cognee.infrastructure.entities.BaseEntityExtractor import BaseEntityExtractor
from cognee.modules.engine.models import Entity
fr... | 73 | 2,627 |
cognee | cognee/tasks/schema/models.py | .py | from cognee.infrastructure.engine.models.DataPoint import DataPoint
from typing import List, Dict, Optional
from datetime import datetime
class DatabaseSchema(DataPoint):
"""Represents a complete database schema with sample data"""
name: str
database_type: str # sqlite, postgres, etc.
tables: str #... | 41 | 1,285 |
cognee | cognee/tasks/schema/ingest_database_schema.py | .py | import json
from typing import List, Dict
from uuid import uuid5, NAMESPACE_OID
from cognee.infrastructure.engine.models.DataPoint import DataPoint
from sqlalchemy import text
from cognee.tasks.schema.models import DatabaseSchema, SchemaTable, SchemaRelationship
from cognee.infrastructure.databases.relational.get_migra... | 135 | 6,050 |
cognee | cognee/tasks/graph/detect_contradictions.py | .py | """Opt-in contradiction detection for the knowledge graph (the "brain").
Pipeline seam: spliced in as the last cognify task by ``get_default_tasks`` when
the ``contradiction_detection`` config flag is on (default off). It runs after
``add_data_points`` so both the new and the pre-existing facts are persisted and
compa... | 236 | 9,833 |
cognee | cognee/tasks/graph/extract_graph_from_code.py | .py | import asyncio
from typing import TYPE_CHECKING, Type, List
from pydantic import BaseModel
from cognee.infrastructure.llm.extraction import extract_content_graph
from cognee.modules.chunking.models.DocumentChunk import DocumentChunk
from cognee.tasks.storage import add_data_points
if TYPE_CHECKING:
from cognee.m... | 36 | 1,118 |
cognee | cognee/tasks/graph/resolve_temporal_contradictions.py | .py | """Opt-in temporal contradiction resolution for the knowledge graph (issue #3631).
Runs after the graph has been written. For the relationships the caller declares
*functional* — single-valued, like a company's current CEO — it inspects the
region of the graph this ingestion touched and, wherever a subject ended up
ho... | 114 | 5,145 |
cognee | cognee/tasks/graph/models.py | .py | from typing import Any, Dict, List, Optional, Union
from pydantic import BaseModel, Field
class RelationshipModel(BaseModel):
"""
Represents a relationship between two entities in a model.
This class holds the type of the relationship and the identifiers for the source and
target entities. It include... | 121 | 4,119 |
cognee | cognee/tasks/graph/__init__.py | .py | """
Graph extraction and manipulation tasks.
This module provides tasks for extracting knowledge graphs from data,
building relationships between entities, and managing graph structures.
"""
from .extract_graph_from_data import extract_graph_from_data
from .extract_graph_from_code import extract_graph_from_code
from ... | 12 | 449 |
cognee | cognee/tasks/graph/extract_graph_from_data.py | .py | import asyncio
import inspect
from typing import Type, List, Optional
from pydantic import BaseModel
from cognee.modules.pipelines.tasks.task import task_summary
from cognee.modules.ontology.ontology_config import Config
from cognee.modules.ontology.get_default_ontology_resolver import get_configured_ontology_resolver... | 220 | 8,394 |
cognee | cognee/tasks/graph/extract_graph_from_data_v2.py | .py | import asyncio
from typing import List
from cognee.modules.chunking.models.DocumentChunk import DocumentChunk
from cognee.shared.data_models import KnowledgeGraph
from cognee.modules.ontology.base_ontology_resolver import BaseOntologyResolver
from cognee.tasks.graph.cascade_extract.utils.extract_nodes import extract_n... | 65 | 2,314 |
cognee | cognee/tasks/graph/extract_graph_and_summarize.py | .py | from typing import List, Type, Optional
from pydantic import BaseModel
import asyncio
from cognee.modules.chunking.models import DocumentChunk
from cognee.modules.ontology.ontology_config import Config
from cognee.tasks.graph import extract_graph_from_data
from cognee.tasks.summarization import summarize_text
from cog... | 38 | 1,194 |
cognee | cognee/tasks/graph/exceptions/exceptions.py | .py | from cognee.exceptions import (
CogneeValidationError,
CogneeConfigurationError,
)
from fastapi import status
class InvalidDataChunksError(CogneeValidationError):
def __init__(self, detail: str):
super().__init__(
message=f"Invalid data_chunks: {detail}",
name="InvalidDataC... | 42 | 1,319 |
cognee | cognee/tasks/graph/exceptions/__init__.py | .py | """
Custom exceptions for the Cognee API.
This module defines a set of exceptions for handling various data errors
"""
from .exceptions import (
InvalidDataChunksError,
InvalidGraphModelError,
InvalidOntologyAdapterError,
InvalidChunkGraphInputError,
)
| 13 | 271 |
cognee | cognee/tasks/graph/cascade_extract/utils/extract_content_nodes_and_relationship_names.py | .py | from typing import List, Tuple
from pydantic import BaseModel
from cognee.infrastructure.llm.prompts import render_prompt, read_query_prompt
from cognee.infrastructure.llm.LLMGateway import LLMGateway
from cognee.root_dir import get_absolute_path
class PotentialNodesAndRelationshipNames(BaseModel):
"""Response m... | 61 | 2,363 |
cognee | cognee/tasks/graph/cascade_extract/utils/extract_nodes.py | .py | from typing import List
from pydantic import BaseModel
from cognee.infrastructure.llm.prompts import render_prompt, read_query_prompt
from cognee.infrastructure.llm.LLMGateway import LLMGateway
from cognee.root_dir import get_absolute_path
class PotentialNodes(BaseModel):
"""Response model containing a list of p... | 44 | 1,512 |
cognee | cognee/tasks/graph/cascade_extract/utils/extract_edge_triplets.py | .py | from typing import List
from cognee.infrastructure.llm.prompts import render_prompt, read_query_prompt
from cognee.infrastructure.llm.LLMGateway import LLMGateway
from cognee.shared.data_models import KnowledgeGraph
from cognee.root_dir import get_absolute_path
async def extract_edge_triplets(
content: str, node... | 61 | 2,318 |
cognee | cognee/shared/utils.py | .py | """This module contains utility functions for the cognee."""
import asyncio
import http.server
import os
import pathlib
import socketserver
import ssl
from datetime import datetime, timezone
from threading import Thread
from typing import Any
from uuid import NAMESPACE_OID, UUID, uuid4, uuid5
import aiohttp
from cog... | 375 | 64,385 |
cognee | cognee/shared/graph_model_utils.py | .py | import asyncio
import re
import sys
import types
from pprint import pprint
from typing import Any, Union, cast, get_args, get_origin
from datamodel_code_generator import DataModelType, GenerateConfig, InputFileType, generate
from pydantic import BaseModel, ConfigDict, Field, create_model
from pydantic._internal._core_... | 245 | 9,921 |
cognee | cognee/shared/data_models.py | .py | """Data models for the cognitive architecture."""
from enum import Enum, auto
from typing import Any
from pydantic import BaseModel, Field
from cognee.infrastructure.llm.config import (
get_llm_config,
)
if get_llm_config().llm_provider.lower() == "gemini":
"""
Note: Gemini doesn't allow for an empty di... | 369 | 11,349 |
cognee | cognee/shared/usage_logger.py | .py | import asyncio
import inspect
import os
from collections.abc import Callable
from datetime import datetime, timezone
from functools import singledispatch, wraps
from typing import Any
from uuid import UUID
from cognee import __version__ as cognee_version
from cognee.infrastructure.databases.cache.config import get_cac... | 345 | 11,853 |
cognee | cognee/shared/logging_utils.py | .py | import importlib.metadata
import logging
import logging.handlers
import os
import platform
import sys
import tempfile
import traceback
from collections.abc import MutableMapping
from datetime import datetime
from pathlib import Path
from typing import Any, Protocol
import structlog
def _get_cognee_version() -> str:
... | 662 | 25,516 |
cognee | cognee/shared/async_utils.py | .py | import asyncio
from collections.abc import Awaitable, Callable, Iterable
from typing import TypeVar
T = TypeVar("T")
AsyncCallFactory = Callable[[], Awaitable[T]]
async def gather_with_concurrency_limit(
call_factories: Iterable[AsyncCallFactory[T]],
limit: int,
) -> list[T]:
"""Run async call factories... | 28 | 774 |
cognee | cognee/shared/lru_cache.py | .py | """
Shared cache size setting for Cognee database adapters.
Set DATABASE_MAX_LRU_CACHE_SIZE in the environment to control the maxsize of the
closing LRU cache used by the graph, vector, and relational DB engine factories
(default: 6). It is also the default for DATASET_QUEUE_MAX_CONCURRENT, keeping
admitted datasets a... | 16 | 650 |
cognee | cognee/shared/encode_uuid.py | .py | from uuid import UUID
def encode_uuid(uuid: UUID) -> str:
uuid_int = uuid.int
base = 52
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
encoded = ""
while len(encoded) < 36:
uuid_int, remainder = divmod(uuid_int, base)
uuid_int = uuid_int * 8
encoded = cha... | 16 | 366 |
cognee | cognee/shared/SourceCodeGraph.py | .py | from typing import Any, Literal
from cognee.infrastructure.engine import DataPoint
class Variable(DataPoint):
id: str
name: str
description: str
is_static: bool | None = False
default_value: str | None = None
data_type: str
metadata: dict = {"index_fields": ["name"]}
class Operator(Dat... | 89 | 1,926 |
cognee | cognee/shared/rate_limiting.py | .py | """Rate-limiting context managers for LLM and embedding dispatch.
This module is the pacing seam: adapters wrap each dispatch attempt with
``llm_rate_limiter_context_manager()`` (inside their tenacity retry) or
``embedding_rate_limiter_context_manager()``. Overload detection and reaction
policy live in ``cognee.infras... | 84 | 3,332 |
cognee | cognee/shared/GithubClassification.py | .py | from enum import Enum
from pydantic import BaseModel
class TextSubclass(str, Enum):
SOURCE_CODE = "Source code in various programming languages"
SHELL_SCRIPTS = "Shell commands and scripts"
MARKUP_LANGUAGES = "Markup languages (HTML, XML)"
STYLESHEETS = "Stylesheets (CSS) and configuration files (YAM... | 30 | 785 |
cognee | cognee/shared/CodeGraphEntities.py | .py | from cognee.low_level import DataPoint
class Repository(DataPoint):
path: str
class ImportStatement(DataPoint):
name: str
module: str
start_point: tuple
end_point: tuple
source_code: str
file_path: str | None = None
class FunctionDefinition(DataPoint):
name: str
start_point: tu... | 62 | 1,514 |
cognee | cognee/shared/cache.py | .py | """
Storage-aware cache management utilities for Cognee.
This module provides cache functionality that works with both local and cloud storage
backends (like S3) through the StorageManager abstraction.
"""
import asyncio
import hashlib
import logging
import zipfile
from io import BytesIO
import aiohttp
from cognee.... | 347 | 13,936 |
cognee | cognee/shared/GithubTopology.py | .py | from typing import Any
from pydantic import BaseModel
class Relationship(BaseModel):
type: str
attributes: dict[str, Any] | None = {}
class Document(BaseModel):
name: str
content: str
filetype: str
class Directory(BaseModel):
name: str
documents: list[Document] = []
directories: l... | 43 | 933 |
cognee | cognee/shared/exceptions/exceptions.py | .py | from fastapi import status
from cognee.exceptions import CogneeConfigurationError, CogneeValidationError
class IngestionError(CogneeValidationError):
def __init__(
self,
message: str = "Failed to load data.",
name: str = "IngestionError",
status_code: int = status.HTTP_422_UNPROCE... | 24 | 728 |
cognee | cognee/shared/exceptions/__init__.py | .py | """
Custom exceptions for the Cognee API.
This module defines a set of exceptions for handling various shared utility errors
"""
from .exceptions import IngestionError, UsageLoggerError
| 8 | 188 |
cognee | cognee/migration/__init__.py | .py | """Public migration API: move memory into and out of Cognee.
Importing from other memory systems (pass any source to ``cognee.remember``)::
from cognee.migration import Mem0Source, ZepSource, LettaSource
await cognee.remember(Mem0Source("mem0_export.json"))
await cognee.remember(ZepSource("graphiti_dump.... | 85 | 1,946 |
cognee | cognee/alembic/env.py | .py | import asyncio
import logging
from alembic import context
from logging.config import fileConfig
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import async_engine_from_config
from cognee.infrastructure.databases.relational import get_relational_engine, Base
import cogn... | 114 | 3,489 |
cognee | cognee/alembic/versions/a1b2c3d4e5f6_add_label_column_to_data.py | .py | """Add label column to data table
Revision ID: a1b2c3d4e5f6
Revises: 211ab850ef3d
Create Date: 2025-11-17 17:54:32.123456
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "a1b2c3d4e5f6"
down_revision: Union[str, None] = "... | 39 | 925 |
cognee | cognee/alembic/versions/e1ec1dcb50b6_add_last_accessed_to_data.py | .py | """add_last_accessed_to_data
Revision ID: e1ec1dcb50b6
Revises: 211ab850ef3d
Create Date: 2025-11-04 21:45:52.642322
"""
import os
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "e1ec1dcb50b6"
down_revision: Union[str, Non... | 52 | 1,468 |
cognee | cognee/alembic/versions/b1c2d3e4f5a6_add_user_api_key_table.py | .py | """add_user_api_key_table
Revision ID: b1c2d3e4f5a6
Revises: f1a2b3c4d5e6
Create Date: 2026-04-01 00:00:00.000000
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "b1c2d3e4f5a6"
down_revision: Union[str, None] = "18f01b0... | 49 | 1,245 |
cognee | cognee/alembic/versions/9e7a3cb85175_loader_separation.py | .py | """loader_separation
Revision ID: 9e7a3cb85175
Revises: 1daae0df1866
Create Date: 2025-08-14 19:18:11.406907
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "9e7a3cb85175"
down_revision: Union[str, None] = "1daae0df1866... | 105 | 4,075 |
cognee | cognee/alembic/versions/d6e8f0a2b4c6_backfill_dataset_scoped_data_drop_dataset_data.py | .py | """backfill_dataset_scoped_data_drop_dataset_data
Completes the dataset-scoping of Data rows and retires the dataset_data
membership table:
1. Adds ``data.legacy_id`` (provenance for split rows).
2. Backfills every legacy row (``dataset_id IS NULL``) from its memberships:
- exactly one membership → the row keeps i... | 330 | 13,586 |
cognee | cognee/alembic/versions/760ef4f08ef0_change_node_label_and_type_to_text.py | .py | """change node label and type to text
Revision ID: 760ef4f08ef0
Revises: 24f5d4f64d0d
Create Date: 2026-05-21 15:00:00.000000
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "760ef4f08ef0"
down_revision: Union[str, None... | 96 | 2,160 |
cognee | cognee/alembic/versions/1a58b986e6e1_enable_delete_for_old_tutorial_notebooks.py | .py | """Enable delete for old tutorial notebooks
Revision ID: 1a58b986e6e1
Revises: 46a6ce2bd2b2
Create Date: 2025-12-17 11:04:44.414259
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "1a58b986e6e1"
down_revision: Union[str... | 53 | 1,288 |
cognee | cognee/alembic/versions/d8f4a1b2c3e9_add_global_database_version.py | .py | """Add the single-row global_database_version table
Tracks the deployment-wide Cognee version (written on every startup in both
access-control modes) and, when backend access control is disabled, the
data-migration revision of the GLOBAL graph/vector databases (no per-dataset
dataset_database rows exist to carry them ... | 49 | 1,548 |
cognee | cognee/alembic/versions/211ab850ef3d_add_sync_operations_table.py | .py | """Add sync_operations table
Revision ID: 211ab850ef3d
Revises: 9e7a3cb85175
Create Date: 2025-09-10 20:11:13.534829
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision: str = "211ab850ef... | 119 | 4,626 |
cognee | cognee/alembic/versions/f1a2b3c4d5e6_add_importance_weight_to_data.py | .py | """add_importance_weight_to_data
Revision ID: f1a2b3c4d5e6
Revises: e1ec1dcb50b6
Create Date: 2026-04-07 00:00:00.000000
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "f1a2b3c4d5e6"
down_revision: Union[str, None] = "... | 45 | 1,153 |
cognee | cognee/alembic/versions/8057ae7329c2_initial_migration.py | .py | """Initial migration
Revision ID: 8057ae7329c2
Revises:
Create Date: 2024-10-02 12:55:20.989372
"""
from typing import Sequence, Union
from sqlalchemy.util import await_only
from cognee.infrastructure.databases.relational import get_relational_engine
# revision identifiers, used by Alembic.
revision: str = "8057ae7... | 26 | 541 |
cognee | cognee/alembic/versions/d4e5f6a7b8c9_add_dataset_configuration_table.py | .py | """add dataset_configuration table
Revision ID: d4e5f6a7b8c9
Revises:
Create Date: 2026-04-04
"""
from alembic import op
import sqlalchemy as sa
revision = "d4e5f6a7b8c9"
down_revision = "f1a2b3c4d5e6"
branch_labels = None
depends_on = None
def upgrade() -> None:
conn = op.get_bind()
insp = sa.inspect(conn... | 45 | 1,188 |
cognee | cognee/alembic/versions/c5d7e9f1a3b5_add_dataset_id_to_data.py | .py | """add_dataset_id_to_data
Data rows become dataset-scoped: `dataset_id` names the dataset that owns the
content row, and the (dataset_id, owner_id, content_hash) index backs
add-time dedup as a LOOKUP (scoped to dataset + owner + tenant) instead of a
content-derived identity. This revision only adds the column and ind... | 66 | 2,114 |
cognee | cognee/alembic/versions/c946955da633_multi_tenant_support.py | .py | """Multi Tenant Support
Revision ID: c946955da633
Revises: 211ab850ef3d
Create Date: 2025-11-04 18:11:09.325158
"""
from typing import Sequence, Union
from datetime import datetime, timezone
from uuid import uuid4
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str... | 138 | 4,543 |
cognee | cognee/alembic/versions/e4ebee1091e7_expand_data_model_info.py | .py | """Expand data model info
Revision ID: e4ebee1091e7
Revises: ab7e313804ae
Create Date: 2025-07-24 13:21:30.738486
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision: str = "e4ebee1091e7"
... | 141 | 5,401 |
cognee | cognee/alembic/versions/7c5d4e2f8a91_add_parent_user_id_to_users.py | .py | """Add parent_user_id to users
Revision ID: 7c5d4e2f8a91
Revises: b2c3d4e5f6a7
Create Date: 2026-04-23 21:35:00.000000
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "7c5d4e2f8a91"
down_revision: Union[str, None] = "b2... | 82 | 2,472 |
cognee | cognee/alembic/versions/482cd6517ce4_add_default_user.py | .py | """Add default user
Revision ID: 482cd6517ce4
Revises: 8057ae7329c2
Create Date: 2024-10-16 22:17:18.634638
"""
from typing import Sequence, Union
from sqlalchemy.util import await_only
from cognee.modules.users.methods import create_default_user, delete_user
from fastapi_users.exceptions import UserAlreadyExists... | 31 | 629 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.