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/chunking/JsonListChunker.py
.py
import json from os.path import basename from uuid import NAMESPACE_OID, uuid5 from cognee.modules.chunking.Chunker import Chunker from cognee.modules.chunking.models.DocumentChunk import DocumentChunk from cognee.shared.logging_utils import get_logger logger = get_logger() class JsonListChunker(Chunker): """Ch...
67
2,414
cognee
cognee/modules/chunking/TextChunker.py
.py
from cognee.shared.logging_utils import get_logger from os.path import basename from uuid import NAMESPACE_OID, uuid5 from cognee.tasks.chunks import chunk_by_paragraph from cognee.modules.chunking.Chunker import Chunker from .models.DocumentChunk import DocumentChunk logger = get_logger() class TextChunker(Chunker...
91
4,141
cognee
cognee/modules/chunking/CsvChunker.py
.py
from cognee.shared.logging_utils import get_logger from os.path import basename from cognee.tasks.chunks import chunk_by_row from cognee.modules.chunking.Chunker import Chunker from .models.DocumentChunk import DocumentChunk logger = get_logger() class CsvChunker(Chunker): async def read(self): documen...
41
1,560
cognee
cognee/modules/chunking/text_chunker_with_overlap.py
.py
from cognee.shared.logging_utils import get_logger from os.path import basename from uuid import NAMESPACE_OID, uuid5 from cognee.tasks.chunks import chunk_by_paragraph from cognee.modules.chunking.Chunker import Chunker from .models.DocumentChunk import DocumentChunk logger = get_logger() class TextChunkerWithOver...
129
4,877
cognee
cognee/modules/chunking/models/DocumentChunk.py
.py
from typing import List, Union, Optional from cognee.infrastructure.engine import DataPoint from cognee.infrastructure.engine.models.Edge import Edge from cognee.modules.data.processing.document_types import Document from cognee.modules.engine.models import Entity from cognee.tasks.temporal_graph.models import Event ...
46
1,744
cognee
cognee/modules/chunking/models/DltRow.py
.py
from cognee.modules.chunking.models.DocumentChunk import DocumentChunk class DltRow(DocumentChunk): """One row of a DLT source manifest — its own graph type AND its own vector collection (DltRow_text). Chunk search (DocumentChunk_text) is for document ingestion only, so rows deliberately do NOT appea...
16
717
cognee
cognee/modules/recall/methods/model_from_json_schema.py
.py
"""Rebuild a Pydantic model class from a client-supplied JSON Schema. The recall HTTP API accepts structured-output requests as a JSON Schema (``response_schema``, typically produced client-side via ``MyModel.model_json_schema()``) because a Python class cannot cross the HTTP boundary. This module turns that schema ba...
170
6,392
cognee
cognee/modules/recall/methods/normalize_search_payload.py
.py
"""Adapter from retriever payloads to the normalized SearchResponse. Retrievers produce heterogeneous payloads (strings, chunk dicts, graph rows, edge lists). This module flattens them into a uniform list of ``SearchResultItem`` so every call to ``cognee.search`` returns the same wire shape regardless of search type. ...
164
6,062
cognee
cognee/modules/recall/types/RecallResponse.py
.py
from typing import Annotated, Literal, Optional from pydantic import BaseModel, Field from cognee.infrastructure.databases.cache import SessionAgentTraceEntry, SessionQAEntry from cognee.modules.recall.types.SearchResultItem import SearchResultItem class ResponseQAEntry(SessionQAEntry): source: Literal["session...
53
1,353
cognee
cognee/modules/recall/types/SearchResultItem.py
.py
"""Normalized search result envelope. ``cognee.search`` routes to retrievers that produce wildly different payloads: plain completion strings from graph/LLM retrievers, chunk payload dicts from CHUNKS, summary dicts from SUMMARIES, raw graph rows from CYPHER, etc. This module defines the single wire shape that all sea...
72
2,356
cognee
cognee/modules/users/get_user_db.py
.py
from typing import AsyncGenerator from fastapi import Depends from contextlib import asynccontextmanager from sqlalchemy.ext.asyncio import AsyncSession from fastapi_users.db import SQLAlchemyUserDatabase from cognee.infrastructure.databases.relational import get_relational_engine from .models.User import User async ...
21
684
cognee
cognee/modules/users/get_fastapi_users.py
.py
import uuid from functools import lru_cache from fastapi_users import FastAPIUsers from .authentication.get_api_auth_backend import get_api_auth_backend from .authentication.get_client_auth_backend import get_client_auth_backend from .authentication.get_api_key_backend import get_api_key_backend from .get_user_manage...
24
723
cognee
cognee/modules/users/get_user_manager.py
.py
import os import re import json import uuid import logging from sqlalchemy import select from typing import Optional from fastapi import Depends, HTTPException, Request, Response from fastapi.security import OAuth2PasswordRequestForm from fastapi_users import BaseUserManager, UUIDIDMixin, exceptions from fastapi_users....
102
4,155
cognee
cognee/modules/users/roles/methods/remove_user_from_role.py
.py
from uuid import UUID from sqlalchemy.future import select from sqlalchemy import delete from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.exceptions import ( UserNotFoundError, RoleNotFoundError, ) from cognee.modules.users.permissions.methods import has_u...
52
1,635
cognee
cognee/modules/users/roles/methods/create_role.py
.py
from uuid import UUID from sqlalchemy.exc import IntegrityError from cognee.infrastructure.databases.exceptions import EntityAlreadyExistsError from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.methods import get_user from cognee.modules.users.permissions.methods i...
53
1,761
cognee
cognee/modules/users/roles/methods/delete_role.py
.py
from uuid import UUID from sqlalchemy.future import select from sqlalchemy import delete from cognee.infrastructure.databases.relational import get_relational_engine from cognee.infrastructure.databases.exceptions import EntityNotFoundError from cognee.modules.users.permissions.methods import has_user_management_perm...
50
1,865
cognee
cognee/modules/users/roles/methods/add_user_to_role.py
.py
from uuid import UUID from sqlalchemy.future import select from sqlalchemy import insert from sqlalchemy.exc import IntegrityError from cognee.infrastructure.databases.exceptions import EntityAlreadyExistsError from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.exce...
68
2,264
cognee
cognee/modules/users/exceptions/exceptions.py
.py
from cognee.exceptions import CogneeValidationError from fastapi import status class RoleNotFoundError(CogneeValidationError): """User group not found""" def __init__( self, message: str = "User role not found.", name: str = "RoleNotFoundError", status_code=status.HTTP_404_NOT...
59
1,639
cognee
cognee/modules/users/exceptions/__init__.py
.py
""" Custom exceptions for the Cognee API. This module defines a set of exceptions for handling various user errors """ from .exceptions import ( RoleNotFoundError, UserNotFoundError, PermissionDeniedError, TenantNotFoundError, PermissionNotFoundError, )
14
276
cognee
cognee/modules/users/tenants/methods/get_user_tenants.py
.py
from sqlalchemy import select from cognee.modules.users.models import User from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.models.Tenant import Tenant from cognee.modules.users.models.UserTenant import UserTenant async def get_user_tenants(user: User): db_en...
30
929
cognee
cognee/modules/users/tenants/methods/get_users_in_role.py
.py
from sqlalchemy import select from uuid import UUID from cognee.modules.users.exceptions import RoleNotFoundError from cognee.modules.users.models import Role, User, UserRole from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.permissions.methods.has_user_management_p...
66
2,422
cognee
cognee/modules/users/tenants/methods/get_user_roles.py
.py
from sqlalchemy import select from uuid import UUID from cognee.modules.users.models import User from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.permissions.methods.has_user_management_permission import ( has_user_management_permission, ) async def get_user_...
35
1,099
cognee
cognee/modules/users/tenants/methods/remove_user_from_tenant.py
.py
from uuid import UUID from fastapi import status from sqlalchemy import delete, select from cognee.exceptions import CogneeValidationError from cognee.infrastructure.databases.exceptions import EntityNotFoundError from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.data.mo...
96
3,842
cognee
cognee/modules/users/tenants/methods/add_user_to_tenant.py
.py
from typing import Optional from uuid import UUID from sqlalchemy.exc import IntegrityError from sqlalchemy import insert from cognee.infrastructure.databases.exceptions import EntityAlreadyExistsError from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.models.UserTen...
70
2,528
cognee
cognee/modules/users/tenants/methods/get_users_in_tenant.py
.py
from sqlalchemy import select from sqlalchemy.orm import selectinload from uuid import UUID from cognee.modules.users.models import User, Role, UserTenant from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.permissions.methods.has_user_management_permission import ( ...
40
1,416
cognee
cognee/modules/users/tenants/methods/create_tenant.py
.py
from uuid import UUID from sqlalchemy import insert from sqlalchemy.exc import IntegrityError from typing import Optional from cognee.modules.users.models.UserTenant import UserTenant from cognee.infrastructure.databases.exceptions import EntityAlreadyExistsError from cognee.infrastructure.databases.relational import ...
58
2,189
cognee
cognee/modules/users/tenants/methods/select_tenant.py
.py
from uuid import UUID from typing import Union import sqlalchemy.exc from sqlalchemy import select from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.methods.get_user import get_user from cognee.modules.users.models.UserTenant import UserTenant from cognee.modules.u...
67
2,292
cognee
cognee/modules/users/tenants/methods/get_tenant_roles.py
.py
from sqlalchemy import select from sqlalchemy.orm import selectinload from uuid import UUID from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.exceptions import PermissionDeniedError from cognee.modules.users.models import Role, UserRole from cognee.modules.users.per...
51
1,702
cognee
cognee/modules/users/permissions/permission_types.py
.py
from typing import FrozenSet PERMISSION_TYPES = ["read", "write", "delete", "share"] # Role names that grant permission to manage users in a tenant (list users, assign/remove # roles, add/remove users, etc.). Tenant owner is always allowed regardless of this set. # Add role names here when introducing admin, org_admi...
11
449
cognee
cognee/modules/users/permissions/methods/get_all_user_permission_datasets.py
.py
from cognee.shared.logging_utils import get_logger from ...models.User import User from cognee.modules.data.models.Dataset import Dataset from cognee.modules.users.permissions.methods import get_principal_datasets logger = get_logger() async def get_all_user_permission_datasets(user: User, permission_type: str) -> ...
49
1,732
cognee
cognee/modules/users/permissions/methods/get_role.py
.py
import sqlalchemy.exc from sqlalchemy import select from uuid import UUID from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.exceptions import RoleNotFoundError from ...models.Role import Role async def get_role(tenant_id: UUID, role_name: str): """ Re...
35
1,121
cognee
cognee/modules/users/permissions/methods/give_default_permission_to_role.py
.py
from uuid import UUID from sqlalchemy.future import select from sqlalchemy import insert from sqlalchemy.exc import IntegrityError from cognee.infrastructure.databases.exceptions import EntityAlreadyExistsError from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.excep...
66
2,038
cognee
cognee/modules/users/permissions/methods/get_principal_datasets.py
.py
from sqlalchemy import select from sqlalchemy.orm import joinedload from cognee.infrastructure.databases.relational import get_relational_engine from ...models.Principal import Principal from cognee.modules.data.models.Dataset import Dataset from ...models.ACL import ACL async def get_principal_datasets(principal: ...
36
1,283
cognee
cognee/modules/users/permissions/methods/authorized_give_permission_on_datasets.py
.py
from typing import Union, List from cognee.modules.users.permissions.methods import get_principal from cognee.modules.users.permissions.methods import give_permission_on_dataset from cognee.modules.users.permissions.methods import get_specific_user_permission_datasets from uuid import UUID async def authorized_give_...
36
1,409
cognee
cognee/modules/users/permissions/methods/get_user_role_names_in_tenant.py
.py
from typing import List from uuid import UUID from sqlalchemy import select from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.models import Role, UserRole async def get_user_role_names_in_tenant(user_id: UUID, tenant_id: UUID) -> List[str]: """ Return the...
30
945
cognee
cognee/modules/users/permissions/methods/give_default_permission_to_tenant.py
.py
from uuid import UUID from sqlalchemy.future import select from sqlalchemy import insert from sqlalchemy.exc import IntegrityError from cognee.infrastructure.databases.exceptions import EntityAlreadyExistsError from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.excep...
67
2,145
cognee
cognee/modules/users/permissions/methods/revoke_permission_on_dataset.py
.py
from uuid import UUID from sqlalchemy.future import select from sqlalchemy import delete from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.permissions import PERMISSION_TYPES from cognee.modules.users.exceptions import PermissionNotFoundError from ...models import ...
50
1,543
cognee
cognee/modules/users/permissions/methods/check_permission_on_dataset.py
.py
from cognee.shared.logging_utils import get_logger from cognee.modules.users.methods import get_default_user from uuid import UUID from cognee.modules.users.permissions.methods import get_specific_user_permission_datasets from ...models.User import User logger = get_logger() async def check_permission_on_dataset(u...
28
778
cognee
cognee/modules/users/permissions/methods/give_default_permission_to_user.py
.py
from uuid import UUID from sqlalchemy.future import select from sqlalchemy import insert from sqlalchemy.exc import IntegrityError from cognee.infrastructure.databases.exceptions import EntityAlreadyExistsError from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.excep...
65
2,085
cognee
cognee/modules/users/permissions/methods/authorized_revoke_permission_on_datasets.py
.py
from typing import Union, List from uuid import UUID from cognee.modules.users.permissions.methods import ( get_principal, get_specific_user_permission_datasets, ) from cognee.modules.users.permissions.methods.revoke_permission_on_dataset import ( revoke_permission_on_dataset, ) async def authorized_revo...
35
1,155
cognee
cognee/modules/users/permissions/methods/give_permission_on_dataset.py
.py
from uuid import UUID from sqlalchemy.future import select from sqlalchemy.exc import IntegrityError from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.permissions import PERMIS...
74
2,613
cognee
cognee/modules/users/permissions/methods/has_user_management_permission.py
.py
from uuid import UUID from cognee.modules.users.exceptions import PermissionDeniedError from cognee.modules.users.permissions.methods.get_tenant import get_tenant from cognee.modules.users.permissions.methods.get_user_role_names_in_tenant import ( get_user_role_names_in_tenant, ) from cognee.modules.users.permissi...
46
1,706
cognee
cognee/modules/users/permissions/methods/get_principal.py
.py
from sqlalchemy import select from uuid import UUID from cognee.infrastructure.databases.relational import get_relational_engine from ...models.Principal import Principal async def get_principal(principal_id: UUID): """ Return information about a user based on their id Args: principal_id: Id ...
24
679
cognee
cognee/modules/users/permissions/methods/get_document_ids_for_user.py
.py
from uuid import UUID from sqlalchemy import select from cognee.modules.data.methods import get_dataset_data from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.data.models import Dataset from ...models import ACL, Permission async def get_document_ids_for_user(user_id: ...
54
1,981
cognee
cognee/modules/users/permissions/methods/get_specific_user_permission_datasets.py
.py
from uuid import UUID from typing import Optional from cognee.modules.data.models.Dataset import Dataset from cognee.modules.users.permissions.methods.get_all_user_permission_datasets import ( get_all_user_permission_datasets, ) from cognee.modules.users.exceptions import PermissionDeniedError from cognee.modules.u...
48
1,953
cognee
cognee/modules/users/permissions/methods/get_tenant.py
.py
import sqlalchemy.exc from sqlalchemy import select from uuid import UUID from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.exceptions import TenantNotFoundError from ...models.Tenant import Tenant async def get_tenant(tenant_id: UUID): """ Return info...
31
961
cognee
cognee/modules/users/permissions/methods/authorized_get_principal_datasets.py
.py
from typing import List from uuid import UUID from cognee.modules.data.models import Dataset from cognee.modules.users.exceptions import PermissionDeniedError, RoleNotFoundError from cognee.modules.users.methods import get_user from cognee.modules.users.permissions.methods.get_principal import get_principal from cogne...
80
3,579
cognee
cognee/modules/users/authentication/get_api_auth_backend.py
.py
import os from functools import lru_cache from fastapi_users import models from fastapi_users.authentication import ( JWTStrategy, AuthenticationBackend, ) from .api_bearer import api_bearer_transport, APIJWTStrategy @lru_cache def get_api_auth_backend(): transport = api_bearer_transport def get_jw...
30
761
cognee
cognee/modules/users/authentication/get_api_key_backend.py
.py
from functools import lru_cache from fastapi_users.authentication import AuthenticationBackend, JWTStrategy from cognee.modules.users.authentication.api_key.get_api_key_transport import get_api_key_transport from cognee.modules.users.authentication.api_key.api_key_jwt_strategy import ApiKeyJWTStrategy @lru_cache def...
22
650
cognee
cognee/modules/users/authentication/get_client_auth_backend.py
.py
import os from functools import lru_cache from fastapi_users import models from fastapi_users.authentication import ( JWTStrategy, AuthenticationBackend, ) from .default import default_transport @lru_cache def get_client_auth_backend(): transport = default_transport def get_jwt_strategy() -> JWTStr...
32
813
cognee
cognee/modules/users/authentication/api_bearer/api_jwt_strategy.py
.py
from fastapi_users.authentication import JWTStrategy class APIJWTStrategy(JWTStrategy): pass
6
99
cognee
cognee/modules/users/authentication/api_bearer/api_bearer_transport.py
.py
from fastapi_users.authentication import BearerTransport api_bearer_transport = BearerTransport( tokenUrl="/api/v1/auth/token", ) api_bearer_transport.name = "bearer"
8
173
cognee
cognee/modules/users/authentication/default/default_transport.py
.py
import os from fastapi_users.authentication import CookieTransport # Get cookie domain from environment variable # If not set or empty, use None to allow cookie to work on any domain cookie_domain = os.getenv("AUTH_TOKEN_COOKIE_DOMAIN") if cookie_domain == "": cookie_domain = None # Note: Cookie expiration is aut...
23
829
cognee
cognee/modules/users/authentication/methods/authenticate_user.py
.py
from fastapi.security import OAuth2PasswordRequestForm from fastapi_users.exceptions import UserNotExists from cognee.infrastructure.databases.relational import get_relational_engine from ...get_user_manager import get_user_manager_context from ...get_user_db import get_user_db_context async def authenticate_user(ema...
23
1,012
cognee
cognee/modules/users/authentication/api_key/api_key_jwt_strategy.py
.py
from fastapi_users.authentication import JWTStrategy from cognee.modules.users.get_user_manager import UserManager class ApiKeyJWTStrategy(JWTStrategy): def __init__(self): pass async def read_token(self, token: str, user_manager: UserManager): user = await user_manager.get_by_token(token=to...
14
346
cognee
cognee/modules/users/authentication/api_key/get_api_key_transport.py
.py
from typing import Optional, Dict from fastapi import Response from fastapi.security import APIKeyHeader from fastapi_users.authentication import Transport from fastapi import Request class APIKeyHeaderTransport(Transport): def __init__(self, header_name: str = "X-Api-Key"): self.header_name = header_nam...
44
1,459
cognee
cognee/modules/users/methods/create_default_user.py
.py
from .create_user import create_user from cognee.base_config import get_base_config async def create_default_user(): base_config = get_base_config() default_user_email = base_config.default_user_email or "default_user@example.com" default_user_password = base_config.default_user_password or "default_passw...
20
555
cognee
cognee/modules/users/methods/delete_user.py
.py
from fastapi_users.exceptions import UserNotExists from cognee.infrastructure.databases.relational import get_relational_engine from ..get_user_manager import get_user_manager_context from ..get_user_db import get_user_db_context async def delete_user(email: str): try: relational_engine = get_relational_e...
19
758
cognee
cognee/modules/users/methods/get_principal_configuration.py
.py
from sqlalchemy import select from uuid import UUID from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.models.PrincipalConfiguration import PrincipalConfiguration async def get_principal_configuration(config_id: UUID) -> dict: """ Retrieves a specific Cognee...
52
1,967
cognee
cognee/modules/users/methods/get_authenticated_user.py
.py
import os from typing import Optional from fastapi import Depends, HTTPException from ..models import User from ..get_fastapi_users import get_fastapi_users from .get_default_user import get_default_user from .get_user import get_user from cognee.shared.logging_utils import get_logger logger = get_logger("get_authent...
111
4,475
cognee
cognee/modules/users/methods/get_user.py
.py
from uuid import UUID from sqlalchemy import select from sqlalchemy.orm import selectinload from cognee.infrastructure.databases.relational import get_relational_engine from cognee.infrastructure.databases.exceptions import EntityNotFoundError from ..models import User async def get_user(user_id: UUID): db_engine...
25
765
cognee
cognee/modules/users/methods/get_user_id_by_email.py
.py
from uuid import UUID from sqlalchemy import select from cognee.infrastructure.databases.relational import get_relational_engine from ..models import User async def get_user_id_by_email(user_email: str) -> UUID | None: """Return the user ID for a given email, or None if no such user exists.""" db_engine = ...
17
521
cognee
cognee/modules/users/methods/create_user.py
.py
from typing import Optional from uuid import UUID from fastapi_users.exceptions import UserAlreadyExists from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.get_user_manager import get_user_manager_context from cognee.modules.users.get_user_db import get_user_db_cont...
49
1,740
cognee
cognee/modules/users/methods/store_principal_configuration.py
.py
from uuid import UUID from sqlalchemy import select from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.models.PrincipalConfiguration import PrincipalConfiguration async def store_principal_configuration( principal_id: UUID, name: str, configuration: dict ) -> P...
54
2,155
cognee
cognee/modules/users/methods/get_user_by_email.py
.py
from sqlalchemy import select from sqlalchemy.orm import joinedload from cognee.infrastructure.databases.relational import get_relational_engine from ..models import User async def get_user_by_email(user_email: str): db_engine = get_relational_engine() async with db_engine.get_async_session() as session: ...
22
578
cognee
cognee/modules/users/methods/get_default_user.py
.py
from types import SimpleNamespace from sqlalchemy.orm import selectinload from sqlalchemy.exc import NoResultFound, OperationalError from sqlalchemy.future import select from cognee.modules.users.models import User from cognee.base_config import get_base_config from cognee.modules.users.exceptions.exceptions import Use...
57
2,683
cognee
cognee/modules/users/api_key/exceptions.py
.py
class ApiKeyCreationError(Exception): def __init__(self, message: str): self.message = message message: str = "Failed to create API key." class ApiKeyDeletionError(Exception): def __init__(self, message: str): self.message = message message: str = "Failed to delete API key." class ...
27
619
cognee
cognee/modules/users/api_key/hash_api_key.py
.py
import hashlib import os HASH_API_KEY = os.getenv("HASH_API_KEY", "false").lower() == "true" def _load_hash_iterations() -> int: raw_value = os.getenv("API_KEY_HASH_ITERATIONS", "600000") try: iterations = int(raw_value) except ValueError as exc: raise ValueError( f"API_KEY_HA...
40
1,213
cognee
cognee/modules/users/api_key/create_api_key.py
.py
import secrets from pydantic_settings import BaseSettings, SettingsConfigDict from cognee.modules.users.models import User from cognee.shared.logging_utils import get_logger from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.models.UserApiKey import UserApiKey from ....
58
1,805
cognee
cognee/modules/users/api_key/get_api_keys.py
.py
from sqlalchemy import select from cognee.modules.users.models import User from cognee.shared.logging_utils import get_logger from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.models.UserApiKey import UserApiKey from .exceptions import ApiKeyQueryError logger = ge...
29
932
cognee
cognee/modules/users/api_key/delete_api_key.py
.py
import secrets from uuid import UUID from sqlalchemy import select from cognee.modules.users.models import User from cognee.shared.logging_utils import get_logger from cognee.infrastructure.databases.relational import get_relational_engine from cognee.modules.users.models.UserApiKey import UserApiKey from .exceptions ...
35
1,164
cognee
cognee/modules/users/models/User.py
.py
from typing import Optional from uuid import UUID as uuid_UUID from fastapi_users import schemas from fastapi_users.db import SQLAlchemyBaseUserTableUUID from sqlalchemy import ForeignKey, Column, UUID from sqlalchemy.orm import relationship, Mapped from .Principal import Principal from .UserTenant import UserTenant f...
62
1,890
cognee
cognee/modules/users/models/Principal.py
.py
from uuid import uuid4 from datetime import datetime, timezone from sqlalchemy import Column, String, DateTime, UUID from cognee.infrastructure.databases.relational import Base class Principal(Base): __tablename__ = "principals" id = Column(UUID, primary_key=True, index=True, default=uuid4) created_at =...
21
644
cognee
cognee/modules/users/models/Permission.py
.py
from uuid import uuid4 from datetime import datetime, timezone from sqlalchemy import Column, DateTime, String, UUID from cognee.infrastructure.databases.relational import Base class Permission(Base): __tablename__ = "permissions" id = Column(UUID, primary_key=True, index=True, default=uuid4) created_a...
17
562
cognee
cognee/modules/users/models/Role.py
.py
from sqlalchemy.orm import relationship, Mapped from sqlalchemy import Column, String, ForeignKey, UUID, UniqueConstraint from .Principal import Principal from .UserRole import UserRole class Role(Principal): __tablename__ = "roles" id = Column(UUID, ForeignKey("principals.id", ondelete="CASCADE"), primary_k...
32
998
cognee
cognee/modules/users/models/Tenant.py
.py
from sqlalchemy.orm import relationship, Mapped from sqlalchemy import Column, String, ForeignKey, UUID from .Principal import Principal from .UserTenant import UserTenant from .Role import Role class Tenant(Principal): __tablename__ = "tenants" id = Column(UUID, ForeignKey("principals.id"), primary_key=True...
32
837
cognee
cognee/modules/users/models/RoleDefaultPermissions.py
.py
from datetime import datetime, timezone from sqlalchemy import Column, ForeignKey, DateTime, UUID from cognee.infrastructure.databases.relational import Base class RoleDefaultPermissions(Base): __tablename__ = "role_default_permissions" created_at = Column(DateTime(timezone=True), default=lambda: datetime.no...
23
700
cognee
cognee/modules/users/models/UserDefaultPermissions.py
.py
from datetime import datetime, timezone from sqlalchemy import Column, ForeignKey, DateTime, UUID from cognee.infrastructure.databases.relational import Base class UserDefaultPermissions(Base): __tablename__ = "user_default_permissions" created_at = Column(DateTime(timezone=True), default=lambda: datetime.no...
19
628
cognee
cognee/modules/users/models/DatasetDatabase.py
.py
from datetime import datetime, timezone from sqlalchemy import Column, DateTime, String, UUID, ForeignKey, JSON, text from cognee.infrastructure.databases.relational import Base class DatasetDatabase(Base): __tablename__ = "dataset_database" owner_id = Column(UUID, ForeignKey("principals.id", ondelete="CASC...
52
2,470
cognee
cognee/modules/users/models/UserRole.py
.py
from datetime import datetime, timezone from sqlalchemy import Column, ForeignKey, DateTime, UUID from cognee.infrastructure.databases.relational import Base class UserRole(Base): __tablename__ = "user_roles" created_at = Column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)) user_i...
13
448
cognee
cognee/modules/users/models/ACL.py
.py
from uuid import uuid4 from datetime import datetime, timezone from sqlalchemy.orm import relationship from sqlalchemy import Column, ForeignKey, DateTime, UUID from cognee.infrastructure.databases.relational import Base class ACL(Base): __tablename__ = "acls" id = Column(UUID, primary_key=True, default=uuid...
23
861
cognee
cognee/modules/users/models/PrincipalConfiguration.py
.py
from sqlalchemy import ForeignKey from datetime import datetime, timezone from sqlalchemy import UUID, Column, DateTime, String, JSON from sqlalchemy.ext.mutable import MutableDict from uuid import uuid4 from cognee.infrastructure.databases.relational import Base class PrincipalConfiguration(Base): __tablename__...
35
1,317
cognee
cognee/modules/users/models/TenantDefaultPermissions.py
.py
from datetime import datetime, timezone from sqlalchemy import Column, ForeignKey, DateTime, UUID from cognee.infrastructure.databases.relational import Base class TenantDefaultPermissions(Base): __tablename__ = "tenant_default_permissions" created_at = Column(DateTime(timezone=True), default=lambda: datetim...
20
637
cognee
cognee/modules/users/models/UserApiKey.py
.py
from uuid import uuid4 from typing import Optional from sqlalchemy import UUID, ForeignKey from sqlalchemy.orm import Mapped, mapped_column from cognee.infrastructure.databases.relational.ModelBase import Base class UserApiKey(Base): __tablename__ = "user_api_key" id: Mapped[UUID] = mapped_column(UUID, prima...
18
671
cognee
cognee/modules/users/models/UserTenant.py
.py
from datetime import datetime, timezone from sqlalchemy import Column, ForeignKey, DateTime, UUID from cognee.infrastructure.databases.relational import Base class UserTenant(Base): __tablename__ = "user_tenants" created_at = Column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)) us...
13
456
cognee
cognee/modules/truth_subspace/models.py
.py
from pydantic import BaseModel from pydantic import Field class TruthCentroidPayload(BaseModel): dataset_id: str slot: int count: int truth_epoch: int updated_at: int centroid: list[float] learning_ids: list[str] = Field(default_factory=list)
13
273
cognee
cognee/modules/truth_subspace/constants.py
.py
TRUTH_CENTROID_COLLECTION = "TruthCentroid_vector" TRUTH_NODE_SET = ["session_learnings"] DEFAULT_K = 8 def truth_session_node_set(session_id: str) -> str: return f"session_learnings:{session_id}"
8
203
cognee
cognee/modules/truth_subspace/align.py
.py
"""Pure truth-subspace alignment functions. No I/O, no database access, no LLM calls — just deterministic math over plain python lists. Everything here is NEUTRAL when inputs are missing/empty/zero: ``truth_score`` returns ``0.5`` and ``truth_factor`` returns ``1.0`` so callers that pass nothing leave baseline scoring...
90
3,344
cognee
cognee/modules/truth_subspace/centroids.py
.py
"""Centroid-slot helpers for truth-subspace reranking. The core invariant is simple: slot ``i`` always means the centroid stored in slot ``i`` for the current truth epoch. Everything here is deterministic so a rebuild from the same learning statements produces the same slots. """ from __future__ import annotations i...
199
6,674
cognee
cognee/modules/truth_subspace/build.py
.py
"""Build centroid-slot truth coordinates for a dataset's session learnings. The ``session_learnings`` node set is replayed on every build into up to ``DEFAULT_K`` deterministic centroid slots. DocumentChunk nodes are projected onto those slots and persisted with the centroid epoch used to compute them. """ from datet...
300
11,855
cognee
cognee/modules/tools/errors.py
.py
"""Exceptions raised by the tool subsystem.""" class ToolError(Exception): """Base class for tool execution errors.""" class ToolNotFoundError(ToolError): """Raised when a tool cannot be resolved from the registry or graph.""" class ToolPermissionError(ToolError): """Raised when the acting user lacks ...
46
1,311
cognee
cognee/modules/tools/skill_runs.py
.py
"""Record SkillRun feedback through the remember() typed-entry path.""" from __future__ import annotations from types import SimpleNamespace from typing import Optional from uuid import NAMESPACE_URL, UUID, uuid5 from cognee.memory.entries import SkillRunEntry from cognee.context_global_variables import set_database...
134
4,885
cognee
cognee/modules/tools/resolve_skills.py
.py
"""Dataset-scoped Skill lookup helpers for the agentic retriever.""" from __future__ import annotations from typing import List, Optional, Sequence, Union from uuid import UUID from cognee.modules.engine.models import Skill from cognee.shared.logging_utils import get_logger logger = get_logger("cognee.tools.resolv...
132
4,215
cognee
cognee/modules/tools/__init__.py
.py
"""Tool subsystem: dispatcher, registry, built-in tools, and loaders.""" from cognee.modules.tools.execute_tool import execute_tool from cognee.modules.tools.ingest_skills import add_skills, looks_like_skill_source from cognee.modules.tools.registry import ( get_tool, list_tools_for_dataset, register_built...
22
616
cognee
cognee/modules/tools/registry.py
.py
"""Tool registry: resolves a tool name to a Tool DataPoint + handler callable. Two storage tiers: - Built-in tools are registered in-memory at import time. They exist for every dataset and do not require cognify to have run. - User-defined tools live in the graph as Tool DataPoints, written at ingest time (e.g. wh...
158
5,713
cognee
cognee/modules/tools/execute_tool.py
.py
"""Single entry point for executing a tool call from the agentic retriever. The dispatcher performs four checks in order: 1. Scope: the tool must be in the active skill/tool scope for this turn. 2. Lookup: resolve the tool name to a Tool DataPoint (built-in or graph-backed). 3. Permission: verify the user has the requ...
89
3,339
cognee
cognee/modules/tools/connections.py
.py
"""Persistence for user-authorized external database connections. CRUD over the ``tool_connections`` table plus the deployment-level connections configured via ``TOOL_SQL_CONNECTIONS``. Connection strings are encrypted at rest through :mod:`cognee.modules.integrations.crypto` and only decrypted by :func:`get_tool_conn...
262
9,550
cognee
cognee/modules/tools/context.py
.py
"""Context variables shared between the AgenticRetriever and built-in tools. AgenticRetriever sets `active_skills_var` to the set of resolved Skill objects before each turn so the `load_skill` tool can return their procedure bodies without another round-trip to the graph. `opened_skills_var` accumulates the names of ...
22
847
cognee
cognee/modules/tools/path_safety.py
.py
"""Filesystem helpers for local skill source ingestion.""" from __future__ import annotations import os import tempfile from fnmatch import fnmatch from pathlib import Path from typing import Iterator def _allowed_base_paths() -> list[str]: return [ os.path.normpath(os.path.realpath(os.getcwd())), ...
64
1,868
cognee
cognee/modules/tools/skill_parser.py
.py
"""Small SKILL.md parser for the v1 agentic-skills flow.""" from __future__ import annotations import hashlib import os import re from pathlib import Path from typing import Any, Dict, List, Optional from uuid import UUID, uuid5 import yaml from cognee.modules.engine.models import Skill from cognee.modules.tools.pa...
197
6,642