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/modules/cognify/recovery.py
.py
import os from datetime import datetime, timedelta, timezone from sqlalchemy import func, select from sqlalchemy.orm import aliased from cognee.context_global_variables import set_database_global_context_variables from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.cognify...
136
5,610
cognee
cognee/modules/cognify/routing.py
.py
"""Cognify routing policy: which task route a data item takes. One pure, synchronous function — no I/O, no configuration — importable by everything that needs the decision: cognify() (to resolve per-item task lists), the dry-run estimator (so cost estimates can never drift from execution), and, via document_class_for,...
42
1,333
cognee
cognee/modules/memify/memify.py
.py
from typing import Union, Optional, List, Sequence, Type, Any from uuid import UUID from cognee.shared.logging_utils import get_logger from cognee.modules.data.constants import DEFAULT_DATASET_NAME from cognee.modules.retrieval.utils.brute_force_triplet_search import get_memory_fragment from cognee.context_global_var...
139
6,720
cognee
cognee/modules/memify/skill_improvement.py
.py
"""Internal proposal-first skill improvement used by remember().""" from __future__ import annotations from types import SimpleNamespace from typing import Any, Optional from uuid import NAMESPACE_URL, UUID, uuid4, uuid5 from pydantic import BaseModel, Field from cognee.context_global_variables import set_database_...
349
12,146
cognee
cognee/modules/pipelines/provenance_config.py
.py
"""Provenance mode configuration for the cognee pipeline. Controls how aggressively provenance metadata is stamped on DataPoints during ingestion. Three modes are supported: - ``lightweight`` (default): stamp only the minimal identifiers (``source_pipeline``, ``source_task``, ``source_node_set``, ``source_content...
80
2,707
cognee
cognee/modules/pipelines/layers/check_pipeline_run_qualification.py
.py
from typing import Union, Optional from cognee.modules.data.models import Dataset from cognee.modules.data.models import Data from cognee.modules.pipelines.models import PipelineRunStatus from cognee.modules.pipelines.operations.get_pipeline_status import get_pipeline_status from cognee.modules.pipelines.methods import...
60
2,479
cognee
cognee/modules/pipelines/layers/validate_pipeline_tasks.py
.py
from ..tasks.task import Task from ..exceptions.tasks import WrongTaskTypeError def validate_pipeline_tasks(tasks: list[Task]): """ Validates the tasks argument to ensure it is a list of Task class instances. Args: tasks (list[Task]): The list of tasks to be validated. """ if not isinsta...
21
662
cognee
cognee/modules/pipelines/layers/reset_dataset_pipeline_run_status.py
.py
from uuid import UUID from typing import Optional, List from cognee.modules.pipelines.methods import get_pipeline_runs_by_dataset, reset_pipeline_run_status from cognee.modules.pipelines.models.PipelineRun import PipelineRunStatus from cognee.modules.users.models import User async def reset_dataset_pipeline_run_stat...
29
1,118
cognee
cognee/modules/pipelines/layers/resolve_authorized_user_dataset.py
.py
from uuid import UUID from typing import Optional from cognee.modules.users.models import User from cognee.modules.pipelines.layers.resolve_authorized_user_datasets import ( resolve_authorized_user_datasets, ) async def resolve_authorized_user_dataset( dataset_name: str, dataset_id: Optional[UUID] = None, us...
32
1,120
cognee
cognee/modules/pipelines/layers/setup_and_check_environment.py
.py
import os import asyncio from cognee.context_global_variables import ( graph_db_config as context_graph_db_config, vector_db_config as context_vector_db_config, ) from cognee.infrastructure.databases.relational import ( create_db_and_tables as create_relational_db_and_tables, ) from cognee.infrastructure.d...
68
2,355
cognee
cognee/modules/pipelines/layers/resolve_authorized_user_datasets.py
.py
from uuid import UUID from typing import Union, Tuple, List, Optional from cognee.modules.users.methods import get_default_user from cognee.modules.users.models import User from cognee.modules.data.models import Dataset from cognee.modules.data.exceptions import DatasetNotFoundError from cognee.modules.data.methods im...
56
2,275
cognee
cognee/modules/pipelines/layers/pipeline_execution_mode.py
.py
import asyncio from typing import Any, AsyncIterable, AsyncGenerator, Callable, Dict, Union, Awaitable from cognee.modules.pipelines.models.PipelineRunInfo import PipelineRunCompleted, PipelineRunErrored from cognee.modules.pipelines.queues.pipeline_run_info_queues import push_to_queue from cognee.modules.users.methods...
141
5,627
cognee
cognee/modules/pipelines/exceptions/exceptions.py
.py
from cognee.exceptions import CogneeSystemError from fastapi import status class PipelineRunFailedError(CogneeSystemError): def __init__( self, message: str = "Pipeline run failed.", name: str = "PipelineRunFailedError", status_code: int = status.HTTP_422_UNPROCESSABLE_CONTENT, ...
13
377
cognee
cognee/modules/pipelines/exceptions/tasks.py
.py
from fastapi import status from cognee.exceptions import CogneeValidationError class WrongTaskTypeError(CogneeValidationError): """ Raised when the tasks argument is not a list of Task class instances. """ def __init__( self, message: str = "tasks argument must be a list, containing T...
17
494
cognee
cognee/modules/pipelines/tasks/task.py
.py
from typing import Union, Callable, Any, Coroutine, Generator, AsyncGenerator import inspect from cognee.pipelines.types import _Drop class BoundTask: """A Task with pre-bound keyword arguments, ready for pipeline chaining. Created by calling a TaskSpec. The first positional argument (pipeline data) is ...
310
10,745
cognee
cognee/modules/pipelines/queues/pipeline_run_info_queues.py
.py
from uuid import UUID from asyncio import Queue from typing import Optional from cognee.modules.pipelines.models import PipelineRunInfo pipeline_run_info_queues = {} def initialize_queue(pipeline_run_id: UUID): pipeline_run_info_queues[str(pipeline_run_id)] = Queue() def get_queue(pipeline_run_id: UUID) -> O...
38
985
cognee
cognee/modules/pipelines/operations/pipeline.py
.py
import asyncio from uuid import UUID from typing import AsyncIterator, Awaitable, Callable, Optional, Union from cognee.infrastructure.locks import get_dataset_lock, held_datasets from cognee.modules.pipelines.layers.setup_and_check_environment import ( setup_and_check_environment, ) from cognee.shared.logging_ut...
176
7,425
cognee
cognee/modules/pipelines/operations/log_pipeline_run_error.py
.py
from uuid import UUID from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.pipelines.models import PipelineRun, PipelineRunStatus from typing import Any from cognee.modules.pipelines.utils import summarize_run_info_data async def log_pipeline_run_error( pipeline_run_id...
38
1,000
cognee
cognee/modules/pipelines/operations/run_parallel.py
.py
from typing import Any, Callable, Generator, List import asyncio from ..tasks.task import Task def run_tasks_parallel(tasks: List[Task]) -> Callable[[Any], Generator[Any, Any, Any]]: async def parallel_run(*args, **kwargs): parallel_tasks = [asyncio.create_task(task.run(*args, **kwargs)) for task in tasks...
14
479
cognee
cognee/modules/pipelines/operations/run_tasks_with_telemetry.py
.py
import json from typing import Optional from cognee.modules.settings import get_current_settings from cognee.modules.users.models import User from cognee.shared.logging_utils import get_logger from cognee.shared.utils import send_telemetry from cognee import __version__ as cognee_version from cognee.modules.pipelines....
71
2,277
cognee
cognee/modules/pipelines/operations/log_pipeline_run_complete.py
.py
from uuid import UUID from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.pipelines.models import PipelineRun, PipelineRunStatus from typing import Any from cognee.modules.pipelines.utils import summarize_run_info_data async def log_pipeline_run_complete( pipeline_run...
32
941
cognee
cognee/modules/pipelines/operations/log_pipeline_run_initiated.py
.py
from uuid import UUID from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.pipelines.models import PipelineRun, PipelineRunStatus from cognee.modules.pipelines.utils import generate_pipeline_run_id async def log_pipeline_run_initiated(pipeline_id: UUID, pipeline_name: str, ...
24
826
cognee
cognee/modules/pipelines/operations/get_pipeline_status.py
.py
from uuid import UUID from sqlalchemy import select, func from cognee.infrastructure.databases.relational import get_relational_engine from ..models import PipelineRun from sqlalchemy.orm import aliased async def get_pipeline_status(dataset_ids: list[UUID], pipeline_name: str): db_engine = get_relational_engine()...
36
1,159
cognee
cognee/modules/pipelines/operations/run_tasks_base.py
.py
from typing import Optional from cognee.modules.observability import OtelStatusCode as StatusCode from cognee.shared.logging_utils import get_logger from cognee.modules.users.models import User from cognee.shared.utils import send_telemetry from cognee import __version__ as cognee_version from cognee.modules.pipelines...
286
10,825
cognee
cognee/modules/pipelines/operations/run_tasks.py
.py
import asyncio from typing import Any, Awaitable, Callable, List, Optional, Union from uuid import UUID from cognee.infrastructure.databases.graph import get_graph_engine from cognee.infrastructure.databases.relational import get_relational_engine from cognee.context_global_variables import set_database_global_contex...
226
9,555
cognee
cognee/modules/pipelines/operations/run_pipeline.py
.py
""" run_pipeline — execute a list of BoundTasks as a pipeline. This is the high-level API for the deferred-call pattern:: from cognee.modules.pipelines.tasks.task import task from cognee.modules.pipelines.operations.run_pipeline import run_pipeline classify = task(classify_documents) extract = task(...
101
3,344
cognee
cognee/modules/pipelines/operations/log_pipeline_run_start.py
.py
from uuid import UUID from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.pipelines.models import PipelineRun, PipelineRunStatus from typing import Any from cognee.modules.pipelines.utils import generate_pipeline_run_id, summarize_run_info_data async def log_pipeline_run_...
34
1,012
cognee
cognee/modules/pipelines/operations/run_tasks_data_item.py
.py
""" Data item processing functions for pipeline operations. This module contains reusable functions for processing individual data items within pipeline operations, supporting both incremental and regular processing modes. """ import os from typing import Any, Dict, AsyncGenerator, Optional from sqlalchemy import sel...
279
10,393
cognee
cognee/modules/pipelines/utils/generate_pipeline_id.py
.py
from uuid import NAMESPACE_OID, UUID, uuid5 def generate_pipeline_id(user_id: UUID, dataset_id: UUID, pipeline_name: str): return uuid5(NAMESPACE_OID, f"{str(user_id)}{pipeline_name}{str(dataset_id)}")
6
208
cognee
cognee/modules/pipelines/utils/generate_pipeline_run_id.py
.py
from uuid import UUID, uuid4 def generate_pipeline_run_id(pipeline_id: UUID, dataset_id: UUID): # pipeline_run_id must be unique per execution; keep args for API compatibility. return uuid4()
7
202
cognee
cognee/modules/pipelines/utils/summarize_run_info_data.py
.py
from typing import Any from cognee.modules.data.models import Data # ``run_info["data"]`` is audit-only metadata that is never read back from the # database. Persisting the full stringified payload makes the ``pipeline_runs`` # table grow without bound, because large inputs (e.g. raw text passed to # ``add``/``cognif...
29
1,123
cognee
cognee/modules/pipelines/methods/get_pipeline_runs_by_dataset.py
.py
from uuid import UUID from typing import Optional from sqlalchemy import select, func from sqlalchemy.orm import aliased from cognee.infrastructure.databases.relational import get_relational_engine from ..models import PipelineRun async def get_pipeline_runs_by_dataset(dataset_id: UUID): db_engine = get_relation...
35
1,038
cognee
cognee/modules/pipelines/methods/get_pipeline_run_by_dataset.py
.py
from uuid import UUID from sqlalchemy import select, func from cognee.infrastructure.databases.relational import get_relational_engine from ..models import PipelineRun from sqlalchemy.orm import aliased async def get_pipeline_run_by_dataset(dataset_id: UUID, pipeline_name: str): db_engine = get_relational_engine(...
34
1,063
cognee
cognee/modules/pipelines/methods/get_pipeline_run.py
.py
from uuid import UUID from sqlalchemy import select from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.pipelines.models import PipelineRun async def get_pipeline_run(pipeline_run_id: UUID): db_engine = get_relational_engine() async with db_engine.get_async_sess...
16
473
cognee
cognee/modules/pipelines/methods/reset_pipeline_run_status.py
.py
from uuid import UUID from cognee.modules.pipelines.utils.generate_pipeline_id import generate_pipeline_id from cognee.modules.pipelines.operations.log_pipeline_run_initiated import ( log_pipeline_run_initiated, ) async def reset_pipeline_run_status(user_id: UUID, dataset_id: UUID, pipeline_name: str): pipeli...
17
636
cognee
cognee/modules/pipelines/models/PipelineTask.py
.py
from datetime import datetime, timezone from sqlalchemy import Column, DateTime, ForeignKey, UUID from cognee.infrastructure.databases.relational import Base class PipelineTask(Base): __tablename__ = "pipeline_task" created_at = Column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)) ...
13
481
cognee
cognee/modules/pipelines/models/TaskRun.py
.py
from uuid import uuid4 from datetime import datetime, timezone from sqlalchemy import Column, DateTime, String, JSON from cognee.infrastructure.databases.relational import Base, UUID class TaskRun(Base): __tablename__ = "task_runs" id = Column(UUID, primary_key=True, default=uuid4) task_name = Column(St...
19
478
cognee
cognee/modules/pipelines/models/__init__.py
.py
from .PipelineContext import PipelineContext from .PipelineRun import PipelineRun, PipelineRunStatus from .PipelineRunInfo import ( PipelineRunInfo, PipelineRunStarted, PipelineRunYield, PipelineRunCompleted, PipelineRunErrored, ) from .DataItemStatus import DataItemStatus
11
294
cognee
cognee/modules/pipelines/models/PipelineRunInfo.py
.py
from typing import Any, Optional, List, Union from uuid import UUID from pydantic import BaseModel from cognee.modules.data.models.Data import Data class PipelineRunInfo(BaseModel): status: str pipeline_run_id: UUID dataset_id: UUID dataset_name: str # Data must be mentioned in typing to allow cus...
47
1,156
cognee
cognee/modules/pipelines/models/Pipeline.py
.py
from uuid import uuid4 from datetime import datetime, timezone from sqlalchemy import Column, DateTime, String, Text, UUID from sqlalchemy.orm import relationship, Mapped from cognee.infrastructure.databases.relational import Base from .PipelineTask import PipelineTask from .Task import Task class Pipeline(Base): ...
25
803
cognee
cognee/modules/pipelines/models/PipelineRun.py
.py
import enum from uuid import uuid4 from datetime import datetime, timezone from sqlalchemy import Column, DateTime, JSON, Enum, UUID, String from cognee.infrastructure.databases.relational import Base class PipelineRunStatus(enum.Enum): DATASET_PROCESSING_INITIATED = "DATASET_PROCESSING_INITIATED" DATASET_PRO...
28
949
cognee
cognee/modules/pipelines/models/Task.py
.py
from uuid import uuid4 from datetime import datetime, timezone from sqlalchemy.orm import relationship, Mapped from sqlalchemy import Column, String, DateTime, Text from cognee.infrastructure.databases.relational import Base, UUID from .PipelineTask import PipelineTask class Task(Base): __tablename__ = "tasks" ...
25
796
cognee
cognee/modules/pipelines/models/PipelineContext.py
.py
from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Set @dataclass class PipelineContext: """Typed runtime context for pipeline tasks. Tasks that need runtime values accept this as an explicit parameter:: async def add_data_points(data_points, ctx: PipelineContext ...
40
1,554
cognee
cognee/modules/pipelines/models/DataItemStatus.py
.py
import enum class DataItemStatus(str, enum.Enum): DATA_ITEM_PROCESSING_COMPLETED = "DATA_ITEM_PROCESSING_COMPLETED"
6
122
cognee
cognee/modules/ingestion/identify.py
.py
from typing import Optional from uuid import UUID from sqlalchemy import select from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.data.models.Data import Data from cognee.modules.users.models import User from .data_types import IngestionData async def identify(data: I...
44
1,772
cognee
cognee/modules/ingestion/save_data_to_file.py
.py
from typing import BinaryIO, Union, Optional from cognee.infrastructure.files.storage import get_file_storage, get_storage_config from .classify import classify import hashlib async def save_data_to_file( data: Union[str, BinaryIO], filename: str = None, file_extension: Optional[str] = None ): storage_config ...
36
1,246
cognee
cognee/modules/ingestion/discover_directory_datasets.py
.py
from os import path, listdir def discover_directory_datasets(root_dir_path: str, parent_dir: str = None): datasets = {} for file_or_dir in listdir(root_dir_path): if path.isdir(path.join(root_dir_path, file_or_dir)): dataset_name = file_or_dir if parent_dir is None else f"{parent_dir}.{fi...
24
787
cognee
cognee/modules/ingestion/classify.py
.py
from os import path from io import BufferedReader, BytesIO from typing import Union, BinaryIO from tempfile import SpooledTemporaryFile from cognee.modules.ingestion.exceptions import IngestionError from .data_types import TextData, BinaryData, S3BinaryData def classify( data: Union[str, BinaryIO], filename: str...
41
1,689
cognee
cognee/modules/ingestion/get_matched_datasets.py
.py
from .discover_directory_datasets import discover_directory_datasets def get_matched_datasets(data_path: str, dataset_name_to_match: str = None): datasets = discover_directory_datasets(data_path) matched_datasets = [] for dataset_name, dataset_files in datasets.items(): if dataset_name_to_match ...
14
475
cognee
cognee/modules/ingestion/exceptions/exceptions.py
.py
from cognee.exceptions import CogneeValidationError from fastapi import status class IngestionError(CogneeValidationError): def __init__( self, message: str = "Type of data sent to classify not supported.", name: str = "IngestionError", status_code=status.HTTP_415_UNSUPPORTED_MEDIA...
13
387
cognee
cognee/modules/ingestion/exceptions/__init__.py
.py
""" Custom exceptions for the Cognee API. This module defines a set of exceptions for handling various ingestion errors """ from .exceptions import ( IngestionError, )
10
174
cognee
cognee/modules/ingestion/data_types/IngestionData.py
.py
from typing import Protocol, BinaryIO, Union class IngestionData(Protocol): data: Union[str, BinaryIO] = None def get_data(self): raise NotImplementedError("Subclasses must implement get_data()") def get_identifier(self): raise NotImplementedError("Subclasses must implement get_identifie...
15
433
cognee
cognee/modules/ingestion/data_types/S3BinaryData.py
.py
import os from typing import Optional import time from contextlib import asynccontextmanager from cognee.infrastructure.files import get_file_metadata, FileMetadata from cognee.infrastructure.utils import run_sync from cognee.shared.logging_utils import get_logger from .IngestionData import IngestionData logger = get...
107
3,632
cognee
cognee/modules/ingestion/data_types/TextData.py
.py
from typing import BinaryIO, AsyncGenerator from contextlib import asynccontextmanager import hashlib from .IngestionData import IngestionData def create_text_data(data: str) -> "TextData": return TextData(data) class TextData(IngestionData): data: str = None metadata: dict = None def __init__(self...
40
1,035
cognee
cognee/modules/ingestion/data_types/BinaryData.py
.py
from typing import BinaryIO from contextlib import asynccontextmanager from cognee.infrastructure.files import get_file_metadata, FileMetadata from cognee.infrastructure.utils.run_sync import run_sync from .IngestionData import IngestionData def create_binary_data(data: BinaryIO): return BinaryData(data) class ...
41
1,076
cognee
cognee/modules/ontology/ontology_env_config.py
.py
"""This module contains the configuration for ontology handling.""" from functools import lru_cache from pydantic_settings import BaseSettings, SettingsConfigDict class OntologyEnvConfig(BaseSettings): """ Represents the configuration for ontology handling, including parameters for ontology file storage ...
46
1,267
cognee
cognee/modules/ontology/models.py
.py
from typing import Any class AttachedOntologyNode: """Lightweight wrapper to be able to parse any ontology solution and generalize cognee interface.""" def __init__(self, uri: Any, category: str): self.uri = uri self.name = self._extract_name(uri) self.category = category @static...
21
621
cognee
cognee/modules/ontology/get_default_ontology_resolver.py
.py
from typing import Optional from cognee.modules.ontology.base_ontology_resolver import BaseOntologyResolver from cognee.modules.ontology.ontology_config import Config from cognee.modules.ontology.ontology_env_config import get_ontology_env_config from cognee.modules.ontology.rdf_xml.RDFLibOntologyResolver import RDFLi...
72
2,906
cognee
cognee/modules/ontology/ontology_config.py
.py
from typing import TypedDict, Optional from cognee.modules.ontology.base_ontology_resolver import BaseOntologyResolver from cognee.modules.ontology.matching_strategies import MatchingStrategy class OntologyConfig(TypedDict, total=False): """Configuration containing ontology resolver. Attributes: ont...
25
660
cognee
cognee/modules/ontology/matching_strategies.py
.py
import difflib from abc import ABC, abstractmethod from typing import List, Optional class MatchingStrategy(ABC): """Abstract base class for ontology entity matching strategies.""" @abstractmethod def find_match(self, name: str, candidates: List[str]) -> Optional[str]: """Find the best match for ...
54
1,649
cognee
cognee/modules/ontology/base_ontology_resolver.py
.py
from abc import ABC, abstractmethod from typing import List, Tuple, Optional from cognee.modules.ontology.models import AttachedOntologyNode from cognee.modules.ontology.matching_strategies import MatchingStrategy, FuzzyMatchingStrategy class BaseOntologyResolver(ABC): """Abstract base class for ontology resolve...
43
1,477
cognee
cognee/modules/ontology/construct_data_points_and_edges_with_ontology.py
.py
from dataclasses import dataclass from typing import Optional from uuid import UUID from cognee.infrastructure.databases.provenance import EdgeIdentity from cognee.infrastructure.engine.models.Edge import Edge from cognee.modules.chunking.models import DocumentChunk from cognee.modules.engine.models import Entity, Ent...
339
12,403
cognee
cognee/modules/ontology/exceptions/exceptions.py
.py
from cognee.exceptions import CogneeSystemError from fastapi import status class OntologyInitializationError(CogneeSystemError): def __init__( self, message: str = "Ontology initialization failed", name: str = "OntologyInitializationError", status_code: int = status.HTTP_500_INTERN...
33
1,001
cognee
cognee/modules/ontology/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 OntologyInitializationError, FindClosestMatchError, GetSubgraphError
8
214
cognee
cognee/modules/ontology/rdf_xml/RDFLibOntologyResolver.py
.py
import os import difflib from cognee.shared.logging_utils import get_logger from collections import deque from typing import List, Tuple, Dict, Optional, Any, Union, IO from rdflib import Graph, URIRef, RDF, RDFS, OWL from rdflib.util import guess_format from cognee.modules.ontology.exceptions import ( OntologyIni...
349
13,784
cognee
cognee/modules/ontology/rdf_xml/rdf_ingest.py
.py
"""Ingest an RDF T-Box + A-Box into the cognee memory graph, preserving URIs. This is the "complementary layer" bridge: point cognee at an RDF knowledge base (the caller's system of record) and get memory-graph nodes that keep the stable external IRIs, rather than the default LLM-extraction path that canonicalizes ent...
267
9,918
cognee
cognee/modules/cloud/exceptions/CloudConnectionError.py
.py
from fastapi import status from cognee.exceptions.exceptions import CogneeConfigurationError class CloudConnectionError(CogneeConfigurationError): """Raised when the connection to the cloud service fails.""" def __init__( self, message: str = "Failed to connect to the cloud service. Please c...
16
527
cognee
cognee/modules/cloud/exceptions/CloudApiKeyMissingError.py
.py
from fastapi import status from cognee.exceptions.exceptions import CogneeConfigurationError class CloudApiKeyMissingError(CogneeConfigurationError): """Raised when the API key for the cloud service is not provided.""" def __init__( self, message: str = "Failed to connect to the cloud servic...
16
524
cognee
cognee/modules/cloud/operations/check_api_key.py
.py
import aiohttp from cognee.modules.cloud.exceptions import CloudConnectionError from cognee.shared.utils import create_secure_ssl_context async def check_api_key(auth_token: str): cloud_base_url = "http://localhost:8001" url = f"{cloud_base_url}/api/api-keys/check" headers = {"X-Api-Key": auth_token} ...
29
1,009
cognee
cognee/modules/session_lifecycle/models.py
.py
"""SQLAlchemy models for session lifecycle.""" from datetime import datetime, timezone from sqlalchemy import Column, DateTime, Float, Integer, String, Text, UUID from cognee.infrastructure.databases.relational import Base class SessionRecord(Base): """One row per (user, session_id). Narrow by design: lif...
127
4,873
cognee
cognee/modules/session_lifecycle/__init__.py
.py
"""Session lifecycle: metrics, status transitions, lock primitives. A thin relational layer on top of the session cache. The cache (Redis/FS) remains the source of truth for QA content and trace steps; this module only owns lifecycle (status), aggregate counters (tokens, cost, duration), and per-session lock primitive...
39
999
cognee
cognee/modules/session_lifecycle/usage_tracking.py
.py
"""Per-session token / cost tracking via a ContextVar scope. Call sites that know the active session_id wrap their work in ``track_session_usage(session_id, user_id)``. Inside that scope, ``LLMGateway.acreate_structured_output`` (and any other caller that opts in) calls ``record_llm_call`` after each LLM completion. T...
170
6,016
cognee
cognee/modules/session_lifecycle/metrics.py
.py
"""Session-lifecycle operations — thin wrappers around SessionRecord. All public functions are async and idempotent where possible: * ``ensure_and_touch_session`` upserts the row and bumps ``last_activity_at`` in a single DB round trip. * ``accumulate_usage`` atomically adds tokens / cost to the session row and, ...
494
18,001
cognee
cognee/modules/agent_memory/sanitization.py
.py
from __future__ import annotations from typing import Any from uuid import UUID MAX_SERIALIZED_VALUE_LENGTH = 1000 MAX_TRACE_CONTAINER_ITEMS = 20 def truncate_text(value: str, limit: int) -> str: """Bound stored trace strings so unusually large params/returns do not create oversized trace payloads.""" if le...
40
1,523
cognee
cognee/modules/agent_memory/runtime.py
.py
from __future__ import annotations import contextvars import inspect import json from dataclasses import dataclass from typing import Any, Optional from uuid import UUID from cognee.exceptions import CogneeValidationError from cognee.modules.observability import new_span from cognee.modules.users.methods import get_d...
564
21,587
cognee
cognee/modules/agent_memory/decorator.py
.py
from __future__ import annotations import functools import inspect import uuid from typing import Any, Callable, Optional from cognee.exceptions import CogneeValidationError from cognee.modules.users.models import User from cognee.modules.agent_memory.runtime import ( AgentMemoryContext, build_method_params,...
166
6,740
cognee
cognee/modules/agent_memory/__init__.py
.py
from cognee.modules.agent_memory.decorator import agent_memory from cognee.modules.agent_memory.runtime import get_current_agent_memory_context __all__ = ["agent_memory", "get_current_agent_memory_context"]
5
208
cognee
cognee/modules/metrics/operations/get_pipeline_run_metrics.py
.py
import time from sqlalchemy import select from sqlalchemy.sql import func from cognee.modules.data.models import Data from cognee.modules.data.models import GraphMetrics from cognee.modules.pipelines.models import PipelineRunInfo from cognee.infrastructure.databases.graph import get_graph_engine from cognee.infrastruc...
79
3,198
cognee
cognee/modules/data/exceptions/exceptions.py
.py
from cognee.exceptions import ( CogneeValidationError, CogneeConfigurationError, ) from fastapi import status class UnstructuredLibraryImportError(CogneeConfigurationError): def __init__( self, message: str = "Import error. Unstructured library is not installed.", name: str = "Unst...
86
2,802
cognee
cognee/modules/data/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 ( UnstructuredLibraryImportError, UnauthorizedDataAccessError, AmbiguousDataIdError, DatasetNotFoundError, DatasetTypeError, )
14
292
cognee
cognee/modules/data/processing/has_new_chunks.py
.py
from cognee.infrastructure.databases.vector import get_vector_engine_async from cognee.modules.chunking import DocumentChunk async def has_new_chunks( data_chunks: list[DocumentChunk], collection_name: str ) -> list[DocumentChunk]: vector_engine = await get_vector_engine_async() if not await vector_engin...
35
1,061
cognee
cognee/modules/data/processing/document_types/DltSourceDocument.py
.py
from os.path import basename from uuid import UUID from cognee.modules.chunking.Chunker import Chunker from .Document import Document class DltSourceDocument(Document): """Document type for a whole DLT-ingested source (one Data item per source). The raw data is a JSON manifest describing every unique row of...
45
1,681
cognee
cognee/modules/data/processing/document_types/PdfDocument.py
.py
from pypdf import PdfReader from cognee.shared.logging_utils import get_logger from cognee.modules.chunking.Chunker import Chunker from cognee.infrastructure.files.utils.open_data_file import open_data_file from .Document import Document logger = get_logger("PDFDocument") class PdfDocument(Document): type: str...
30
927
cognee
cognee/modules/data/processing/document_types/CodeFileDocument.py
.py
from .TextDocument import TextDocument class CodeFileDocument(TextDocument): """Document type for a supported code file (system_metadata.source == "code"). Exists as the classification target the cognify CODE route keys on (modules/cognify/routing.py): such items run the deterministic enola code grap...
15
540
cognee
cognee/modules/data/processing/document_types/CodeRepoDocument.py
.py
from .TextDocument import TextDocument class CodeRepoDocument(TextDocument): """Document type for a code-repository manifest (system_metadata.source == "code_repo"). Exists as the classification target the cognify CODE_REPO route keys on (modules/cognify/routing.py): the item's raw data is a small JSON m...
16
608
cognee
cognee/modules/data/processing/document_types/ImageDocument.py
.py
from cognee.infrastructure.llm.LLMGateway import LLMGateway from cognee.modules.chunking.Chunker import Chunker from .Document import Document class ImageDocument(Document): type: str = "image" async def transcribe_image(self): result = await LLMGateway.transcribe_image(self.raw_data_location) ...
23
707
cognee
cognee/modules/data/processing/document_types/TextDocument.py
.py
from cognee.modules.chunking.Chunker import Chunker from cognee.infrastructure.files.utils.open_data_file import open_data_file from .Document import Document class TextDocument(Document): type: str = "text" mime_type: str = "text/plain" async def read(self, chunker_cls: Chunker, max_chunk_size: int): ...
23
778
cognee
cognee/modules/data/processing/document_types/AudioDocument.py
.py
from cognee.modules.chunking.Chunker import Chunker from cognee.infrastructure.llm.LLMGateway import LLMGateway from .Document import Document class AudioDocument(Document): type: str = "audio" async def create_transcript(self): result = await LLMGateway.create_transcript(self.raw_data_location) ...
23
688
cognee
cognee/modules/data/processing/document_types/CsvDocument.py
.py
import io import csv from typing import Type from cognee.modules.chunking.Chunker import Chunker from cognee.infrastructure.files.utils.open_data_file import open_data_file from .Document import Document class CsvDocument(Document): type: str = "csv" mime_type: str = "text/csv" async def read(self, chun...
34
1,108
cognee
cognee/modules/data/processing/document_types/Document.py
.py
from typing import Optional, List from cognee.infrastructure.engine import DataPoint from cognee.modules.chunking.Chunker import Chunker class Document(DataPoint): name: str raw_data_location: str external_metadata: Optional[str] mime_type: str metadata: dict = {"index_fields": ["name"]} impor...
16
446
cognee
cognee/modules/data/processing/document_types/UnstructuredDocument.py
.py
from io import StringIO from typing import Any, AsyncGenerator from cognee.modules.chunking.Chunker import Chunker from cognee.modules.data.exceptions import UnstructuredLibraryImportError from cognee.infrastructure.files.utils.open_data_file import open_data_file from .Document import Document class UnstructuredDo...
37
1,263
cognee
cognee/modules/data/processing/document_types/exceptions/exceptions.py
.py
from cognee.exceptions import CogneeSystemError from fastapi import status class PyPdfInternalError(CogneeSystemError): """Internal pypdf error""" def __init__( self, message: str = "Error during PyPdf processing. Pdf is damaged or cannot be processed.", name: str = "PyPdfInternalErro...
15
435
cognee
cognee/modules/data/processing/document_types/exceptions/__init__.py
.py
""" Custom exceptions for the Cognee API. This module defines a set of exceptions for the different document types """ from .exceptions import PyPdfInternalError
8
164
cognee
cognee/modules/data/methods/get_datasets_by_name.py
.py
from typing import Union from uuid import UUID from sqlalchemy import select from cognee.infrastructure.databases.relational import get_relational_engine from ..models import Dataset async def get_datasets_by_name( dataset_names: Union[str, list[str]], user_id: UUID ) -> list[Dataset]: db_engine = get_relatio...
25
731
cognee
cognee/modules/data/methods/add_model_class_to_graph.py
.py
# PROPOSED TO BE DEPRECATED from typing import Type, Optional, get_args, get_origin from pydantic import BaseModel from cognee.infrastructure.databases.graph.graph_db_interface import GraphDBInterface async def add_model_class_to_graph( model_class: Type[BaseModel], graph: GraphDBInterface, parent: Optio...
74
2,601
cognee
cognee/modules/data/methods/get_unique_data_id.py
.py
from typing import Optional from uuid import uuid5, NAMESPACE_OID, UUID from sqlalchemy import select from cognee.modules.data.models.Data import Data from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.models import User async def get_unique_data_id( data_iden...
53
2,346
cognee
cognee/modules/data/methods/get_deletion_counts.py
.py
from typing import Optional from uuid import UUID from cognee.cli.exceptions import CliCommandException from cognee.infrastructure.databases.exceptions.exceptions import EntityNotFoundError from sqlalchemy import select from sqlalchemy.sql import func from cognee.infrastructure.databases.relational import get_relationa...
97
3,863
cognee
cognee/modules/data/methods/get_datasets.py
.py
from uuid import UUID from sqlalchemy import select from cognee.infrastructure.databases.relational import get_relational_engine from ..models import Dataset async def get_datasets(user_id: UUID) -> list[Dataset]: db_engine = get_relational_engine() async with db_engine.get_async_session() as session: ...
16
463
cognee
cognee/modules/data/methods/load_or_create_datasets.py
.py
from typing import List, Union from uuid import UUID from cognee.modules.data.models import Dataset from cognee.modules.data.methods.create_authorized_dataset import create_authorized_dataset from cognee.modules.data.exceptions import DatasetNotFoundError async def load_or_create_datasets( dataset_names: List[Un...
39
1,364
cognee
cognee/modules/data/methods/delete_dataset.py
.py
from cognee.modules.users.models import DatasetDatabase from sqlalchemy import select, text from cognee.modules.data.models import Dataset, Data from cognee.infrastructure.databases.utils.get_vector_dataset_database_handler import ( get_vector_dataset_database_handler, ) from cognee.infrastructure.databases.utils....
67
3,181