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/retrieval/entity_extractors/DummyEntityExtractor.py | .py | from typing import List
from cognee.modules.engine.models import Entity, EntityType
from cognee.infrastructure.entities.BaseEntityExtractor import (
BaseEntityExtractor,
)
class DummyEntityExtractor(BaseEntityExtractor):
"""Simple entity extractor that returns a constant entity."""
async def extract_ent... | 16 | 566 |
cognee | cognee/modules/retrieval/utils/used_graph_elements.py | .py | """Helpers to extract used graph element IDs from retriever results for session QA."""
from typing import Any, Dict, List, Optional
def is_edge_list(obj: Any) -> bool:
"""Duck-type: list of objects with node1, node2, attributes (CogneeGraph Edge)."""
if not isinstance(obj, list) or not obj:
return Fa... | 84 | 3,056 |
cognee | cognee/modules/retrieval/utils/node_edge_vector_search.py | .py | import asyncio
import time
from typing import Any, List, Optional
from cognee.shared.logging_utils import get_logger, ERROR
from cognee.infrastructure.databases.vector.exceptions import CollectionNotFoundError
from cognee.infrastructure.databases.vector import get_vector_engine_async
from cognee.modules.observability ... | 222 | 9,623 |
cognee | cognee/modules/retrieval/utils/query_decomposition.py | .py | from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional
from pydantic import BaseModel
from cognee.modules.graph.cognee_graph.CogneeGraphElements import Edge
class DecompositionMode(str, Enum):
"""Supported decomposition execution modes."""
ANSWER_PER_SUBQUERY = "an... | 88 | 2,557 |
cognee | cognee/modules/retrieval/utils/extract_uuid_from_node.py | .py | from typing import Any, Optional
from uuid import UUID
def extract_uuid_from_node(node: Any) -> Optional[UUID]:
"""
Try to pull a UUID string out of node.id or node.properties['id'],
then return a UUID instance (or None if neither exists).
"""
id_str = None
if not id_str:
id_str = geta... | 19 | 517 |
cognee | cognee/modules/retrieval/utils/references.py | .py | """Deterministic, LLM-free helpers for building reference (Evidence) blocks.
Evidence is grounded in the generated answer, not in whatever happened to be
retrieved before the LLM was called:
- ``format_chunk_references`` builds an Evidence block from retrieved vector
payloads, keeping only chunks that share signifi... | 370 | 13,849 |
cognee | cognee/modules/retrieval/utils/completion.py | .py | import asyncio
from typing import Any, List, Optional, Tuple, Type
from cognee.infrastructure.llm.LLMGateway import LLMGateway
from cognee.infrastructure.llm.pipeline_stage import pipeline_stage
from cognee.infrastructure.llm.prompts import render_prompt, read_query_prompt
from cognee.modules.observability import new_... | 150 | 5,429 |
cognee | cognee/modules/retrieval/utils/brute_force_triplet_search.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, List, Optional, Type, Union
from cognee.modules.observability import OtelStatusCode as StatusCode
from cognee.base_config import get_base_config
from cognee.infrastructure.databases.graph import get_graph_engine
from cognee.infrastructure.databases... | 365 | 16,312 |
cognee | cognee/modules/retrieval/utils/stop_words.py | .py | """Common stop words for text processing."""
# Common English stop words to filter out in text processing
DEFAULT_STOP_WORDS = {
"a",
"an",
"the",
"and",
"or",
"but",
"is",
"are",
"was",
"were",
"in",
"on",
"at",
"to",
"for",
"with",
"by",
"about"... | 72 | 883 |
cognee | cognee/modules/retrieval/utils/merge_results.py | .py | """Combine two retrievals of the same result shape into one ranked list.
Used when a single turn retrieves twice — a session turn runs the raw question and a
conversational rewrite of it — and the two result sets have to become one before the
retriever formats its context. Retrievers own the merge for their own shape ... | 119 | 4,909 |
cognee | cognee/modules/retrieval/utils/access_tracking.py | .py | """Utilities for tracking data access in retrievers."""
from datetime import datetime, timezone
from typing import Any, Optional
from uuid import UUID
import os
from cognee.infrastructure.databases.graph import get_graph_engine
from cognee.infrastructure.databases.relational import get_relational_engine
from cognee.mo... | 148 | 5,130 |
cognee | cognee/modules/retrieval/utils/validate_queries.py | .py | from cognee.modules.retrieval.exceptions.exceptions import QueryValidationError
def validate_queries(query, query_batch) -> tuple[bool, str]:
if query is not None and query_batch is not None:
return False, "Cannot provide both 'query' and 'query_batch'; use exactly one."
if query is None and query_bat... | 29 | 1,324 |
cognee | cognee/modules/retrieval/utils/description_to_codepart_search.py | .py | import asyncio
from cognee.shared.logging_utils import get_logger, setup_logging, ERROR
from typing import List
from cognee.infrastructure.databases.graph import get_graph_engine
from cognee.infrastructure.databases.vector import get_vector_engine_async
from cognee.modules.graph.cognee_graph.CogneeGraph import CogneeG... | 159 | 6,357 |
cognee | cognee/modules/retrieval/utils/global_context.py | .py | from typing import Any, Optional
from cognee.infrastructure.databases.vector.exceptions import CollectionNotFoundError
from cognee.modules.retrieval.utils.brute_force_triplet_search import get_memory_fragment
# Vector collection for the persisted GlobalContextSummary.text index.
GLOBAL_CONTEXT_SUMMARY_COLLECTION = "G... | 81 | 2,633 |
cognee | cognee/modules/retrieval/utils/query_state.py | .py | from typing import List
from cognee.modules.graph.cognee_graph.CogneeGraphElements import Edge
class QueryState:
"""Tracks per-query state across retrieval rounds."""
def __init__(self, triplets: List[Edge] = None, context_text: str = ""):
self.triplets = triplets or []
self.context_text = co... | 26 | 898 |
cognee | cognee/modules/retrieval/context_providers/SummarizedTripletSearchContextProvider.py | .py | from typing import List, Optional
from cognee.modules.retrieval.utils.completion import summarize_text
from cognee.modules.retrieval.context_providers.TripletSearchContextProvider import (
TripletSearchContextProvider,
)
class SummarizedTripletSearchContextProvider(TripletSearchContextProvider):
"""Context p... | 23 | 894 |
cognee | cognee/modules/retrieval/context_providers/DummyContextProvider.py | .py | from typing import List
from cognee.modules.engine.models import Entity
from cognee.infrastructure.context.BaseContextProvider import (
BaseContextProvider,
)
class DummyContextProvider(BaseContextProvider):
"""Simple context getter that returns a constant context."""
async def get_context(self, entitie... | 14 | 419 |
cognee | cognee/modules/retrieval/context_providers/TripletSearchContextProvider.py | .py | from typing import List, Optional
import asyncio
from cognee.infrastructure.context.BaseContextProvider import BaseContextProvider
from cognee.infrastructure.engine import DataPoint
from cognee.modules.graph.cognee_graph.CogneeGraph import CogneeGraph
from cognee.modules.retrieval.utils.brute_force_triplet_search impo... | 93 | 3,563 |
cognee | cognee/modules/graph/cognee_graph/CogneeGraphElements.py | .py | import numpy as np
from typing import List, Dict, Optional, Any, Union
from pydantic import BaseModel, ConfigDict, field_serializer
from cognee.modules.graph.exceptions import InvalidDimensionsError, DimensionOutOfRangeError
class Node(BaseModel):
"""
Represents a node in a graph.
Attributes:
id (... | 249 | 8,887 |
cognee | cognee/modules/graph/cognee_graph/CogneeAbstractGraph.py | .py | from abc import ABC, abstractmethod
from typing import List, Dict, Union
from cognee.modules.graph.cognee_graph.CogneeGraphElements import Node, Edge
from cognee.infrastructure.databases.graph.graph_db_interface import GraphDBInterface
class CogneeAbstractGraph(ABC):
"""
Abstract base class for representing a... | 39 | 1,093 |
cognee | cognee/modules/graph/cognee_graph/CogneeGraph.py | .py | import time
from cognee.shared.logging_utils import get_logger
from cognee.modules.graph.models.EdgeType import EdgeType
from typing import List, Dict, Union, Optional, Type, Iterable, Tuple, Callable, Any
from cognee.modules.graph.exceptions import (
EntityNotFoundError,
InvalidDimensionsError,
)
from cognee.... | 560 | 23,048 |
cognee | cognee/modules/graph/exceptions/exceptions.py | .py | from cognee.exceptions import CogneeValidationError
from fastapi import status
class EntityNotFoundError(CogneeValidationError):
"""Database returns nothing"""
def __init__(
self,
message: str = "The requested entity does not exist.",
name: str = "EntityNotFoundError",
status_... | 49 | 1,492 |
cognee | cognee/modules/graph/exceptions/__init__.py | .py | """
Custom exceptions for the Cognee API.
This module defines a set of exceptions for handling various graph errors
"""
from .exceptions import (
EntityNotFoundError,
EntityAlreadyExistsError,
InvalidDimensionsError,
DimensionOutOfRangeError,
)
| 13 | 263 |
cognee | cognee/modules/graph/utils/retrieve_existing_edges.py | .py | from collections.abc import Collection
from cognee.infrastructure.databases.graph import get_graph_engine
from cognee.infrastructure.databases.provenance import EdgeIdentity
async def find_existing_edge_identities(
edge_identities: Collection[EdgeIdentity],
) -> set[EdgeIdentity]:
"""Return the supplied edge... | 29 | 914 |
cognee | cognee/modules/graph/utils/expand_with_nodes_and_edges.py | .py | 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, EntityType
from cognee.modules.engine.utils import generate_edge_... | 230 | 7,870 |
cognee | cognee/modules/graph/utils/get_model_instance_from_graph.py | .py | from collections import OrderedDict
from threading import Lock
from pydantic_core import PydanticUndefined
from cognee.infrastructure.engine import DataPoint
from cognee.modules.storage.utils import copy_model
# Memoize extended-model classes across calls. ``copy_model`` returns a
# brand-new pydantic subclass on ev... | 133 | 5,976 |
cognee | cognee/modules/graph/utils/get_graph_from_model.py | .py | from collections import OrderedDict
from datetime import datetime, timezone
from threading import Lock
from typing import Tuple, List, Any, Dict, Optional
from cognee.infrastructure.engine import DataPoint, Edge
from cognee.modules.storage.utils import copy_model
from cognee.shared.logging_utils import get_logger
logg... | 340 | 12,536 |
cognee | cognee/modules/graph/utils/temporal_conflict_resolver.py | .py | """Temporal contradiction resolution for graph edges (issue #3631, Approach E).
When a *functional* (single-valued) relationship holds more than one target for
the same source — e.g. two documents name a different current CEO — the most
recent assertion is the current fact and the older ones are outdated. This
module ... | 101 | 4,196 |
cognee | cognee/modules/graph/utils/copy_edge.py | .py | def copy_edge(obj, overrides):
cls = obj.__class__
data = {c.name: getattr(obj, c.name) for c in cls.__table__.columns if not c.primary_key}
data.update(overrides)
return cls(**data)
| 8 | 201 |
cognee | cognee/modules/graph/utils/deduplicate_nodes_and_edges.py | .py | from cognee.infrastructure.engine import DataPoint
def deduplicate_nodes_and_edges(nodes: list[DataPoint], edges: list[dict]):
added_entities = {}
final_nodes = []
final_edges = []
for node in nodes:
if str(node.id) not in added_entities:
final_nodes.append(node)
added... | 21 | 598 |
cognee | cognee/modules/graph/utils/resolve_edges_to_text.py | .py | import string
from typing import List
from collections import Counter
from cognee.modules.graph.cognee_graph.CogneeGraphElements import Edge
from cognee.modules.retrieval.utils.stop_words import DEFAULT_STOP_WORDS
from cognee.shared.logging_utils import get_logger
logger = get_logger()
def _get_top_n_frequent_words... | 108 | 3,417 |
cognee | cognee/modules/graph/utils/get_entity_nodes_from_triplets.py | .py | def get_entity_nodes_from_triplets(triplets):
entity_nodes = []
seen_ids = set()
for triplet in triplets:
if hasattr(triplet, "node1") and triplet.node1 and triplet.node1.id not in seen_ids:
entity_nodes.append({"id": str(triplet.node1.id)})
seen_ids.add(triplet.node1.id)
... | 13 | 541 |
cognee | cognee/modules/graph/utils/prepare_edges_for_storage.py | .py | """Prepare edges for graph storage by ensuring each has default edge properties."""
from typing import Any, Dict, Iterable, List, Tuple
from cognee.modules.engine.utils import generate_edge_object_id
from cognee.shared.logging_utils import get_logger
logger = get_logger()
def _get_value(item: Any, field_name: str)... | 131 | 4,328 |
cognee | cognee/modules/graph/utils/convert_node_to_data_point.py | .py | from cognee.infrastructure.engine import DataPoint
def convert_node_to_data_point(node_data: dict) -> DataPoint:
subclass = find_subclass_by_name(DataPoint, node_data["type"])
return subclass(**node_data)
def get_all_subclasses(cls):
subclasses = []
for subclass in cls.__subclasses__():
sub... | 25 | 622 |
cognee | cognee/modules/graph/legacy/GraphRelationshipLedger.py | .py | from uuid import uuid5, NAMESPACE_OID
from datetime import datetime, timezone
from sqlalchemy import UUID, Column, DateTime, String, Index
from cognee.infrastructure.databases.relational import Base
class GraphRelationshipLedger(Base):
__tablename__ = "graph_relationship_ledger"
id = Column(
UUID,
... | 44 | 1,808 |
cognee | cognee/modules/graph/legacy/has_edges_in_legacy_ledger.py | .py | from typing import List
from sqlalchemy import and_, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from cognee.infrastructure.databases.relational import with_async_session
from cognee.modules.graph.models import Edge
from .GraphRelationshipLedger import GraphRelationshipLedger
@with_async_session
asyn... | 39 | 1,476 |
cognee | cognee/modules/graph/legacy/has_nodes_in_legacy_ledger.py | .py | from uuid import UUID
from typing import List, Tuple
from sqlalchemy import and_, select
from sqlalchemy.ext.asyncio import AsyncSession
from cognee.infrastructure.databases.graph import get_graph_engine
from cognee.infrastructure.databases.relational import with_async_session
from cognee.context_global_variables impo... | 69 | 2,345 |
cognee | cognee/modules/graph/legacy/mark_ledger_as_deleted.py | .py | from uuid import UUID
from datetime import datetime, timezone
from typing import List
from sqlalchemy import and_, or_, update
from sqlalchemy.ext.asyncio import AsyncSession
from cognee.infrastructure.databases.relational import with_async_session
from .GraphRelationshipLedger import GraphRelationshipLedger
BATCH_S... | 82 | 2,846 |
cognee | cognee/modules/graph/legacy/record_data_in_legacy_ledger.py | .py | from uuid import UUID
from typing import Dict, List, Tuple
from sqlalchemy.ext.asyncio import AsyncSession
from cognee.infrastructure.databases.relational import with_async_session
from cognee.infrastructure.engine.models.DataPoint import DataPoint
from .GraphRelationshipLedger import GraphRelationshipLedger
@with_a... | 36 | 1,071 |
cognee | cognee/modules/graph/methods/get_dataset_related_edges.py | .py | from uuid import UUID
from sqlalchemy.orm import aliased
from sqlalchemy import select, and_, exists
from sqlalchemy.ext.asyncio import AsyncSession
from cognee.infrastructure.databases.relational import with_async_session
from cognee.modules.graph.models import Edge
@with_async_session
async def get_dataset_related... | 35 | 991 |
cognee | cognee/modules/graph/methods/delete_dataset_related_nodes.py | .py | from uuid import UUID
from sqlalchemy import delete, select
from sqlalchemy.ext.asyncio import AsyncSession
from cognee.infrastructure.databases.relational import with_async_session
from cognee.modules.graph.models import Node
BATCH_SIZE = 1000
@with_async_session
async def delete_dataset_related_nodes(dataset_id: ... | 19 | 698 |
cognee | cognee/modules/graph/methods/delete_dataset_nodes_and_edges.py | .py | from uuid import UUID
from cognee.context_global_variables import backend_access_control_enabled
from cognee.infrastructure.databases.unified import get_unified_engine
from cognee.infrastructure.databases.provenance.markers import stores_provenance_in_graph
from cognee.modules.graph.legacy.has_nodes_in_legacy_ledger i... | 60 | 2,772 |
cognee | cognee/modules/graph/methods/upsert_nodes.py | .py | from typing import List, Optional
from uuid import NAMESPACE_OID, UUID, uuid5
from fastapi.encoders import jsonable_encoder
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.dialects.postgresql import insert
from cognee.modules.graph.models import Node
from cognee.infrastructure.engine.models.DataPoint i... | 77 | 3,098 |
cognee | cognee/modules/graph/methods/upsert_edges.py | .py | from uuid import UUID, uuid5, NAMESPACE_OID
from typing import Any, Dict, List, Optional, Tuple
from fastapi.encoders import jsonable_encoder
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.dialects.postgresql import insert
from cognee.modules.engine.utils import generate_edge_id
from cognee.modules.gr... | 84 | 3,160 |
cognee | cognee/modules/graph/methods/get_shared_slugs_losing_dataset_anchor.py | .py | from typing import List
from uuid import UUID
from sqlalchemy import and_, exists, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import aliased
from cognee.infrastructure.databases.relational import with_async_session
from cognee.modules.graph.models import Node
@with_async_session... | 75 | 2,366 |
cognee | cognee/modules/graph/methods/try_delete_data_by_graph_provenance.py | .py | from uuid import UUID
from cognee.infrastructure.databases.provenance import make_source_ref_key
from cognee.infrastructure.databases.provenance.markers import stores_provenance_in_graph
from cognee.infrastructure.databases.unified import get_unified_engine
async def try_delete_data_by_graph_provenance(dataset_id: U... | 23 | 863 |
cognee | cognee/modules/graph/methods/legacy_delete.py | .py | from uuid import UUID
from cognee.api.v1.exceptions.exceptions import DocumentSubgraphNotFoundError
from cognee.infrastructure.databases.graph import get_graph_engine
from cognee.infrastructure.engine import DataPoint
from cognee.modules.data.models import Data
from cognee.modules.graph.models.EdgeType import EdgeType... | 121 | 4,812 |
cognee | cognee/modules/graph/methods/get_orphaned_nodeset_labels_for_dataset.py | .py | from typing import List
from uuid import UUID
from sqlalchemy import and_, exists, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import aliased
from cognee.infrastructure.databases.relational import with_async_session
from cognee.modules.graph.models import Node
@with_async_session
asyn... | 61 | 2,089 |
cognee | cognee/modules/graph/methods/get_dataset_related_nodes.py | .py | from uuid import UUID
from sqlalchemy.orm import aliased
from sqlalchemy import exists, and_, select
from sqlalchemy.ext.asyncio import AsyncSession
from cognee.infrastructure.databases.relational import with_async_session
from cognee.modules.graph.models import Node
@with_async_session
async def get_dataset_related... | 38 | 1,072 |
cognee | cognee/modules/graph/methods/delete_data_related_edges.py | .py | from uuid import UUID
from sqlalchemy import and_, delete
from sqlalchemy.ext.asyncio import AsyncSession
from cognee.infrastructure.databases.relational import with_async_session
from cognee.modules.graph.models import Edge
@with_async_session
async def delete_data_related_edges(data_id: UUID, dataset_id: UUID, ses... | 14 | 463 |
cognee | cognee/modules/graph/methods/get_global_context_graph_inputs.py | .py | from __future__ import annotations
from collections.abc import Iterable
from dataclasses import dataclass
from uuid import UUID
from sqlalchemy import and_, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import aliased
from cognee.infrastructure.databases.provenance.markers import stores_... | 403 | 13,931 |
cognee | cognee/modules/graph/methods/get_formatted_graph_data.py | .py | from uuid import UUID
from cognee.infrastructure.databases.graph import get_graph_engine
from cognee.context_global_variables import set_database_global_context_variables
from cognee.modules.data.exceptions.exceptions import DatasetNotFoundError
from cognee.modules.data.methods import get_authorized_dataset
from cognee... | 48 | 1,737 |
cognee | cognee/modules/graph/methods/delete_data_related_nodes.py | .py | from uuid import UUID
from sqlalchemy import and_, delete
from sqlalchemy.ext.asyncio import AsyncSession
from cognee.infrastructure.databases.relational import with_async_session
from cognee.modules.graph.models import Node
@with_async_session
async def delete_data_related_nodes(data_id: UUID, dataset_id: UUID, ses... | 14 | 463 |
cognee | cognee/modules/graph/methods/delete_dataset_related_edges.py | .py | from uuid import UUID
from sqlalchemy import delete, select
from sqlalchemy.ext.asyncio import AsyncSession
from cognee.infrastructure.databases.relational import with_async_session
from cognee.modules.graph.models import Edge
BATCH_SIZE = 1000
@with_async_session
async def delete_dataset_related_edges(dataset_id: ... | 19 | 698 |
cognee | cognee/modules/graph/methods/get_data_related_nodes.py | .py | from uuid import UUID
from typing import Optional
from sqlalchemy.orm import aliased
from sqlalchemy import and_, exists, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from cognee.infrastructure.databases.relational import with_async_session
from cognee.modules.graph.models import Node
@with_async_ses... | 81 | 2,781 |
cognee | cognee/modules/graph/methods/has_data_related_nodes.py | .py | from uuid import UUID
from sqlalchemy import and_, select
from sqlalchemy.ext.asyncio import AsyncSession
from cognee.infrastructure.databases.relational import with_async_session
from cognee.modules.graph.models import Node
@with_async_session
async def has_data_related_nodes(dataset_id: UUID, data_id: UUID, sessio... | 17 | 570 |
cognee | cognee/modules/graph/methods/delete_from_graph_and_vector.py | .py | from typing import Dict, List
from cognee.infrastructure.databases.graph.get_graph_engine import get_graph_engine
from cognee.infrastructure.databases.vector.get_vector_engine import get_vector_engine_async
from cognee.modules.graph.legacy.mark_ledger_as_deleted import (
mark_ledger_edges_as_deleted,
mark_ledg... | 176 | 7,180 |
cognee | cognee/modules/graph/methods/sanitize_relational_payload.py | .py | from typing import Any
def sanitize_relational_payload(value: Any) -> Any:
"""Normalize payload values before relational writes.
Removes Postgres-incompatible NUL bytes from strings and recursively applies
the same cleanup to nested container values. Byte sequences are decoded with
replacement so inv... | 30 | 988 |
cognee | cognee/modules/graph/methods/delete_data_nodes_and_edges.py | .py | from uuid import UUID
from cognee.context_global_variables import backend_access_control_enabled
from cognee.infrastructure.databases.graph.get_graph_engine import get_graph_engine
from cognee.infrastructure.databases.vector.get_vector_engine import get_vector_engine_async
from cognee.modules.graph.legacy.has_edges_in... | 122 | 5,758 |
cognee | cognee/modules/graph/methods/get_data_related_edges.py | .py | from uuid import UUID
from typing import Optional
from sqlalchemy.orm import aliased
from sqlalchemy import and_, exists, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from cognee.infrastructure.databases.relational import with_async_session
from cognee.modules.graph.models import Edge
@with_async_ses... | 81 | 2,467 |
cognee | cognee/modules/graph/rdf/export.py | .py | """Export the cognee memory graph as RDF and query it with SPARQL.
cognee stores knowledge in a labeled property graph (Kuzu/Neo4j/etc.). This
module builds an RDF view over that graph so downstream consumers can query it
with SPARQL and link its identifiers out to other ontologies/datasets, without
being tied to one ... | 165 | 6,363 |
cognee | cognee/modules/graph/rdf/__init__.py | .py | from .export import (
DEFAULT_BASE_IRI,
graph_data_to_rdf,
export_memory_graph_to_rdf,
serialize_memory_graph,
query_memory_graph_sparql,
)
__all__ = [
"DEFAULT_BASE_IRI",
"graph_data_to_rdf",
"export_memory_graph_to_rdf",
"serialize_memory_graph",
"query_memory_graph_sparql",
]... | 16 | 321 |
cognee | cognee/modules/graph/models/Edge.py | .py | from datetime import datetime, timezone
from sqlalchemy import (
# event,
DateTime,
JSON,
UUID,
Text,
)
# from sqlalchemy.schema import DDL
from sqlalchemy.orm import Mapped, mapped_column
from cognee.infrastructure.databases.relational import Base
class Edge(Base):
__tablename__ = "edges"
... | 62 | 2,013 |
cognee | cognee/modules/graph/models/Node.py | .py | from datetime import datetime, timezone
from sqlalchemy import (
DateTime,
Index,
# event,
Text,
JSON,
UUID,
)
# from sqlalchemy.schema import DDL
from sqlalchemy.orm import Mapped, mapped_column
from cognee.infrastructure.databases.relational import Base
class Node(Base):
__tablename__ ... | 63 | 2,029 |
cognee | cognee/modules/graph/models/EdgeType.py | .py | from cognee.infrastructure.engine import DataPoint
class EdgeType(DataPoint):
relationship_name: str
number_of_edges: int
# identity_fields makes the id deterministic and namespaced by class
# (uuid5 of "EdgeType:<normalized relationship_name>") — same mechanism as
# Entity/EntityType. EdgeType.i... | 16 | 561 |
cognee | catalog/inventory_sync.py | .py | """Cross-repo drift check between the catalog and cognee-integrations/inventory.yml.
Fetches ``inventory.yml`` from ``topoteretes/cognee-integrations`` via the
GitHub REST API and cross-checks the ``slug`` values against every
``inventory_slug`` field in the local catalog.
Two directions of drift are reported:
* **C... | 179 | 6,030 |
cognee | catalog/__init__.py | .py | """Cognee Integrations Hub and Use-Case Gallery catalog.
Callers import the loader API directly:
from catalog.loader import CatalogEntry, CatalogError, load_catalog
See ``catalog/schema.json`` for the entry contract and
``docs/contributing/add-catalog-entry.md`` for the authoring guide.
"""
| 10 | 299 |
cognee | catalog/loader.py | .py | """Catalog loader for the Cognee Integrations Hub and Use-Case Gallery.
Reads every YAML file under ``catalog/entries/`` and returns a validated list of
:class:`CatalogEntry`. Validation happens in three passes:
1. Structural: entry conforms to ``catalog/schema.json``.
2. Naming: ``id`` matches the filename stem, and... | 236 | 7,890 |
cognee | catalog/tests/test_loader.py | .py | """Tests for the catalog loader's validation passes.
Each test writes YAML fixtures into a temporary entries root and asserts the
loader either returns the expected entries or raises ``CatalogError`` with a
message pointing at the specific problem. One smoke test loads the real shipped
catalog so a broken seed entry f... | 137 | 5,007 |
cognee | tests/test_exif_perceptualhash.py | .py | """
Standalone tests for EXIF and perceptual-hash helpers extracted from ImageLoader.
"""
import os
import tempfile
import pytest
from PIL import Image
# ------------------------------------------------------------------
# Standalone helper functions (copied from what would be added to image_loader.py)
# ---------... | 326 | 10,709 |
cognee | cognee-mcp/tests/test_tool_search_benchmark.py | .py | """Benchmark FastMCP's tool-search transforms against a hand-rolled alternative.
Exists to answer "should we have written this ourselves?" with numbers rather
than taste. Three things get measured over synthetic catalogs of mock tools:
* **Context cost** — bytes/tokens of the ``tools/list`` payload an agent pays on
... | 419 | 17,267 |
cognee | cognee-mcp/tests/test_tool_search.py | .py | """Behavior of the tool-search gating added in CLO-352.
The guarantee these tests protect: shrinking what ``tools/list`` advertises must
not shrink what is *callable*. Every unadvertised tool has to stay reachable
both directly by name (how the workspace UI calls its internals) and through
the ``call_tool`` proxy (how... | 286 | 10,946 |
cognee | cognee-mcp/tests/test_mcp_server_hardening.py | .py | import asyncio
import base64
import hashlib
import importlib
import json
import mimetypes
import os
import re
import sys
from pathlib import Path
import httpx
import pytest
MCP_ROOT = Path(__file__).resolve().parents[1] # cognee-mcp/
if str(MCP_ROOT) not in sys.path:
sys.path.insert(0, str(MCP_ROOT))
CogneeCli... | 1,230 | 41,731 |
cognee | cognee-mcp/tests/conftest.py | .py | """Flags MCP tools that no test ever exercises.
A tool is registered by decorator, so adding one is easy and forgetting to test
it is easier. At the end of the run this reports every name in
``server.registry`` that was never invoked.
What it measures is invocation, not assertion quality: a tool called incidentally
b... | 104 | 3,547 |
cognee | cognee-mcp/src/server.py | .py | import json
import os
import sys
import argparse
import asyncio
import base64
import subprocess
from collections import deque
from datetime import datetime, timezone
from pathlib import Path
from typing import Deque, List, Optional, Tuple
from cognee.modules.data.methods.get_datasets_by_name import get_datasets_by_name... | 2,116 | 81,587 |
cognee | cognee-mcp/src/test_client.py | .py | #!/usr/bin/env python3
"""Smoke-test the public Cognee MCP memory tools."""
import asyncio
import os
from contextlib import asynccontextmanager
from uuid import uuid4
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
try:
from .server import registry
from .tool_r... | 211 | 8,159 |
cognee | cognee-mcp/src/server_utils.py | .py | """Pure helpers for Cognee MCP tool input validation and result rendering."""
import json
import os
import re
from dataclasses import dataclass
from typing import Any, Callable, Optional
MAX_TOP_K = 100
COMPLETION_SEARCH_TYPES = {"GRAPH_COMPLETION", "GRAPH_COMPLETION_COT", "RAG_COMPLETION"}
VALID_DELETE_MODES = {"so... | 290 | 9,231 |
cognee | cognee-mcp/src/__init__.py | .py | import warnings
import sys
def _load_server_main():
"""Import the heavy server module lazily.
Importing server eagerly at package-import time pulls in the MCP SDK
and uvicorn/starlette, which aren't available in environments that
only depend on the core cognee library (e.g. the unit-tests CI job).
... | 73 | 2,038 |
cognee | cognee-mcp/src/client.py | .py | from datetime import timedelta
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
# Create server parameters for stdio connection
server_params = StdioServerParameters(
command="uv", # Executable
args=["--directory", ".", "run", "cognee"], # Optional command line a... | 61 | 2,384 |
cognee | cognee-mcp/src/cognee_client.py | .py | """
Cognee Client abstraction that supports both direct function calls and HTTP API calls.
This module provides a unified interface for interacting with Cognee, supporting:
- Direct mode: Directly imports and calls cognee functions (default behavior)
- API mode: Makes HTTP requests to a running Cognee FastAPI server
"... | 775 | 30,314 |
cognee | cognee-mcp/src/tool_registry.py | .py | """Tag-driven tool registration for the MCP server.
Wraps FastMCP's ``@mcp.tool`` so every tool declares which tier it belongs to
at its definition site, and the set of always-advertised tools is *derived*
from those declarations instead of maintained as a list somewhere else.
FastMCP's decorator returns the bare fun... | 65 | 2,533 |
cognee | cognee-mcp/src/retrieval_utils.py | .py | """Graph-backed document retrieval helpers for the Cognee MCP server."""
from __future__ import annotations
import json
from typing import Any, Literal
DOCUMENT_TYPES = {
"Document",
"TextDocument",
"PdfDocument",
"AudioDocument",
"ImageDocument",
"UnstructuredDocument",
"CsvDocument",
... | 393 | 12,641 |
cognee | cognee-mcp/src/strip_vectors.py | .py | """
Filter embedding vectors from cognee search results before returning to MCP clients.
Search results from CHUNKS and SUMMARIES types include `text_vector` fields containing
raw embedding vectors (e.g. 4096 floats, ~92KB per result). These are useless for LLM
clients and quickly exhaust context windows.
This module... | 28 | 1,165 |
cognee | cognee-mcp/src/codingagents/coding_rule_associations.py | .py | from uuid import NAMESPACE_OID, uuid5
from cognee.infrastructure.databases.graph import get_graph_engine
from cognee.infrastructure.databases.vector import get_vector_engine_async
from cognee.infrastructure.llm.prompts import render_prompt
from cognee.low_level import DataPoint
from cognee.infrastructure.llm import L... | 127 | 4,379 |
cognee | cognee-starter-kit/src/pipelines/default.py | .py | import os
import asyncio
import pathlib
from cognee import config, add, cognify, search, SearchType, prune, visualize_graph
async def main():
data_directory_path = str(
pathlib.Path(os.path.join(pathlib.Path(__file__).parent, ".data_storage")).resolve()
)
# Set up the data directory. Cognee will s... | 68 | 2,225 |
cognee | cognee-starter-kit/src/pipelines/custom-model.py | .py | import os
import asyncio
import pathlib
from cognee import config, add, cognify, search, SearchType, prune, visualize_graph
from cognee.low_level import DataPoint
async def main():
data_directory_path = str(
pathlib.Path(os.path.join(pathlib.Path(__file__).parent, ".data_storage")).resolve()
)
# ... | 88 | 2,822 |
cognee | cognee-starter-kit/src/pipelines/low_level.py | .py | """Cognee demo with simplified structure."""
from __future__ import annotations
import asyncio
import json
import logging
from collections import defaultdict
from pathlib import Path
from typing import Any, Dict, Iterable, List, Mapping
from uuid import UUID, uuid4
from pydantic import BaseModel
from cognee import ... | 268 | 7,791 |
cognee | examples/demos/truth_subspace_reranking_demo.py | .py | """Truth-Subspace Reranking — runnable demo.
What it shows
-------------
A finished "session" teaches the system a preference (here: the user cares about
*coffee*, not tea). We distill that into deterministic centroid slots, project
every corpus chunk onto those slots, and store the per-chunk coordinates on the
graph ... | 178 | 7,704 |
cognee | examples/demos/dynamic_multiple_weighted_edges_example.py | .py | import os
import asyncio
from os import path
# Note: OS environment variables need to be set before Cognee import
os.environ["ENABLE_BACKEND_ACCESS_CONTROL"] = "False"
from typing import Any
from pydantic import SkipValidation
import cognee
from cognee import visualize_graph
from cognee.infrastructure.engine import... | 124 | 3,972 |
cognee | examples/demos/pipeline_api_proposal.py | .py | """
Pipeline API Proposal — What the simplified API would look like
================================================================
This is NOT runnable code. It's a design document showing how the three
PRs from the review plan would work together from a user's perspective.
Plan:
PR A — Fix Task.__init__ to accep... | 309 | 12,214 |
cognee | examples/demos/custom_pipeline_single_object_example.py | .py | """
Custom pipeline example: LLM-powered entity extraction on DataPoint objects.
Demonstrates the deferred-call pipeline pattern (TaskSpec / BoundTask)
with typed DataPoint models, field annotations, LLM structured output,
and per-source freshness tracking via source_content_hash.
Usage:
uv run python examples/de... | 177 | 5,468 |
cognee | examples/demos/contradiction_feedback_demo.py | .py | """Contradiction detection + feedback, live and visualized step by step.
Runs the real pipeline on two conflicting one-line documents:
1. remember "Anna leads Falcon. Budget is 2M EUR."
2. remember "Marko leads Falcon. Budget is 5M EUR." -> contradicts edge
3. ask "What is the budget of Project Falcon?... | 242 | 9,930 |
cognee | examples/demos/feedback_score_shifting_example.py | .py | import asyncio
import cognee
from cognee import SearchType
from cognee.exceptions import CogneeConfigurationError
from cognee.infrastructure.databases.cache.config import get_cache_config
from cognee.memify_pipelines.apply_feedback_weights import apply_feedback_weights_pipeline
from cognee.modules.users.methods import... | 122 | 7,552 |
cognee | examples/demos/dlt_ingestion_example.py | .py | import asyncio
import os
import cognee
try:
import dlt
except ImportError:
dlt = None
from cognee.infrastructure.databases.graph.get_graph_engine import get_graph_engine
from cognee.modules.ontology.ontology_config import Config
from cognee.modules.ontology.rdf_xml.RDFLibOntologyResolver import RDFLibOntolog... | 204 | 6,175 |
cognee | examples/demos/local_ollama_example.py | .py | """Example: Running Cognee fully locally using Ollama.
Demonstrates local graph extraction and search using a recommended Ollama setup:
- LLM Provider: Ollama (Llama 3.1 8B)
- Embeddings: Ollama (nomic-embed-text)
- Local embedded database stack (Ladybug, LanceDB, SQLite)
Requires `ollama serve` running and the follo... | 91 | 3,117 |
cognee | examples/demos/hybrid_context_only_demo.py | .py | """Local playground for inspecting HybridRetriever retrieval, context, and completion.
This demo ingests a tiny Northstar Labs corpus, manually calls HybridRetriever
for retrieved objects, builds context from those objects, then runs completion
from that context. It prints each stage so retrieval behavior is visible.
... | 173 | 6,268 |
cognee | examples/demos/agentic_session_context_demo.py | .py | """Agentic session-context demo.
The agentic counterpart to ``live_session_context_feedback_demo.py``. Where the QA demo learns
lessons from conversation feedback, this one learns ``agent``-profile lessons from an agent's
tool/action traces — and, like that demo, the real lesson extraction is LLM-backed.
Run (full, r... | 516 | 18,130 |
cognee | examples/demos/session_feedback_example.py | .py | # ruff: noqa: E402
import os
import asyncio
# Set os.environ before importing Cognee: Cognee reads env-backed settings at import time, so values
# assigned later may not override defaults or `.env`. See https://docs.cognee.ai/setup-configuration/overview#using-os-environ
os.environ.setdefault("CACHING", "true")
os.env... | 119 | 4,602 |
cognee | examples/demos/custom_graph_model_entity_schema_definition.py | .py | import asyncio
import os
from cognee import SearchType, config, forget, recall, remember, visualize_graph
from cognee.low_level import DataPoint
# Define a custom graph model for programming languages.
class FieldType(DataPoint):
name: str = "Field"
class Field(DataPoint):
name: str
is_type: FieldType
... | 83 | 2,433 |
cognee | examples/demos/live_session_context_feedback_demo.py | .py | """Live session-context feedback demo.
Run with:
uv run python examples/demos/live_session_context_feedback_demo.py
Reuse already-ingested demo data and start a fresh session:
uv run python examples/demos/live_session_context_feedback_demo.py --no-ingest
This demo uses the real public ingestion and recall ... | 443 | 15,832 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.