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/infrastructure/databases/vector/turso/TursoVectorDatasetDatabaseHandler.py
.py
import os from uuid import UUID from typing import Optional from cognee.infrastructure.databases.vector.create_vector_engine import ( vector_engine_cache, ) from cognee.modules.users.models import User from cognee.modules.users.models import DatasetDatabase from cognee.base_config import get_base_config from cogne...
69
3,208
cognee
cognee/infrastructure/databases/vector/turso/TursoVectorAdapter.py
.py
"""Vector-database adapter backed by Turso / libSQL.""" import json import asyncio import threading from typing import Any, List, Optional from uuid import UUID from cognee.shared.logging_utils import get_logger from cognee.infrastructure.engine import DataPoint from cognee.infrastructure.engine.utils import parse_id...
518
21,634
cognee
cognee/infrastructure/databases/vector/models/ScoredResult.py
.py
from typing import Any, Dict, Optional from uuid import UUID from pydantic import BaseModel class ScoredResult(BaseModel): """ Represents a vector retrieval result with an identification and associated data. Attributes: - id (UUID): Unique identifier for the scored result. - score (float): Raw b...
22
676
cognee
cognee/infrastructure/databases/vector/models/PayloadSchema.py
.py
from typing import TypeVar PayloadSchema = TypeVar("PayloadSchema")
4
69
cognee
cognee/infrastructure/databases/vector/models/CollectionConfig.py
.py
from pydantic import BaseModel from .VectorConfig import VectorConfig class CollectionConfig(BaseModel): """ Represent a configuration for a collection of vector embeddings. This class is a subclass of BaseModel and encapsulates the configuration details for a vector collection. Public methods in...
22
598
cognee
cognee/infrastructure/databases/vector/models/VectorConfig.py
.py
from typing import Literal from pydantic import BaseModel class VectorConfig(BaseModel): """ Represent a configuration for vector operations, including distance metric and size. Public methods include: None Instance variables: distance, size """ distance: Literal["Cosine", "Dot"] size: i...
15
323
cognee
cognee/infrastructure/databases/vector/lancedb/LanceDBDatasetDatabaseHandler.py
.py
import os from uuid import UUID from typing import Optional from cognee.infrastructure.databases.vector.create_vector_engine import ( vector_engine_cache, ) from cognee.modules.users.models import User from cognee.modules.users.models import DatasetDatabase from cognee.base_config import get_base_config from cogne...
63
2,855
cognee
cognee/infrastructure/databases/vector/lancedb/LanceDBAdapter.py
.py
import asyncio import copy import inspect import threading import types from collections import OrderedDict from os import path from uuid import UUID from enum import Enum import lancedb from pydantic import BaseModel from lancedb.pydantic import LanceModel, Vector from typing import List, Optional, Union, get_args, ge...
1,472
65,209
cognee
cognee/infrastructure/databases/vector/lancedb/subprocess/proxy.py
.py
"""Main-process proxies that look like the slice of ``lancedb.AsyncConnection`` and table/builder types the cognee adapter uses, but route every call through a subprocess that only imports ``lancedb`` + ``pyarrow`` (no cognee). """ from __future__ import annotations import asyncio import multiprocessing as mp from ty...
400
15,241
cognee
cognee/infrastructure/databases/dataset_queue/__init__.py
.py
"""Dataset Queue — lightweight concurrency limiter for dataset operations. Configuration: * ``DATASET_QUEUE_ENABLED`` — environment variable. Truthy values turn the queue on; anything else (including unset) leaves it off. Default: off. * ``DATASET_QUEUE_MAX_CONCURRENT`` — environment variable. Integer value for max...
13
429
cognee
cognee/infrastructure/databases/dataset_queue/pinning.py
.py
"""Engine-cache pin predicate built on the dataset queue's slot registry.""" class DatasetQueuePinPredicate: """Pin predicate for ``closing_lru_cache``, bound to a named parameter. The predicate is True when the engine's database belongs to a dataset currently holding a dataset-queue slot: capacity evict...
67
3,209
cognee
cognee/infrastructure/databases/dataset_queue/queue.py
.py
"""Semaphore-backed dataset queue with per-task, per-dataset slot tracking. Each distinct dataset a task touches via :func:`set_database_global_context_variables` (which calls :meth:`DatasetQueue.ensure_slot` under the hood) takes its own slot against the shared budget. Ref-counting model (per (task, dataset)): Repe...
516
22,426
cognee
cognee/infrastructure/databases/utils/get_or_create_dataset_database.py
.py
import os from uuid import UUID from typing import Union, Optional from sqlalchemy import select from sqlalchemy.exc import IntegrityError from cognee.modules.data.methods import create_dataset from cognee.infrastructure.databases.relational import get_relational_engine from cognee.infrastructure.databases.vector imp...
137
5,239
cognee
cognee/infrastructure/databases/utils/engine_cache_ops.py
.py
"""Shared cache-management facade for the decorated engine factories. Graph and vector engines expose the same cache operations — evict, touch, is-cached, evict-by-database, evict-by-url, and their async variants — through one public instance per engine module: ``graph_engine_cache`` in ``get_graph_engine`` and ``vect...
128
6,684
cognee
cognee/infrastructure/databases/utils/closing_lru_cache.py
.py
"""LRU cache that closes entries after they leave the cache and caller scope. Cached values are live database engines (in subprocess mode: a worker process holding an exclusive on-disk file lock), so removal from the cache and death of the engine are separate events. This module is the single owner of that lifecycle; ...
1,095
51,206
cognee
cognee/infrastructure/databases/utils/resolve_dataset_database_connection_info.py
.py
from cognee.infrastructure.databases.utils.get_graph_dataset_database_handler import ( get_graph_dataset_database_handler, ) from cognee.infrastructure.databases.utils.get_vector_dataset_database_handler import ( get_vector_dataset_database_handler, ) from cognee.modules.users.models.DatasetDatabase import Data...
31
1,280
cognee
cognee/infrastructure/databases/utils/get_graph_dataset_database_handler.py
.py
from cognee.modules.users.models.DatasetDatabase import DatasetDatabase def get_graph_dataset_database_handler(dataset_database: DatasetDatabase) -> dict: from cognee.infrastructure.databases.dataset_database_handler.supported_dataset_database_handlers import ( supported_dataset_database_handlers, ) ...
11
438
cognee
cognee/infrastructure/databases/utils/get_vector_dataset_database_handler.py
.py
from cognee.modules.users.models.DatasetDatabase import DatasetDatabase def get_vector_dataset_database_handler(dataset_database: DatasetDatabase) -> dict: from cognee.infrastructure.databases.dataset_database_handler.supported_dataset_database_handlers import ( supported_dataset_database_handlers, ) ...
11
440
cognee
cognee/infrastructure/databases/relational/get_migration_relational_engine.py
.py
from .config import get_migration_config from .create_relational_engine import create_relational_engine def get_migration_relational_engine(): """ Create and return a relational database engine using the migration configuration. This function fetches the migration configuration details and uses them to c...
29
1,070
cognee
cognee/infrastructure/databases/relational/create_db_and_tables.py
.py
import asyncio from .get_relational_engine import get_relational_engine _create_db_lock = asyncio.Lock() async def create_db_and_tables(): """ Create a database and its tables. This asynchronous function retrieves the relational engine and calls its method to create a database. """ async wi...
19
443
cognee
cognee/infrastructure/databases/relational/create_relational_engine.py
.py
from functools import lru_cache from cognee.shared.lru_cache import DATABASE_MAX_LRU_CACHE_SIZE from sqlalchemy import URL from .sqlalchemy.SqlAlchemyAdapter import SQLAlchemyAdapter @lru_cache(maxsize=DATABASE_MAX_LRU_CACHE_SIZE) def create_relational_engine( db_path: str, db_name: str, db_host: str, ...
108
4,048
cognee
cognee/infrastructure/databases/relational/get_relational_engine.py
.py
from cognee.infrastructure.databases.relational.sqlalchemy.SqlAlchemyAdapter import ( SQLAlchemyAdapter, ) from .config import get_relational_config from .create_relational_engine import create_relational_engine def get_relational_engine() -> SQLAlchemyAdapter: """ Create and return a relational engine i...
26
874
cognee
cognee/infrastructure/databases/relational/ModelBase.py
.py
from sqlalchemy.orm import DeclarativeBase from sqlalchemy.ext.asyncio import AsyncAttrs class Base(AsyncAttrs, DeclarativeBase): """ Represents a base class for declarative models using SQLAlchemy. The Base class provides the foundation for creating ORM-mapped classes and manages the mapping of clas...
14
362
cognee
cognee/infrastructure/databases/relational/with_async_session.py
.py
from typing import Any, Callable, Optional from sqlalchemy.ext.asyncio import AsyncSession from .get_async_session import get_async_session def get_session_from_args(args): last_arg = args[-1] if isinstance(last_arg, AsyncSession): return last_arg return None def with_async_session(func: Callabl...
26
803
cognee
cognee/infrastructure/databases/relational/get_async_session.py
.py
from typing import AsyncGenerator from contextlib import asynccontextmanager from sqlalchemy.ext.asyncio import AsyncSession from .get_relational_engine import get_relational_engine @asynccontextmanager async def get_async_session(auto_commit=False) -> AsyncGenerator[AsyncSession, None]: db_engine = get_relation...
16
471
cognee
cognee/infrastructure/databases/relational/config.py
.py
import json import os from functools import lru_cache from typing import Union import pydantic from pydantic_settings import BaseSettings, SettingsConfigDict from cognee.base_config import get_base_config class RelationalConfig(BaseSettings): """ Configure database connection settings. """ db_path:...
176
6,769
cognee
cognee/infrastructure/databases/relational/sqlalchemy/SqlAlchemyAdapter.py
.py
import os import gc import asyncio from os import path import tempfile from uuid import UUID from typing import Optional from typing import AsyncGenerator, List from contextlib import asynccontextmanager from sqlalchemy.orm import joinedload from sqlalchemy.exc import NoResultFound from sqlalchemy import NullPool, even...
840
38,016
cognee
cognee/infrastructure/databases/relational/sqlalchemy/TursoAdapter.py
.py
"""Relational adapter for Turso (libSQL), a drop-in replacement for SQLite. A libSQL database file is a SQLite file, so cognee talks to Turso through the same aiosqlite driver, sqlite dialect, and sqlite-dialect Alembic migrations it already uses for the SQLite backend. ``TursoAdapter`` is therefore a thin subclass of...
149
6,207
cognee
cognee/infrastructure/databases/postgres/admin.py
.py
"""Postgres admin operations against the cluster's 'postgres' maintenance database. These helpers handle the boilerplate of opening an AUTOCOMMIT connection to the admin DB, running a CREATE/DROP DATABASE statement, and disposing of the maintenance engine. Callers supply connection credentials directly; this module is...
255
8,898
cognee
cognee/infrastructure/databases/postgres/__init__.py
.py
from .admin import ( create_pg_database_if_not_exists, drop_pg_database_if_exists, create_pg_schema_if_not_exists, drop_pg_schema_if_exists, dataset_schema_name, )
8
184
cognee
cognee/infrastructure/databases/unified/graph_vector_store_interface.py
.py
from cognee.infrastructure.databases.exceptions import UnsupportedProvenanceCapability class GraphVectorStoreInterface: """ Defines graph-provenance delete and rollback operations across graph and vector storage. Default implementations raise UnsupportedProvenanceCapability so existing adapters keep ...
45
1,393
cognee
cognee/infrastructure/databases/unified/__init__.py
.py
from .capabilities import EngineCapability from .graph_vector_store_interface import GraphVectorStoreInterface from .unified_store_engine import UnifiedStoreEngine from .get_unified_engine import get_unified_engine __all__ = [ "EngineCapability", "GraphVectorStoreInterface", "UnifiedStoreEngine", "get_...
12
339
cognee
cognee/infrastructure/databases/unified/unified_store_engine.py
.py
from __future__ import annotations from typing import Optional, cast from cognee.infrastructure.databases.exceptions import UnsupportedProvenanceCapability from cognee.infrastructure.databases.graph.graph_db_interface import GraphDBInterface from cognee.infrastructure.databases.vector.vector_db_interface import Vecto...
153
6,017
cognee
cognee/infrastructure/databases/unified/capabilities.py
.py
from enum import Flag, auto class EngineCapability(Flag): """Capability flags for unified store engines. Describes what operations a store engine supports: - GRAPH: Can perform graph operations (implements GraphDBInterface) - VECTOR: Can perform vector operations (implements VectorDBInterface) - ...
19
584
cognee
cognee/infrastructure/databases/unified/provenance_delete_planner.py
.py
"""Retry-safe planner for graph-provenance source-ref removal. Given snapshots of the matched nodes/edges and the set of source refs to remove from each, the planner decides which artifacts become *unowned* (no owning source ref remains -> hard delete) versus which merely *survive* (some ref remains -> detach the targ...
238
10,024
cognee
cognee/infrastructure/databases/unified/get_unified_engine.py
.py
from cognee.infrastructure.databases.graph.config import get_graph_context_config from cognee.infrastructure.databases.vector.config import get_vectordb_context_config from cognee.infrastructure.databases.graph import get_graph_engine from cognee.infrastructure.databases.vector import get_vector_engine_async from .cap...
127
5,114
cognee
cognee/infrastructure/databases/cache/models.py
.py
from typing import Any, Dict, List, Optional from pydantic import BaseModel, Field, field_validator from cognee.modules.agent_memory.sanitization import ( MAX_SERIALIZED_VALUE_LENGTH, sanitize_value, truncate_text, ) def _validate_list_of_str(value: object, key: str) -> List[str]: if not isinstance(va...
155
6,047
cognee
cognee/infrastructure/databases/cache/config.py
.py
from pydantic_settings import BaseSettings, SettingsConfigDict from functools import lru_cache from typing import Literal, Optional import pydantic class CacheConfig(BaseSettings): """ Configuration for distributed cache systems (e.g., Redis), used for locking or coordination. Attributes: - cache_bac...
117
5,890
cognee
cognee/infrastructure/databases/cache/cache_db_interface.py
.py
import uuid from abc import ABC, abstractmethod from contextlib import contextmanager from cognee.infrastructure.databases.cache.models import SessionAgentTraceEntry, SessionQAEntry class CacheDBInterface(ABC): """ Abstract base class for distributed cache coordination systems (e.g., Redis, Memcached). P...
337
10,906
cognee
cognee/infrastructure/databases/cache/get_cache_engine.py
.py
"""Factory to get the appropriate cache coordination engine (e.g., Redis).""" import os from functools import lru_cache from typing import Optional from cognee.shared.logging_utils import get_logger from cognee.infrastructure.databases.cache.config import get_cache_config from cognee.infrastructure.databases.cache.ca...
221
8,604
cognee
cognee/infrastructure/databases/cache/sql/tables.py
.py
"""Schema definitions for the SQL cache adapter (engine-agnostic: Postgres + SQLite). Tables live on a private MetaData (``cache_metadata``) — not the relational declarative Base and not alembic-managed — mirroring the Postgres graph adapter's create-on-init pattern. Payload columns use JSONB on Postgres and plain JSO...
187
6,703
cognee
cognee/infrastructure/databases/cache/sql/__init__.py
.py
from .SqlCacheAdapter import SqlCacheAdapter __all__ = ["SqlCacheAdapter"]
4
76
cognee
cognee/infrastructure/databases/cache/sql/SqlCacheAdapter.py
.py
"""Engine-agnostic SQL cache adapter (Postgres via asyncpg, SQLite via aiosqlite).""" import asyncio import json import time import uuid from datetime import datetime, timedelta, timezone from hashlib import sha256 from typing import List, Optional from pydantic import ValidationError from sqlalchemy import ( Nul...
1,206
54,018
cognee
cognee/infrastructure/databases/cache/fscache/FsCacheAdapter.py
.py
import json import os import uuid from datetime import datetime, timezone import diskcache as dc from pydantic import ValidationError from cognee.infrastructure.databases.cache.cache_db_interface import CacheDBInterface from cognee.infrastructure.databases.cache.models import SessionAgentTraceEntry, SessionQAEntry fr...
564
23,300
cognee
cognee/infrastructure/databases/cache/tapes/TapesCacheAdapter.py
.py
"""Filesystem-backed cache adapter that mirrors QA writes to a running tapes ingest server (https://github.com/papercomputeco/tapes). The FS adapter remains the source of truth for session state. Every new QA entry is additionally POSTed to `{tapes_ingest_url}/v1/ingest` as a provider- shaped request/response turn, so...
176
6,652
cognee
cognee/infrastructure/databases/cache/tapes/__init__.py
.py
from .TapesCacheAdapter import TapesCacheAdapter __all__ = ["TapesCacheAdapter"]
4
82
cognee
cognee/infrastructure/databases/cache/redis/RedisAdapter.py
.py
import json import uuid from contextlib import contextmanager from datetime import datetime, timezone import redis import redis.asyncio as aioredis from pydantic import BaseModel, ValidationError from cognee.infrastructure.databases.cache.cache_db_interface import CacheDBInterface from cognee.infrastructure.databases...
738
30,757
cognee
cognee/infrastructure/databases/dataset_database_handler/dataset_database_handler_interface.py
.py
from typing import Optional from uuid import UUID from abc import ABC, abstractmethod from cognee.modules.users.models.User import User from cognee.modules.users.models.DatasetDatabase import DatasetDatabase class DatasetDatabaseHandlerInterface(ABC): @classmethod @abstractmethod async def create_dataset...
81
4,463
cognee
cognee/infrastructure/databases/dataset_database_handler/supported_dataset_database_handlers.py
.py
from cognee.infrastructure.databases.graph.neo4j_driver.Neo4jAuraDevDatasetDatabaseHandler import ( Neo4jAuraDevDatasetDatabaseHandler, ) from cognee.infrastructure.databases.graph.neo4j_driver.Neo4jDatasetDatabaseHandler import ( Neo4jDatasetDatabaseHandler, ) from cognee.infrastructure.databases.graph.neo4j_d...
85
3,334
cognee
cognee/infrastructure/databases/dataset_database_handler/use_dataset_database_handler.py
.py
from .supported_dataset_database_handlers import supported_dataset_database_handlers def use_dataset_database_handler( dataset_database_handler_name, dataset_database_handler, dataset_database_provider ): supported_dataset_database_handlers[dataset_database_handler_name] = { "handler_instance": datase...
11
401
cognee
cognee/infrastructure/databases/graph/use_graph_adapter.py
.py
from .supported_databases import supported_databases def use_graph_adapter(vector_db_name, vector_db_adapter): supported_databases[vector_db_name] = vector_db_adapter
6
173
cognee
cognee/infrastructure/databases/graph/config.py
.py
"""This module contains the configuration for the graph database.""" import os from functools import lru_cache from pydantic_settings import BaseSettings, SettingsConfigDict import pydantic from pydantic import Field from cognee.base_config import get_base_config from cognee.root_dir import ensure_absolute_path from c...
202
8,563
cognee
cognee/infrastructure/databases/graph/graph_db_interface.py
.py
from uuid import UUID from abc import abstractmethod, ABC from typing import Optional, Dict, Any, List, Tuple, Type, Union from cognee.shared.logging_utils import get_logger from cognee.infrastructure.engine import DataPoint from cognee.infrastructure.databases.exceptions import UnsupportedProvenanceCapability from cog...
758
25,167
cognee
cognee/infrastructure/databases/graph/get_graph_engine.py
.py
"""Factory function to get the appropriate graph client based on the graph type.""" import inspect import os from numbers import Number from cognee.infrastructure.databases.dataset_queue.pinning import dataset_queue_pin_predicate from cognee.infrastructure.databases.utils.closing_lru_cache import closing_lru_cache fr...
609
25,924
cognee
cognee/infrastructure/databases/graph/neo4j_driver/Neo4jDatasetDatabaseHandler.py
.py
import asyncio import re from time import monotonic from typing import Optional from uuid import UUID from cognee.infrastructure.databases.exceptions import DatabaseCredentialsError from cognee.infrastructure.databases.graph import get_graph_config from cognee.infrastructure.databases.graph.get_graph_engine import ( ...
304
11,871
cognee
cognee/infrastructure/databases/graph/neo4j_driver/neo4j_community_containers.py
.py
"""Docker container lifecycle for per-dataset Neo4j Community instances. Neo4j Community edition supports exactly ONE database per running server — ``CREATE DATABASE`` is Enterprise-only. Per-dataset graph isolation on the free edition therefore means one server per dataset, realized here as one Docker container per d...
410
16,945
cognee
cognee/infrastructure/databases/graph/neo4j_driver/deadlock_retry.py
.py
import asyncio from functools import wraps from cognee.shared.logging_utils import get_logger from cognee.infrastructure.utils.calculate_backoff import calculate_backoff logger = get_logger("deadlock_retry") def deadlock_retry(max_retries=10): """ Decorator that automatically retries an asynchronous functi...
63
1,976
cognee
cognee/infrastructure/databases/graph/neo4j_driver/adapter.py
.py
"""Neo4j Adapter for Graph Database""" import json import asyncio from uuid import UUID from textwrap import dedent from neo4j import AsyncSession from neo4j import AsyncGraphDatabase from neo4j.exceptions import Neo4jError from contextlib import asynccontextmanager from typing import Optional, Any, List, Dict, Type, ...
2,497
91,086
cognee
cognee/infrastructure/databases/graph/neo4j_driver/neo4j_metrics_utils.py
.py
from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from cognee.infrastructure.databases.graph.neo4j_driver.adapter import Neo4jAdapter async def get_edge_density(adapter: Neo4jAdapter): """ Calculate the edge density of a graph in a Neo4j database. This function ex...
191
5,940
cognee
cognee/infrastructure/databases/graph/neo4j_driver/Neo4jCommunityDatasetDatabaseHandler.py
.py
import os import base64 import hashlib import secrets from uuid import UUID from typing import Optional from cryptography.fernet import Fernet from cognee.infrastructure.databases.graph import get_graph_config from cognee.infrastructure.databases.dataset_database_handler import ( DatasetDatabaseHandlerInterface, ...
196
7,948
cognee
cognee/infrastructure/databases/graph/neo4j_driver/Neo4jAuraDevDatasetDatabaseHandler.py
.py
import os import aiohttp import asyncio import base64 import hashlib from uuid import UUID from typing import Optional from urllib.parse import urlparse from cryptography.fernet import Fernet from aiohttp import BasicAuth from cognee.infrastructure.databases.graph import get_graph_config from cognee.modules.users.mode...
204
8,479
cognee
cognee/infrastructure/databases/graph/neo4j_driver/neo4j_community_adapter.py
.py
from typing import Any, Optional from .adapter import Neo4jAdapter from .neo4j_community_containers import get_container_manager class Neo4jCommunityAdapter(Neo4jAdapter): """Neo4j adapter bound to a per-dataset Docker container. Selected by ``_create_graph_engine`` when the graph dataset database handl...
42
1,700
cognee
cognee/infrastructure/databases/graph/kuzu/show_remote_kuzu_stats.py
.py
import asyncio from cognee.infrastructure.databases.graph.ladybug.remote_ladybug_adapter import ( RemoteLadybugAdapter, ) from cognee.infrastructure.databases.graph.config import get_graph_config async def main(): config = get_graph_config() adapter = RemoteLadybugAdapter( config.graph_database_ur...
36
1,065
cognee
cognee/infrastructure/databases/graph/kuzu/remote_kuzu_adapter.py
.py
"""Legacy import path for the remote Ladybug graph adapter.""" from cognee.infrastructure.databases.graph.ladybug.remote_ladybug_adapter import ( RemoteLadybugAdapter, ) RemoteKuzuAdapter = RemoteLadybugAdapter
9
218
cognee
cognee/infrastructure/databases/graph/kuzu/KuzuDatasetDatabaseHandler.py
.py
"""Legacy import path for the Ladybug dataset database handler.""" from cognee.infrastructure.databases.graph.ladybug.LadybugDatasetDatabaseHandler import ( LadybugDatasetDatabaseHandler, ) KuzuDatasetDatabaseHandler = LadybugDatasetDatabaseHandler
9
256
cognee
cognee/infrastructure/databases/graph/kuzu/adapter.py
.py
"""Legacy import path for the Ladybug graph adapter. The graph adapter was renamed from ``KuzuAdapter`` to ``LadybugAdapter`` on ``dev``. This module preserves the historical import paths so call sites and external tests that still spell things ``kuzu`` continue to work without churn. New code should import from ``cog...
24
677
cognee
cognee/infrastructure/databases/graph/kuzu/kuzu_migrate.py
.py
"""Legacy import path for Ladybug graph database migration helpers.""" from cognee.infrastructure.databases.graph.ladybug.ladybug_migrate import ( ladybug_migration, read_ladybug_storage_version, ) kuzu_migration = ladybug_migration read_kuzu_storage_version = read_ladybug_storage_version
11
301
cognee
cognee/infrastructure/databases/graph/kuzu/subprocess/proxy.py
.py
"""Main-process proxies that look like ``kuzu.Database`` / ``kuzu.Connection`` but route every call through a dedicated subprocess that only imports ``kuzu``. The subprocess machinery lives in the top-level ``cognee_db_workers`` package so the child never imports cognee. """ from __future__ import annotations import...
303
11,130
cognee
cognee/infrastructure/databases/graph/turso/tables.py
.py
"""Schema definitions for the Turso graph adapter (graph_node, graph_edge).""" from sqlalchemy import Table, Column, MetaData, String, DateTime, Index, ForeignKey, func _meta = MetaData() _node_table = Table( "graph_node", _meta, Column("id", String, primary_key=True), Column("name", String), Col...
45
1,422
cognee
cognee/infrastructure/databases/graph/turso/TursoGraphDatasetDatabaseHandler.py
.py
import os from uuid import UUID from typing import Optional from cognee.base_config import get_base_config from cognee.infrastructure.databases.graph.config import get_graph_config from cognee.infrastructure.databases.graph.get_graph_engine import ( create_graph_engine, graph_engine_cache, ) from cognee.module...
77
2,738
cognee
cognee/infrastructure/databases/graph/turso/adapter.py
.py
"""Turso/libSQL graph adapter using two tables (graph_node, graph_edge) over SQLAlchemy + aiosqlite.""" import asyncio import json from uuid import UUID from datetime import datetime, timezone from contextlib import asynccontextmanager from typing import AsyncIterator, Dict, Any, List, Union, Optional, Tuple, Type fr...
911
38,621
cognee
cognee/infrastructure/databases/graph/ladybug/ladybug_migrate.py
.py
#!/usr/bin/env python3 """Ladybug Database Migration Script — CLI entry point and re-exports. The implementation lives in ``cognee_db_workers.ladybug_migrate`` (pure stdlib, no cognee dependency) so the subprocess worker can use the same code. This module re-exports everything for backwards compatibility and provides ...
90
2,699
cognee
cognee/infrastructure/databases/graph/ladybug/LadybugDatasetDatabaseHandler.py
.py
import os from uuid import UUID from typing import Optional from cognee.infrastructure.databases.graph.get_graph_engine import ( graph_engine_cache, ) from cognee.base_config import get_base_config from cognee.modules.users.models import User from cognee.modules.users.models import DatasetDatabase from cognee.infr...
89
3,894
cognee
cognee/infrastructure/databases/graph/ladybug/adapter.py
.py
"""Adapter for Ladybug graph database.""" import os import json import asyncio import threading import tempfile from uuid import UUID, uuid5, NAMESPACE_OID # Importing this package registers the Windows DLL search path ladybug's native # extension needs, so it has to precede the ``ladybug`` imports below. See # cogne...
3,813
158,847
cognee
cognee/infrastructure/databases/graph/ladybug/remote_ladybug_adapter.py
.py
"""Adapter for remote Ladybug graph database via REST API.""" import json from uuid import UUID from typing import List, Optional, Tuple import aiohttp from cognee.infrastructure.databases.graph.ladybug.adapter import LadybugAdapter from cognee.shared.logging_utils import get_logger from cognee.shared.utils import c...
205
7,559
cognee
cognee/infrastructure/databases/graph/postgres/tables.py
.py
"""Schema definitions for the Postgres graph adapter (graph_node, graph_edge).""" from sqlalchemy import Table, Column, MetaData, String, DateTime, Index, ForeignKey, func, text from sqlalchemy.dialects.postgresql import JSONB, ARRAY _meta = MetaData() def _provenance_columns() -> list: """Four graph-provenance...
98
3,898
cognee
cognee/infrastructure/databases/graph/postgres/__init__.py
.py
"""Postgres graph backend (graph-as-tables). DEMO: Using Postgres as a graph store is currently a demo feature and is not production-ready. Use it to demo keeping relational metadata, PGVector, and graph state in a single Postgres service, but rely on a graph-native backend such as Kuzu or Neo4j for production workloa...
11
470
cognee
cognee/infrastructure/databases/graph/postgres/PostgresGraphDatasetDatabaseHandler.py
.py
from uuid import UUID from typing import Optional from cognee.infrastructure.databases.graph.config import get_graph_config from cognee.infrastructure.databases.graph.get_graph_engine import ( create_graph_engine, graph_engine_cache, ) from cognee.infrastructure.databases.postgres import ( create_pg_databa...
104
4,255
cognee
cognee/infrastructure/databases/graph/postgres/adapter.py
.py
"""Postgres graph adapter using two tables (graph_node, graph_edge) over SQLAlchemy + asyncpg. DEMO: Using Postgres as a graph store is currently a demo feature and is not production-ready. Use it to demo keeping relational metadata, PGVector, and graph state in a single Postgres service, but rely on a graph-native ba...
1,651
68,697
cognee
cognee/infrastructure/databases/graph/postgres/PostgresGraphSharedDatasetDatabaseHandler.py
.py
from uuid import UUID from typing import Optional from cognee.infrastructure.databases.graph.config import get_graph_config from cognee.infrastructure.databases.graph.get_graph_engine import ( create_graph_engine, graph_engine_cache, ) from cognee.infrastructure.databases.relational import get_relational_confi...
135
5,383
cognee
cognee/infrastructure/databases/graph/neptune_driver/exceptions.py
.py
"""Neptune Analytics Exceptions This module defines custom exceptions for Neptune Analytics operations. """ from cognee.exceptions import ( CogneeSystemError, CogneeTransientError, CogneeValidationError, CogneeConfigurationError, ) from fastapi import status class NeptuneAnalyticsError(CogneeSystemE...
121
4,166
cognee
cognee/infrastructure/databases/graph/neptune_driver/__init__.py
.py
"""Neptune Analytics Driver Module This module provides the Neptune Analytics adapter and utilities for interacting with Amazon Neptune Analytics graph databases. """ from .adapter import NeptuneGraphDB from . import neptune_utils from . import exceptions __all__ = [ "NeptuneGraphDB", "neptune_utils", "e...
16
334
cognee
cognee/infrastructure/databases/graph/neptune_driver/neptune_utils.py
.py
"""Neptune Utilities This module provides utility functions for Neptune Analytics operations including connection management, URL parsing, and Neptune-specific configurations. """ import re from typing import Optional, Dict, Any, Tuple from urllib.parse import urlparse from cognee.shared.logging_utils import get_log...
225
6,374
cognee
cognee/infrastructure/databases/graph/neptune_driver/adapter.py
.py
"""Neptune Analytics Adapter for Graph Database""" import json from typing import Optional, Any, List, Dict, Type, Tuple from uuid import UUID from cognee.shared.logging_utils import get_logger from cognee.infrastructure.databases.graph.graph_db_interface import ( GraphDBInterface, NodeData, EdgeData, ...
1,555
58,322
cognee
cognee/infrastructure/session/session_context_models.py
.py
from enum import Enum from typing import Annotated, List, Literal, Optional from pydantic import BaseModel, Field, field_validator, model_validator VALID_RATINGS = {"helpful", "harmful"} MAX_CONTEXT_CONTENT_CHARS = 280 MIN_CANDIDATE_CONFIDENCE = 0.75 class ContextSection(str, Enum): """Sections under which acti...
498
17,199
cognee
cognee/infrastructure/session/session_context_builder.py
.py
"""Deterministic builder, ranker, and candidate applier for the active session-context layer. This module loads stored active ``SessionContextEntry`` rows, ranks them with a deterministic lexical ranker (no LLM), applies per-section and total character budgets, and renders a compact four-heading guidance block. It als...
459
16,531
cognee
cognee/infrastructure/session/agent_context_extraction.py
.py
"""Turn agent trace evidence into agent-profile session-context lessons. Flow: 1. LIVE (cheap, no LLM) — runs after each trace is stored; turns an errored step into a failure_lessons candidate built straight from its error text. 2. BATCH (LLM) — proposes reasoning-heavy sections (tool_rules, success_patterns, ...
396
14,867
cognee
cognee/infrastructure/session/__init__.py
.py
from cognee.infrastructure.session.get_session_manager import get_session_manager from cognee.infrastructure.session.session_manager import SessionManager __all__ = ["SessionManager", "get_session_manager"]
5
208
cognee
cognee/infrastructure/session/feedback_detection.py
.py
"""Session turn analysis from user messages via LLM.""" from cognee.infrastructure.llm.LLMGateway import LLMGateway from cognee.infrastructure.llm.prompts import read_query_prompt from cognee.infrastructure.session.feedback_models import SessionTurnAnalysis from cognee.shared.logging_utils import get_logger logger = ...
111
4,096
cognee
cognee/infrastructure/session/session_agent_trace.py
.py
"""Per-step feedback generation for agent trace entries. A trace step records one agent method call. Its ``session_feedback`` is a one-line summary of what the step did — generated from the step's return value via an LLM, or falling back to a deterministic success/failure line. Storage of trace steps stays in ``Sessio...
81
2,902
cognee
cognee/infrastructure/session/feedback_models.py
.py
from pydantic import BaseModel, Field, field_validator from cognee.infrastructure.session.session_context_models import ( CandidateContextUpdate, CandidateContextUpdateVariant, ServedContextRating, ) class SessionTurnAnalysis(BaseModel): """ Result of analyzing a user message for answer routing a...
93
3,101
cognee
cognee/infrastructure/session/session_embeddings.py
.py
"""Vector helpers for session QA recall.""" from uuid import UUID from cognee.infrastructure.databases.vector.exceptions import CollectionNotFoundError from cognee.infrastructure.engine import DataPoint from cognee.shared.logging_utils import get_logger logger = get_logger("session_embeddings") # Number of vector-r...
172
5,454
cognee
cognee/infrastructure/session/session_persist_watermark.py
.py
"""Per-session watermark for persisting session Q&A into the knowledge graph. Session persistence (``improve(session_ids=...)`` -> ``extract_user_sessions`` -> ``cognify_session``) previously serialized the ENTIRE session on every run: each time a session grew, the full history was re-added, re-embedded and re-extract...
97
3,707
cognee
cognee/infrastructure/session/get_session_manager.py
.py
from uuid import UUID from cognee.infrastructure.databases.cache import get_cache_engine from cognee.infrastructure.session.session_manager import SessionManager def get_session_manager(dataset_id: UUID | None = None) -> SessionManager: """ Return a SessionManager instance. Uses the cache engine from ge...
22
844
cognee
cognee/infrastructure/session/session_concurrent_turn.py
.py
"""Session reads and writes for one concurrent turn. A concurrent turn does not chain analysis before retrieval the way the sequential path does. It reads the session once, then runs the turn analysis and the answer concurrently, and applies the analysis after both land. These are the session-side pieces of that: the ...
249
9,461
cognee
cognee/infrastructure/session/session_manager.py
.py
import uuid from typing import Any from cognee.context_global_variables import current_dataset_id, session_user from cognee.infrastructure.databases.cache import SessionAgentTraceEntry, SessionQAEntry from cognee.infrastructure.databases.cache.cache_db_interface import CacheDBInterface from cognee.infrastructure.datab...
908
35,767
cognee
cognee/infrastructure/session/session_turn.py
.py
"""Processing one session turn: interpret the user message, apply its feedback to the stored session context, and assemble the prompt for the answer. These are the helpers behind SessionManager's turn flow. Like ``session_context_builder``, they take the SessionManager as a parameter and call back into its storage fac...
429
15,111
cognee
cognee/infrastructure/utils/calculate_backoff.py
.py
import random # Default retry settings DEFAULT_MAX_RETRIES = 5 DEFAULT_INITIAL_BACKOFF = 1.0 # seconds DEFAULT_BACKOFF_FACTOR = 2.0 # exponential backoff multiplier DEFAULT_JITTER = 0.1 # 10% jitter to avoid thundering herd def calculate_backoff( attempt: int, initial_backoff: float = DEFAULT_INITIAL_BACK...
31
976
cognee
cognee/infrastructure/utils/run_sync.py
.py
import asyncio import threading from collections.abc import Coroutine from typing import Any, TypeVar T = TypeVar("T") def run_sync( coro: Coroutine[Any, Any, T], running_loop: asyncio.AbstractEventLoop | None = None, timeout: float | None = None, ) -> T | None: result = None exception = None ...
42
999
cognee
cognee/infrastructure/utils/run_async.py
.py
import asyncio import inspect from collections.abc import Callable from concurrent.futures import Executor from functools import partial from typing import Any, TypeVar T = TypeVar("T") async def run_async( func: Callable[..., T], *args: Any, loop: asyncio.AbstractEventLoop | None = None, executor: E...
30
748