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/data/methods/get_authorized_dataset_by_name.py
.py
from typing import Optional from cognee.modules.users.models import User from cognee.modules.data.methods.get_authorized_existing_datasets import ( get_authorized_existing_datasets, ) from ..models import Dataset async def get_authorized_dataset_by_name( dataset_name: str, user: User, permission_type: str )...
28
874
cognee
cognee/modules/data/methods/delete_data.py
.py
from uuid import UUID from cognee.modules.data.exceptions.exceptions import InvalidTableAttributeError from cognee.modules.data.models import Data from cognee.infrastructure.databases.relational import get_relational_engine async def delete_data(data: Data, dataset_id: UUID): """Delete a data record from the dat...
23
657
cognee
cognee/modules/data/methods/get_last_added_data.py
.py
from uuid import UUID from typing import Optional from sqlalchemy import select from cognee.modules.data.models import Data, Dataset from cognee.infrastructure.databases.relational import get_relational_engine async def get_last_added_data(dataset_id: UUID) -> Optional[Data]: db_engine = get_relational_engine() ...
23
665
cognee
cognee/modules/data/methods/has_dataset_data.py
.py
from uuid import UUID from sqlalchemy import select from sqlalchemy.sql import func from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.data.models import Data async def has_dataset_data(dataset_id: UUID) -> bool: db_engine = get_relational_engine() async with d...
18
549
cognee
cognee/modules/data/methods/get_authorized_existing_datasets.py
.py
from typing import Union from uuid import UUID from cognee.modules.data.models import Dataset from cognee.modules.users.models import User from cognee.modules.data.methods.get_dataset_ids import get_dataset_ids from cognee.modules.users.permissions.methods import get_all_user_permission_datasets from cognee.modules.us...
40
1,448
cognee
cognee/modules/data/methods/get_dataset_databases.py
.py
from sqlalchemy import select from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.models import DatasetDatabase async def get_dataset_databases() -> list[DatasetDatabase]: db_engine = get_relational_engine() async with db_engine.get_async_session() as sessi...
13
440
cognee
cognee/modules/data/methods/get_dataset_ids.py
.py
from typing import Union from uuid import UUID from cognee.modules.data.exceptions import DatasetTypeError from cognee.modules.data.methods import get_datasets async def get_dataset_ids(datasets: Union[list[str], list[UUID]], user): """ Function returns dataset IDs necessary based on provided input. It t...
41
1,618
cognee
cognee/modules/data/methods/get_data.py
.py
from typing import Optional from uuid import UUID from sqlalchemy import select from cognee.infrastructure.databases.relational import get_relational_engine from ..exceptions import AmbiguousDataIdError, UnauthorizedDataAccessError from ..models import Data, Dataset from .resolve_data_id import resolve_data_id asy...
84
3,113
cognee
cognee/modules/data/methods/get_unique_dataset_id.py
.py
from uuid import UUID, uuid5, NAMESPACE_OID from typing import Union from sqlalchemy import select from cognee.modules.data.models.Dataset import Dataset from cognee.modules.users.models import User from cognee.infrastructure.databases.relational import get_relational_engine async def get_unique_dataset_id(dataset_n...
83
3,648
cognee
cognee/modules/data/methods/get_authorized_dataset.py
.py
from uuid import UUID from typing import Optional from cognee.modules.users.models import User from cognee.modules.data.methods.get_authorized_existing_datasets import ( get_authorized_existing_datasets, ) from ..models import Dataset async def get_authorized_dataset( user: User, dataset_id: UUID, permission...
30
846
cognee
cognee/modules/data/methods/create_dataset.py
.py
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import joinedload from cognee.infrastructure.databases.relational import with_async_session from cognee.modules.data.models import Dataset from cognee.modules.data.methods.get_un...
52
1,976
cognee
cognee/modules/data/methods/get_dataset.py
.py
from typing import Optional from uuid import UUID from cognee.infrastructure.databases.relational import get_relational_engine from ..models import Dataset async def get_dataset(user_id: UUID, dataset_id: UUID) -> Optional[Dataset]: db_engine = get_relational_engine() async with db_engine.get_async_session()...
17
491
cognee
cognee/modules/data/methods/resolve_data_id.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 import Data async def resolve_data_id(dataset_id: UUID, data_id: UUID) -> Optional[UUID]: """Resolve a caller-supplied data...
38
1,419
cognee
cognee/modules/data/methods/get_dataset_data.py
.py
from uuid import UUID from sqlalchemy import select from cognee.modules.data.models import Data from cognee.infrastructure.databases.relational import get_relational_engine async def get_dataset_data(dataset_id: UUID) -> list[Data]: db_engine = get_relational_engine() async with db_engine.get_async_session()...
18
544
cognee
cognee/modules/data/methods/create_authorized_dataset.py
.py
import logging from cognee.infrastructure.databases.relational import get_relational_engine from cognee.infrastructure.databases.exceptions import EntityNotFoundError from cognee.modules.users.models import User from cognee.modules.data.models import Dataset from cognee.modules.users.methods import get_user from cogne...
55
2,018
cognee
cognee/modules/data/methods/check_dataset_name.py
.py
def check_dataset_name(dataset_name: str): if "." in dataset_name or " " in dataset_name: raise ValueError("Dataset name cannot contain spaces or dots.")
4
166
cognee
cognee/modules/data/models/GraphMetrics.py
.py
from datetime import datetime, timezone from sqlalchemy.sql import func from sqlalchemy import Column, DateTime, Float, Integer, JSON, UUID from cognee.infrastructure.databases.relational import Base from uuid import uuid4 class GraphMetrics(Base): __tablename__ = "graph_metrics" # TODO: Change ID to refle...
29
1,123
cognee
cognee/modules/data/models/answers_data.py
.py
from datetime import datetime, timezone from uuid import uuid4 from sqlalchemy import Column, DateTime, JSON, UUID from cognee.modules.data.models.answers_base import AnswersBase class Answers(AnswersBase): __tablename__ = "eval_answers" id = Column(UUID, primary_key=True, default=uuid4) payload = Colu...
16
439
cognee
cognee/modules/data/models/Dataset.py
.py
from uuid import uuid4 from typing import List from datetime import datetime, timezone from sqlalchemy.orm import relationship, Mapped from sqlalchemy import Column, Text, DateTime, UUID from cognee.infrastructure.databases.relational import Base class Dataset(Base): __tablename__ = "datasets" id = Column(UU...
50
1,703
cognee
cognee/modules/data/models/DatasetConfiguration.py
.py
from uuid import uuid4 from datetime import datetime, timezone from sqlalchemy.orm import relationship from sqlalchemy import Column, ForeignKey, DateTime, Text, UUID from sqlalchemy.types import JSON as GenericJSON from cognee.infrastructure.databases.relational import Base class DatasetConfiguration(Base): __ta...
24
895
cognee
cognee/modules/data/models/metrics_data.py
.py
from datetime import datetime, timezone from uuid import uuid4 from sqlalchemy import Column, DateTime, JSON, UUID from cognee.modules.data.models.metrics_base import MetricsBase class Metrics(MetricsBase): __tablename__ = "eval_metrics" id = Column(UUID, primary_key=True, default=uuid4) payload = Colu...
16
439
cognee
cognee/modules/data/models/questions_data.py
.py
from datetime import datetime, timezone from uuid import uuid4 from sqlalchemy import Column, DateTime, JSON, UUID from cognee.modules.data.models.questions_base import QuestionsBase class Questions(QuestionsBase): __tablename__ = "eval_questions" id = Column(UUID, primary_key=True, default=uuid4) payl...
16
449
cognee
cognee/modules/data/models/Data.py
.py
from datetime import datetime, timezone from uuid import uuid4 from sqlalchemy import UUID, Column, DateTime, Index, String, JSON, Integer, Float from sqlalchemy.ext.mutable import MutableDict from cognee.infrastructure.databases.relational import Base class Data(Base): __tablename__ = "data" # Dedup is a lo...
76
3,716
cognee
cognee/modules/data/models/metrics_base.py
.py
from sqlalchemy.orm import DeclarativeBase class MetricsBase(DeclarativeBase): pass
6
90
cognee
cognee/modules/data/models/questions_base.py
.py
from sqlalchemy.orm import DeclarativeBase class QuestionsBase(DeclarativeBase): pass
6
92
cognee
cognee/modules/data/models/answers_base.py
.py
from sqlalchemy.orm import DeclarativeBase class AnswersBase(DeclarativeBase): pass
6
90
cognee
cognee/modules/data/deletion/prune_data.py
.py
from cognee.infrastructure.files.storage import get_file_storage, get_storage_config from cognee.infrastructure.databases.cache.get_cache_engine import close_cache_engine async def prune_data(): storage_config = get_storage_config() data_root_directory = storage_config["data_root_directory"] await close_c...
10
395
cognee
cognee/modules/data/deletion/prune_system.py
.py
from sqlalchemy.exc import OperationalError, ProgrammingError from cognee.infrastructure.databases.exceptions import EntityNotFoundError from cognee.context_global_variables import backend_access_control_enabled from cognee.infrastructure.databases.vector import get_vector_engine_async from cognee.infrastructure.datab...
93
3,759
cognee
cognee/modules/sync/methods/get_sync_operation.py
.py
from uuid import UUID from typing import List, Optional from sqlalchemy import select, desc, and_ from cognee.modules.sync.models import SyncOperation, SyncStatus from cognee.infrastructure.databases.relational import get_relational_engine async def get_sync_operation(run_id: str) -> Optional[SyncOperation]: """ ...
108
3,339
cognee
cognee/modules/sync/methods/update_sync_operation.py
.py
import asyncio from typing import Optional, List from datetime import datetime, timezone from sqlalchemy import select from sqlalchemy.exc import SQLAlchemyError, DisconnectionError, OperationalError, TimeoutError from cognee.modules.sync.models import SyncOperation, SyncStatus from cognee.infrastructure.databases.rela...
249
10,065
cognee
cognee/modules/sync/methods/__init__.py
.py
from .create_sync_operation import create_sync_operation from .get_sync_operation import ( get_sync_operation, get_user_sync_operations, get_running_sync_operations_for_user, ) from .update_sync_operation import ( update_sync_operation, mark_sync_started, mark_sync_completed, mark_sync_faile...
24
576
cognee
cognee/modules/sync/methods/create_sync_operation.py
.py
from uuid import UUID from typing import Optional, List from datetime import datetime, timezone from cognee.modules.sync.models import SyncOperation, SyncStatus from cognee.infrastructure.databases.relational import get_relational_engine async def create_sync_operation( run_id: str, dataset_ids: List[UUID], ...
54
1,908
cognee
cognee/modules/sync/models/SyncOperation.py
.py
from uuid import uuid4 from enum import Enum from typing import Optional, List from datetime import datetime, timezone from sqlalchemy import ( Column, Text, DateTime, UUID as SQLAlchemy_UUID, Integer, Enum as SQLEnum, JSON, ) from cognee.infrastructure.databases.relational import Base cl...
143
5,681
cognee
cognee/modules/sync/models/__init__.py
.py
from .SyncOperation import SyncOperation, SyncStatus __all__ = ["SyncOperation", "SyncStatus"]
4
96
cognee
cognee/modules/integrations/oauth_flow.py
.py
"""Provider-agnostic OAuth2 ``state`` signing and validation. Every OAuth2 install flow needs a CSRF token that also binds the incoming callback to whichever cognee user started it — the callback itself is necessarily unauthenticated (the browser arrives from the provider's site without a session header), so a valid, ...
103
3,997
cognee
cognee/modules/integrations/connect.py
.py
"""Generic OAuth installation completion, shared by every provider. Exchange code -> parse response -> persist credential is the same three-step dance regardless of provider; the only per-provider pieces are ``exchange_code`` and ``parse_installation`` on the :class:`~cognee.modules.integrations.base.OAuthIntegration`...
45
1,966
cognee
cognee/modules/integrations/registry.py
.py
"""Registry of installed third-party OAuth integrations. Mirrors the ``supported_databases``/``use_vector_adapter`` seam already used by the graph and vector adapters: a plain module-level dict, populated by ``use_integration()`` at provider-package import time, never by this module importing providers itself. A provi...
32
1,345
cognee
cognee/modules/integrations/credentials.py
.py
"""Generic persistence for third-party connector credentials. Provider-agnostic CRUD over the single ``integration_credentials`` table. Connector-specific code (e.g. the Slack layer) maps its OAuth response into the ``token_payload`` + metadata these functions accept, then routes inbound webhooks back via :func:`get_c...
254
10,282
cognee
cognee/modules/integrations/base.py
.py
"""Base contracts for third-party OAuth integrations. Every provider (Slack today; Notion, GitHub, Google Drive later) needs the same connect story — mint an authorize URL, exchange a code for tokens, and turn the resulting token response into exactly what the generic credential store (:mod:`cognee.modules.integration...
153
6,510
cognee
cognee/modules/integrations/crypto.py
.py
"""Encryption seam for stored third-party integration credentials. Version 1 encrypts with AES-256-GCM under a **keyring**: a set of 32-byte keys (base64) each addressed by a short ``key_id``. New rows are written under the active key id; every row stores the id it was written with, so decryption always uses the right...
117
4,697
cognee
cognee/modules/integrations/slack/handle_cognee_remember.py
.py
"""Handle ``/cognee-remember`` slash command — save free text to memory. There are two ways to remember, and they answer different needs. The "Remember this" message shortcut covers what Slack already has on screen: the thing worth keeping was written by someone else, and retyping it is exactly the friction that stops...
145
5,515
cognee
cognee/modules/integrations/slack/persistence.py
.py
"""Slack adapter over the generic credential store. Exposes team-id-keyed lookups the webhook handlers route through. Persisting a completed OAuth exchange now goes through the generic :func:`cognee.modules.integrations.connect.complete_installation` + :class:`~cognee.modules.integrations.slack.adapter.SlackIntegratio...
71
2,740
cognee
cognee/modules/integrations/slack/remember_message.py
.py
"""Remember a Slack message shortcut's content in Cognee. Wraps :func:`cognee.remember` with a Slack-specific dataset and provenance-carrying text — bare message text alone loses who said it and where, both useful context for the resulting knowledge graph. """ from typing import Optional from uuid import UUID from c...
88
3,177
cognee
cognee/modules/integrations/slack/handle_cognee_ask.py
.py
"""Handle ``/cognee-ask`` slash command — recall from knowledge graph. Nothing about a ``/cognee-ask`` becomes visible to the channel until the asker has seen the answer and explicitly chosen to share it — neither the question nor the answer are known to be channel-appropriate before that. So every step here, includin...
339
13,668
cognee
cognee/modules/integrations/slack/handle_slack_link.py
.py
"""Handle ``/cognee-link`` — link the invoking Slack member's own cognee account via a magic link, not a pasted API key. One Slack OAuth install serves an entire workspace, but ``/cognee-ask`` and "Remember this" need to know *which* cognee account each individual member should read from/write to. Typical SDK/local us...
127
5,194
cognee
cognee/modules/integrations/slack/home.py
.py
"""Publish the Cognee App Home tab. Slack shows a blank Home tab until the app calls ``views.publish`` — this is what makes clicking Cognee in the sidebar show anything at all. The view is static/informational (same content for every viewer) — it exists to answer the "what do I even do with this app, and what does it ...
105
4,263
cognee
cognee/modules/integrations/slack/handle_slack_interactive.py
.py
"""Interactive payload dispatch — message shortcuts, block actions, etc. Slack POSTs ``application/x-www-form-urlencoded`` for interactive payloads, with a single ``payload`` field holding a URL-encoded JSON string — unlike the Events API, which POSTs raw JSON directly. Parsed here from the verified raw bytes, same re...
145
5,778
cognee
cognee/modules/integrations/slack/__init__.py
.py
"""Slack integration package. Importing this package registers the Slack adapter with the integrations registry as a side effect — mirrors :mod:`cognee.modules.tools.builtin`, which registers built-in tools the same way at import time. """ from cognee.modules.integrations.registry import use_integration from cognee.m...
13
417
cognee
cognee/modules/integrations/slack/channels.py
.py
"""List a connected Slack workspace's public channels. Backs the per-channel allowlist on the Integrations page: a workspace owner picks which channels ``/cognee-ask`` (and future slash commands) may be used in, rather than the whole workspace by default. Requires the ``channels:read`` bot scope — basic metadata only ...
102
3,580
cognee
cognee/modules/integrations/slack/slack_settings.py
.py
from pydantic_settings import SettingsConfigDict from cognee.modules.integrations.base import IntegrationSettings class SlackSettings(IntegrationSettings): """Configuration for the Slack integration. One Slack app is installed into many workspaces; these values identify that single app. Secrets default ...
43
1,628
cognee
cognee/modules/integrations/slack/response_url.py
.py
"""POST a followup message to a Slack ``response_url``. Shared by every Slack handler that acks fast and delivers its real answer later — the async ``/cognee-ask`` search and the "Remember this" message shortcut both use this. A ``response_url`` is valid for 30 minutes and accepts up to 5 posts; ``replace_original: tr...
39
1,566
cognee
cognee/modules/integrations/slack/oauth.py
.py
"""Slack OAuth v2 install flow: authorize URL, signed state, code exchange. https://docs.slack.dev/authentication/installing-with-oauth The ``state`` parameter is the CSRF defense AND the connecting-user binding: it is minted only for the authenticated cognee user who initiated the install, carries ``user_id:expiry``...
96
3,916
cognee
cognee/modules/integrations/slack/adapter.py
.py
"""Slack as an ``OAuthIntegration`` adapter. Wraps the already-tested free functions in :mod:`cognee.modules.integrations .slack.oauth` behind the generic contract so :mod:`cognee.api.v1.integrations.routers.get_integrations_router` can dispatch to Slack the same way it will dispatch to any future provider. Nothing he...
172
7,696
cognee
cognee/modules/integrations/slack/handle_slack_event.py
.py
"""Events API dispatch for the Slack app. Handles: * ``app_uninstalled`` / ``tokens_revoked`` — lifecycle hygiene, revokes the stored installation so no dangling bot token survives an uninstall. * ``app_home_opened`` — publishes the (static, informational) Home tab content. Slack shows a blank Home tab until the ...
94
3,656
cognee
cognee/modules/integrations/slack/handle_slack_command.py
.py
"""Slash command handling for the Slack app. ``/cognee-ask``, ``/cognee-remember`` and ``/cognee-link`` (per-member account linking — see handle_slack_link.py) are implemented today, matching the commands the cloud integration exposes. ``/cognee-forget`` is not: cognee can delete a dataset, one data item, or everythin...
66
2,959
cognee
cognee/modules/integrations/slack/verify_slack_signature.py
.py
"""Slack request signature verification. Every inbound Slack payload — slash commands, Events API, interactivity — is authenticated by an HMAC over ``v0:{timestamp}:{raw_body}`` keyed with the app's signing secret, compared against the ``X-Slack-Signature`` header (https://docs.slack.dev/authentication/verifying-reque...
66
2,500
cognee
cognee/modules/integrations/models/__init__.py
.py
from .IntegrationCredential import IntegrationCredential __all__ = ["IntegrationCredential"]
4
94
cognee
cognee/modules/integrations/models/IntegrationCredential.py
.py
from datetime import datetime, timezone from typing import Optional from uuid import UUID, uuid4 from cognee.infrastructure.databases.relational.ModelBase import Base from sqlalchemy import JSON, DateTime, Index, LargeBinary, SmallInteger, String from sqlalchemy import UUID as SAUUID from sqlalchemy.orm import Mapped,...
101
4,597
cognee
cognee/modules/agents/operations.py
.py
from __future__ import annotations from datetime import datetime, timedelta, timezone from typing import Any, Literal, Optional from uuid import UUID as UUIDType from sqlalchemy import select from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.agents.models import ( A...
300
10,020
cognee
cognee/modules/agents/models.py
.py
from __future__ import annotations from datetime import datetime from typing import Any, Literal, Optional from uuid import UUID from pydantic import BaseModel, Field AgentConnectionType = Literal["sdk", "api", "mcp", "claude_code", "opencode", "workflow", "unknown"] AgentMemoryMode = Literal["session", "cognee", "...
88
3,066
cognee
cognee/modules/agents/delete_agent.py
.py
from uuid import UUID from cognee.modules.agents.registry import delete_user_agent_connections from cognee.modules.users.methods.delete_user import delete_user from cognee.modules.users.methods.get_user import get_user async def delete_agent(agent_id: UUID, owner_id: UUID) -> None: agent_user = await get_user(ag...
19
608
cognee
cognee/modules/agents/__init__.py
.py
from cognee.modules.agents.models import ( AgentConnection, AgentDatasetRef, AgentDetailResponse, AgentsListResponse, MemorySourceConnection, RegisterAgentRequest, ) from cognee.modules.agents.operations import ( get_agent_connection_detail, list_agent_connections, register_agent_fro...
36
926
cognee
cognee/modules/agents/create_agent.py
.py
from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.api_key.create_api_key import create_api_key from cognee.modules.users.methods import create_user from cognee.modules.users.models.User import User from sqlalchemy import update async def create_agent(name: str, par...
29
1,096
cognee
cognee/modules/agents/registry.py
.py
from __future__ import annotations import hashlib import re from datetime import datetime, timezone from threading import RLock from typing import Iterable, Optional from uuid import UUID from cognee.modules.agents.models import ( AgentConnection, AgentConnectionType, AgentDatasetRef, AgentMemoryMode,...
274
9,266
cognee
cognee/modules/agents/agent_mode.py
.py
"""Agent mode: automatic server shutdown when no agents are active. When COGNEE_AGENT_MODE=true, the server tracks how many agent connections have registered via the /register endpoint. A background watchdog thread starts on the first registration and checks every 60 seconds whether any connections remain. If the coun...
126
3,666
cognee
cognee/modules/agents/get_agent.py
.py
from uuid import UUID from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.agents.list_agents import AgentInfo from cognee.modules.users.methods.get_user import get_user from cognee.modules.users.models.UserApiKey import UserApiKey from sqlalchemy import select async def g...
27
945
cognee
cognee/modules/agents/list_agents.py
.py
from dataclasses import dataclass from typing import Optional from uuid import UUID from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.models.User import User from cognee.modules.users.models.UserApiKey import UserApiKey from sqlalchemy import select @dataclass cla...
35
1,112
cognee
cognee/modules/retrieval/completion_retriever.py
.py
from typing import Any, Dict, List, Optional, Type from cognee.shared.logging_utils import get_logger from cognee.infrastructure.databases.vector import get_vector_engine_async from cognee.modules.retrieval.utils.completion import generate_completion from cognee.modules.retrieval.utils.merge_results import conversatio...
188
8,055
cognee
cognee/modules/retrieval/jaccard_retrival.py
.py
from cognee.modules.retrieval.lexical_retriever import LexicalRetriever, tokenize_words from collections import Counter from typing import Optional class JaccardChunksRetriever(LexicalRetriever): """ Retriever that specializes LexicalRetriever to use Jaccard similarity. """ def __init__( self...
57
2,172
cognee
cognee/modules/retrieval/hybrid_retriever.py
.py
import asyncio from typing import Any, Dict, List, Optional, Type from cognee.context_global_variables import current_dataset_id, session_user from cognee.infrastructure.databases.cache.config import CacheConfig from cognee.infrastructure.databases.unified import get_unified_engine from cognee.infrastructure.session.g...
316
13,311
cognee
cognee/modules/retrieval/base_retriever.py
.py
from abc import ABC, abstractmethod from typing import Any, Dict, List, Optional, Union class BaseRetriever(ABC): """ Base class for all retrieval operations. The retrieval workflow follows a three-step pipeline: 1. get_retrieved_objects: Fetch raw data (e.g., Graph Edges, Vector chunks). 2. get_...
141
5,809
cognee
cognee/modules/retrieval/lexical_retriever.py
.py
import asyncio import re from typing import Any, Callable, Optional, List, Union from heapq import nlargest from cognee.infrastructure.databases.graph import get_graph_engine from cognee.modules.retrieval.base_retriever import BaseRetriever from cognee.modules.retrieval.exceptions.exceptions import NoDataError from co...
180
6,970
cognee
cognee/modules/retrieval/register_retriever.py
.py
from typing import Type from .base_retriever import BaseRetriever from .registered_community_retrievers import registered_community_retrievers from ..search.types import SearchType def use_retriever(search_type: SearchType, retriever: Type[BaseRetriever]): """Register a retriever class for a given search type.""...
11
383
cognee
cognee/modules/retrieval/graph_completion_retriever.py
.py
import asyncio from typing import Any, Dict, List, Optional, Type, Union from cognee.base_config import get_base_config from cognee.infrastructure.engine import DataPoint from cognee.modules.graph.cognee_graph.CogneeGraphElements import Edge from cognee.modules.retrieval.utils.validate_queries import validate_retrieve...
442
18,531
cognee
cognee/modules/retrieval/coding_rules_retriever.py
.py
import asyncio from functools import reduce from typing import List, Optional, Any from cognee.shared.logging_utils import get_logger from cognee.modules.retrieval.base_retriever import BaseRetriever from cognee.tasks.codingagents.coding_rule_associations import get_existing_rules logger = get_logger("CodingRulesRetri...
39
1,531
cognee
cognee/modules/retrieval/graph_completion_cot_retriever.py
.py
import asyncio import json from typing import Optional, List, Type, Any, Union from pydantic import BaseModel from cognee.base_config import get_base_config from cognee.modules.graph.cognee_graph.CogneeGraphElements import Edge from cognee.modules.retrieval.utils.query_state import QueryState from cognee.modules.retr...
332
14,202
cognee
cognee/modules/retrieval/chunks_retriever.py
.py
from typing import Any, Optional, List, Union from cognee.shared.logging_utils import get_logger from cognee.infrastructure.databases.unified import get_unified_engine from cognee.modules.retrieval.base_retriever import BaseRetriever from cognee.modules.retrieval.exceptions.exceptions import NoDataError from cognee.inf...
131
4,930
cognee
cognee/modules/retrieval/bm25_retriever.py
.py
import math from collections import Counter from typing import Optional from cognee.modules.retrieval.lexical_retriever import LexicalRetriever, tokenize_words from cognee.modules.retrieval.utils.stop_words import DEFAULT_STOP_WORDS class BM25ChunksRetriever(LexicalRetriever): """ Retriever that specializes ...
105
3,910
cognee
cognee/modules/retrieval/cypher_search_retriever.py
.py
from typing import Any, Optional from fastapi.encoders import jsonable_encoder from cognee.infrastructure.databases.graph import get_graph_engine from cognee.modules.retrieval.base_retriever import BaseRetriever from cognee.modules.retrieval.utils.completion import generate_completion from cognee.modules.retrieval.exc...
104
3,725
cognee
cognee/modules/retrieval/graph_completion_context_extension_retriever.py
.py
import asyncio from typing import Optional, List, Type, Union from cognee.base_config import get_base_config from cognee.modules.graph.cognee_graph.CogneeGraphElements import Edge from cognee.modules.retrieval.utils.query_state import QueryState from cognee.modules.retrieval.utils.validate_queries import validate_retr...
142
5,979
cognee
cognee/modules/retrieval/graph_summary_completion_retriever.py
.py
from typing import Optional, Type, List from cognee.base_config import get_base_config from cognee.modules.retrieval.graph_completion_retriever import GraphCompletionRetriever from cognee.modules.retrieval.utils.completion import summarize_text class GraphSummaryCompletionRetriever(GraphCompletionRetriever): """...
74
3,048
cognee
cognee/modules/retrieval/summaries_retriever.py
.py
from typing import Any, Optional, List, Union from cognee.shared.logging_utils import get_logger from cognee.infrastructure.databases.unified import get_unified_engine from cognee.modules.retrieval.base_retriever import BaseRetriever from cognee.modules.retrieval.exceptions.exceptions import NoDataError from cognee.in...
117
4,127
cognee
cognee/modules/retrieval/agentic_retriever.py
.py
"""Retriever that unifies memory retrieval, skills, and tool calls. Extends GraphCompletionRetriever so memory triplet retrieval and context formatting are reused. Adds a ReAct-style loop: at each turn the LLM emits a structured AgentStep (either a tool_call or a final_answer). Tool calls flow through execute_tool, wh...
566
22,734
cognee
cognee/modules/retrieval/natural_language_retriever.py
.py
from typing import Any, Optional from cognee.shared.logging_utils import get_logger from cognee.infrastructure.databases.graph import get_graph_engine from cognee.infrastructure.llm.LLMGateway import LLMGateway from cognee.infrastructure.llm.prompts import render_prompt from cognee.modules.retrieval.base_retriever impo...
178
7,125
cognee
cognee/modules/retrieval/graph_report_retriever.py
.py
from __future__ import annotations from typing import Any, Dict, List, Optional, Set, Tuple import networkx as nx from pydantic import BaseModel from cognee.infrastructure.databases.graph import get_graph_engine from cognee.infrastructure.llm.LLMGateway import LLMGateway from cognee.modules.retrieval.base_retriever ...
315
12,889
cognee
cognee/modules/retrieval/code_retriever.py
.py
"""Deterministic queries over an Enola-derived Cognee code graph. The retriever intentionally uses only the graph adapter. It does not invoke an LLM, an embedding engine, or vector search. ``query`` is the human-readable seed while ``config`` selects one exact graph operation and its arguments. For backend portabil...
1,355
51,934
cognee
cognee/modules/retrieval/temporal_retriever.py
.py
import os import asyncio from typing import Any, Dict, List, Optional, Type from datetime import datetime from operator import itemgetter from cognee.base_config import get_base_config from cognee.infrastructure.databases.unified import get_unified_engine from cognee.infrastructure.llm.prompts import render_prompt fro...
177
7,303
cognee
cognee/modules/retrieval/session_aware_completion.py
.py
"""Session-aware completion for ``get_retriever_output``. Public door: ``run_session_aware_completion`` → concurrent or sequential runner. Both return ``(retrieved_objects, context, completion)``. Retriever ``get_completion`` stays as on ``dev`` and does not call this module. Session I/O for the concurrent path lives...
438
15,636
cognee
cognee/modules/retrieval/graph_completion_decomposition_retriever.py
.py
import asyncio from typing import Any, List, Optional, Type from cognee.base_config import get_base_config from cognee.infrastructure.databases.unified import get_unified_engine from cognee.infrastructure.llm.LLMGateway import LLMGateway from cognee.infrastructure.llm.prompts import read_query_prompt from cognee.modul...
261
10,126
cognee
cognee/modules/retrieval/triplet_retriever.py
.py
from typing import Any, Dict, List, Optional, Type, Union from cognee.shared.logging_utils import get_logger from cognee.infrastructure.databases.vector import get_vector_engine_async from cognee.modules.retrieval.utils.completion import generate_completion from cognee.modules.retrieval.utils.merge_results import conv...
195
8,031
cognee
cognee/modules/retrieval/hybrid/entities.py
.py
from typing import Any, Optional from cognee.modules.retrieval.hybrid.facts import connection_edge_type_id from cognee.modules.retrieval.hybrid.results import ( display_value, first_display_value, payload, result_id, ) from cognee.shared.logging_utils import get_logger logger = get_logger("HybridRetri...
233
7,651
cognee
cognee/modules/retrieval/hybrid/facts.py
.py
from typing import Any, Optional from cognee.modules.graph.models.EdgeType import EdgeType from cognee.modules.graph.utils.prepare_edges_for_storage import get_edge_retrieval_text from cognee.modules.retrieval.hybrid.results import first_display_value, payload, result_id MIN_FACT_WORD_COUNT = 3 # Prefix emitted in t...
70
2,541
cognee
cognee/modules/retrieval/hybrid/context.py
.py
from typing import Any, Optional from cognee.modules.retrieval.hybrid.entities import format_entities from cognee.modules.retrieval.hybrid.facts import format_facts from cognee.modules.retrieval.hybrid.results import display_value, payload, result_id def format_hybrid_context(global_context: str, retrieved_objects: ...
78
2,587
cognee
cognee/modules/retrieval/hybrid/chunks.py
.py
import asyncio from typing import Any, Optional from cognee.infrastructure.databases.vector.exceptions import CollectionNotFoundError from cognee.modules.retrieval.bm25_retriever import BM25ChunksRetriever from cognee.modules.retrieval.exceptions.exceptions import NoDataError from cognee.modules.retrieval.hybrid.pairs...
281
8,846
cognee
cognee/modules/retrieval/hybrid/merge.py
.py
"""Merge two hybrid retrievals into one result of the same shape. Each channel merges under its own budget, and ``chunk_summaries`` is rebuilt for the chunks that survived so it never references a dropped chunk. Keys the retriever carries but this module does not own are taken from the primary result unchanged. """ f...
63
2,249
cognee
cognee/modules/retrieval/hybrid/pairs.py
.py
from typing import Any, Optional from uuid import UUID, uuid5 from cognee.modules.retrieval.hybrid.results import ( display_value, payload, payload_matches_node_filter, result_id, ) from cognee.shared.logging_utils import get_logger logger = get_logger("HybridRetriever") def chunk_summary_pairs( ...
132
4,258
cognee
cognee/modules/retrieval/hybrid/ranking.py
.py
from typing import Optional from cognee.modules.retrieval.hybrid.results import payload, result_id from cognee.modules.truth_subspace.align import truth_factor def rank_chunk_summary_pairs( pairs: list[dict], limit: int, use_importance_weight: bool, use_truth_weight: bool = False, q_coords: Optio...
60
1,968
cognee
cognee/modules/retrieval/hybrid/results.py
.py
from typing import Any, Optional from uuid import UUID def payload(result: Any) -> dict: if isinstance(result, dict): return result result_payload = getattr(result, "payload", None) return result_payload if isinstance(result_payload, dict) else {} def display_value(value: Any) -> Optional[str]: ...
60
1,709
cognee
cognee/modules/retrieval/exceptions/exceptions.py
.py
from fastapi import status from cognee.exceptions import CogneeValidationError, CogneeSystemError class SearchTypeNotSupported(CogneeValidationError): def __init__( self, message: str = "CYPHER search type not supported by the adapter.", name: str = "SearchTypeNotSupported", status...
53
1,715
cognee
cognee/modules/retrieval/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 SearchTypeNotSupported, CypherSearchError
8
187