repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
cognee
cognee/infrastructure/llm/extraction/extract_event_entities.py
.py
import os from pydantic import BaseModel from cognee.infrastructure.llm.config import ( get_llm_config, ) from cognee.infrastructure.llm.LLMGateway import LLMGateway from cognee.infrastructure.llm.prompts.render_prompt import render_prompt async def extract_event_entities(content: str, response_model: type[Base...
47
1,610
cognee
cognee/infrastructure/llm/extraction/knowledge_graph/extract_content_graph.py
.py
import os from typing import Any from pydantic import BaseModel from cognee.infrastructure.engine import DataPoint from cognee.infrastructure.llm.config import ( get_llm_config, ) from cognee.infrastructure.llm.LLMGateway import LLMGateway from cognee.infrastructure.llm.prompts import render_prompt from cognee.sh...
48
1,683
cognee
cognee/infrastructure/llm/extraction/knowledge_graph/extract_event_graph.py
.py
import os from pydantic import BaseModel from cognee.infrastructure.llm.config import ( get_llm_config, ) from cognee.infrastructure.llm.LLMGateway import LLMGateway from cognee.infrastructure.llm.prompts import render_prompt async def extract_event_graph(content: str, response_model: type[BaseModel]) -> BaseMo...
48
1,609
cognee
cognee/infrastructure/llm/structured_output_framework/baml/baml_src/extraction/create_dynamic_baml_type.py
.py
import types from datetime import datetime from enum import Enum from typing import Union, get_args, get_origin from baml_py.baml_py import ClassBuilder # ty:ignore[unresolved-import] from cognee.shared.logging_utils import get_logger logger = get_logger() def create_dynamic_baml_type(tb, baml_model, pydantic_mod...
126
5,327
cognee
cognee/infrastructure/llm/structured_output_framework/baml/baml_src/extraction/acreate_structured_output.py
.py
import asyncio import logging from typing import TypeVar from pydantic import BaseModel from tenacity import ( before_sleep_log, retry, wait_exponential_jitter, ) from cognee.infrastructure.llm.config import get_llm_config from cognee.infrastructure.llm.retry_config import ( llm_retry_condition, l...
96
3,280
cognee
cognee/infrastructure/llm/structured_output_framework/litellm_native/native_adapter.py
.py
"""Universal LiteLLM-native adapter for structured output. Implements ``NativeLiteLLMAdapter`` β€” a single adapter that works with every provider LiteLLM supports, using LiteLLM's own ``response_format`` to obtain validated Pydantic objects **without** the ``instructor`` library. Two paths, chosen per model via ``lite...
391
14,581
cognee
cognee/infrastructure/llm/structured_output_framework/litellm_native/get_native_client.py
.py
"""Factory for the litellm_native structured-output client. Called by ``LLMGateway`` when ``STRUCTURED_OUTPUT_FRAMEWORK="litellm_native"``. Unlike the instructor factory there is no provider dispatch β€” one universal adapter serves every provider β€” and construction is pure attribute assignment (no client build, no I/O)...
60
2,783
cognee
cognee/infrastructure/llm/structured_output_framework/litellm_instructor/llm/types.py
.py
from pydantic import BaseModel class TranscriptionReturnType: text: str payload: BaseModel def __init__(self, text: str, payload: BaseModel): self.text = text self.payload = payload
11
213
cognee
cognee/infrastructure/llm/structured_output_framework/litellm_instructor/llm/rate_limiter.py
.py
""" Rate limiter for LLM API calls. This module provides rate limiting functionality for LLM API calls to prevent exceeding API provider rate limits. The implementation uses the `limits` library with a moving window strategy to limit requests. Configuration is done through the LLMConfig with these settings: - llm_rat...
540
16,744
cognee
cognee/infrastructure/llm/structured_output_framework/litellm_instructor/llm/get_llm_client.py
.py
"""Get the LLM client.""" from dataclasses import dataclass from enum import Enum from functools import lru_cache from typing import Any, Hashable, TypeGuard from cognee.infrastructure.llm.config import get_llm_context_config from cognee.infrastructure.llm.exceptions import ( LLMAPIKeyNotSetError, Unsupported...
421
15,740
cognee
cognee/infrastructure/llm/structured_output_framework/litellm_instructor/llm/llm_interface.py
.py
"""LLM Interface""" from abc import ABC, abstractmethod from typing import Any, TypeVar import litellm from pydantic import BaseModel from cognee.infrastructure.llm.structured_output_framework.litellm_instructor.llm.types import ( TranscriptionReturnType, ) T = TypeVar("T", bound="BaseModel | str") class LLMI...
97
3,476
cognee
cognee/infrastructure/llm/structured_output_framework/litellm_instructor/llm/instructor_modes.py
.py
"""Single source of truth for each provider's default Instructor mode. Replaces the ``default_instructor_mode`` class attributes that were previously duplicated across the individual adapter modules. """ import instructor # Values match each adapter's historical default. Azure is absent on purpose: # AzureOpenAIAdap...
30
1,032
cognee
cognee/infrastructure/llm/structured_output_framework/litellm_instructor/llm/gemini/adapter.py
.py
"""Adapter for Gemini API LLM provider""" import logging from typing import Any import instructor import litellm from instructor.core import InstructorRetryException from litellm.exceptions import ContentPolicyViolationError from openai import ContentFilterFinishReasonError from pydantic import BaseModel from tenacit...
201
7,553
cognee
cognee/infrastructure/llm/structured_output_framework/litellm_instructor/llm/bedrock/__init__.py
.py
"""Bedrock LLM adapter module.""" from .adapter import BedrockAdapter __all__ = ["BedrockAdapter"]
6
101
cognee
cognee/infrastructure/llm/structured_output_framework/litellm_instructor/llm/bedrock/adapter.py
.py
import logging from typing import Any import instructor import litellm from instructor.exceptions import InstructorRetryException from litellm.exceptions import ContentPolicyViolationError from pydantic import BaseModel from tenacity import before_sleep_log, retry, wait_exponential_jitter from cognee.infrastructure.f...
182
6,709
cognee
cognee/infrastructure/llm/structured_output_framework/litellm_instructor/llm/mcp_sampling/__init__.py
.py
"""MCP-sampling LLM backend. Reuses the host harness's LLM connection via the MCP ``sampling/createMessage`` capability instead of a separate provider client, so no ``LLM_API_KEY`` is needed when the host grants sampling. See issue #3644. """
7
244
cognee
cognee/infrastructure/llm/structured_output_framework/litellm_instructor/llm/mcp_sampling/session_context.py
.py
"""Access to the host MCP sampling session. When cognee runs as an MCP server (``cognee-mcp``), the host client can grant a ``sampling/createMessage`` capability (support varies by host). That call must happen in the server process within the request, where the client connection lives. This module lets the LLM adapter...
55
2,118
cognee
cognee/infrastructure/llm/structured_output_framework/litellm_instructor/llm/mcp_sampling/adapter.py
.py
"""LLM adapter that delegates completions to the host via MCP sampling. When cognee runs as an MCP server, this routes structured-output requests through the host client's ``sampling/createMessage`` capability instead of a provider API, so no ``LLM_API_KEY`` is needed (issue #3644). MCP sampling returns free text β€” t...
173
7,088
cognee
cognee/infrastructure/llm/structured_output_framework/litellm_instructor/llm/mistral/adapter.py
.py
import asyncio import logging from typing import Any import instructor import litellm from litellm import JSONSchemaValidationError from mistralai import Mistral # ty:ignore[unresolved-import] from pydantic import BaseModel from tenacity import ( before_sleep_log, retry, retry_if_not_exception_type, s...
200
7,367
cognee
cognee/infrastructure/llm/structured_output_framework/litellm_instructor/llm/openai/adapter.py
.py
import asyncio import logging from typing import Any import instructor import litellm from instructor.core import InstructorRetryException from litellm.exceptions import ContentPolicyViolationError from openai import ContentFilterFinishReasonError from pydantic import BaseModel from tenacity import ( before_sleep_...
271
9,568
cognee
cognee/infrastructure/llm/structured_output_framework/litellm_instructor/llm/anthropic/adapter.py
.py
import logging from typing import Any import anthropic # ty:ignore[unresolved-import] import instructor from instructor.core.patch import AsyncInstructorChatCompletionCreate from pydantic import BaseModel from tenacity import ( before_sleep_log, retry, wait_exponential_jitter, ) from cognee.infrastructur...
122
4,499
cognee
cognee/infrastructure/llm/structured_output_framework/litellm_instructor/llm/azure_openai/adapter.py
.py
"""Adapter for Azure OpenAI with managed identity and API key support.""" import logging from typing import Any import instructor import litellm from instructor.core import InstructorRetryException from litellm.exceptions import ContentPolicyViolationError from openai import ( AsyncAzureOpenAI, ContentFilterF...
276
10,438
cognee
cognee/infrastructure/llm/structured_output_framework/litellm_instructor/llm/generic_llm_api/adapter.py
.py
"""Adapter for Generic API LLM provider API""" import asyncio import base64 import logging import mimetypes from typing import Any import instructor import litellm from instructor.core import InstructorRetryException from litellm.exceptions import ContentPolicyViolationError from openai import ContentFilterFinishReas...
416
15,798
cognee
cognee/infrastructure/llm/structured_output_framework/litellm_instructor/llm/llama_cpp/adapter.py
.py
"""Adapter for Instructor-backed Structured Output Framework for Llama CPP""" import asyncio import logging import threading from typing import Any, cast import instructor from instructor.core.patch import InstructorChatCompletionCreate from openai import AsyncOpenAI from pydantic import BaseModel from tenacity impor...
236
8,595
cognee
cognee/infrastructure/llm/structured_output_framework/litellm_instructor/llm/ollama/adapter.py
.py
import asyncio import base64 import logging from typing import Any import instructor import litellm from openai import AsyncOpenAI from pydantic import BaseModel from tenacity import ( before_sleep_log, retry, retry_if_not_exception_type, stop_after_attempt, wait_exponential_jitter, ) from cognee....
293
10,316
cognee
cognee/infrastructure/context/BaseContextProvider.py
.py
from abc import ABC, abstractmethod from cognee.infrastructure.engine import DataPoint class BaseContextProvider(ABC): """ Base class for context retrieval strategies. This class serves as a blueprint for creating different strategies that retrieve context based on specified entities and a query. An...
33
1,170
cognee
cognee/infrastructure/loaders/supported_loaders.py
.py
from cognee.infrastructure.loaders import LoaderInterface from cognee.infrastructure.loaders.core import ( AudioLoader, CodeLoader, CsvLoader, ImageLoader, TextLoader, VideoLoader, ) from cognee.infrastructure.loaders.external import PyPdfLoader # Registry for loader implementations supported_l...
61
1,772
cognee
cognee/infrastructure/loaders/__init__.py
.py
""" File loader infrastructure for cognee. This package provides a plugin-based system for loading different file formats into cognee, following the same patterns as database adapters. Main exports: - get_loader_engine(): Factory function to get configured loader engine - use_loader(): Register custom loaders at runt...
19
643
cognee
cognee/infrastructure/loaders/get_loader_engine.py
.py
from functools import lru_cache from .create_loader_engine import create_loader_engine from .LoaderEngine import LoaderEngine @lru_cache def get_loader_engine() -> LoaderEngine: """ Factory function to get loader engine. Follows cognee's pattern with @lru_cache for efficient reuse of engine instance...
20
518
cognee
cognee/infrastructure/loaders/create_loader_engine.py
.py
from cognee.shared.logging_utils import get_logger from .LoaderEngine import LoaderEngine from .supported_loaders import supported_loaders logger = get_logger(__name__) def create_loader_engine() -> LoaderEngine: """ Create loader engine with given configuration. Follows cognee's pattern for engine cre...
34
965
cognee
cognee/infrastructure/loaders/LoaderInterface.py
.py
from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Any, ClassVar, Optional from uuid import UUID @dataclass class LoaderResult: """Rich loader output for loaders that own more than text extraction. ``load()`` normally returns the stored derived-text path as a plain str. ...
88
2,613
cognee
cognee/infrastructure/loaders/use_loader.py
.py
from cognee.infrastructure.loaders import LoaderInterface from .supported_loaders import supported_loaders def use_loader(loader_name: str, loader_class: type[LoaderInterface]) -> None: """ Register a loader at runtime. This allows external packages and custom loaders to be registered into the loade...
24
688
cognee
cognee/infrastructure/loaders/LoaderEngine.py
.py
from typing import Any import filetype from cognee.infrastructure.files.utils.guess_file_type import guess_file_type from cognee.shared.logging_utils import get_logger from .LoaderInterface import LoaderInterface, LoaderResult logger = get_logger(__name__) class LoaderEngine: """ Main loader engine for ma...
243
8,536
cognee
cognee/infrastructure/loaders/core/audio_loader.py
.py
import os from typing import Any from cognee.infrastructure.files.storage import get_file_storage, get_storage_config from cognee.infrastructure.files.utils.get_file_metadata import get_file_metadata from cognee.infrastructure.llm.LLMGateway import LLMGateway from cognee.infrastructure.loaders.LoaderInterface import L...
104
3,086
cognee
cognee/infrastructure/loaders/core/text_loader.py
.py
import os from typing import Any from cognee.infrastructure.files.storage import get_file_storage, get_storage_config from cognee.infrastructure.files.utils.get_file_metadata import get_file_metadata from cognee.infrastructure.loaders.LoaderInterface import LoaderInterface class TextLoader(LoaderInterface): """ ...
91
2,945
cognee
cognee/infrastructure/loaders/core/csv_loader.py
.py
import csv import os from typing import Any from cognee.infrastructure.files.storage import get_file_storage, get_storage_config from cognee.infrastructure.files.utils.get_file_metadata import get_file_metadata from cognee.infrastructure.loaders.LoaderInterface import LoaderInterface class CsvLoader(LoaderInterface)...
95
2,984
cognee
cognee/infrastructure/loaders/core/code_loader.py
.py
import os from pathlib import Path from typing import Any from cognee.infrastructure.files.storage import get_file_storage, get_storage_config from cognee.infrastructure.files.utils.get_file_metadata import get_file_metadata from cognee.infrastructure.loaders.LoaderInterface import LoaderInterface, LoaderResult # Sou...
108
3,748
cognee
cognee/infrastructure/loaders/core/image_loader.py
.py
import asyncio import os from functools import lru_cache from typing import Any, Optional from cognee.infrastructure.files.storage import get_file_storage, get_storage_config from cognee.infrastructure.files.utils.get_file_metadata import get_file_metadata from cognee.infrastructure.llm.config import get_llm_config fr...
403
14,739
cognee
cognee/infrastructure/loaders/core/video_loader.py
.py
import asyncio import os import shutil import subprocess import tempfile from contextlib import asynccontextmanager from typing import Any from cognee.infrastructure.files.storage import get_file_storage, get_storage_config from cognee.infrastructure.files.utils.get_file_metadata import get_file_metadata from cognee.i...
252
9,236
cognee
cognee/infrastructure/loaders/external/beautiful_soup_loader.py
.py
"""BeautifulSoup-based web crawler for extracting content from web pages. This module provides the BeautifulSoupCrawler class for fetching and extracting content from web pages using BeautifulSoup or Playwright for JavaScript-rendered pages. It supports robots.txt handling, rate limiting, and custom extraction rules. ...
333
13,886
cognee
cognee/infrastructure/loaders/external/__init__.py
.py
""" External loader implementations for cognee. This module contains loaders that depend on external libraries: - pypdf_loader: PDF processing using pypdf - unstructured_loader: Document processing using unstructured - dlt_loader: Data lake/warehouse integration using DLT These loaders are optional and only available...
51
1,118
cognee
cognee/infrastructure/loaders/external/dlt_csv_loader.py
.py
"""CSV ingestion through the DLT pipeline, packaged as a loader. Registered above the plain ``csv_loader`` in the engine's priority order, so when the ``dlt`` extra is installed every CSV takes the structured route: staging ingestion via dlt, one manifest per file with a stable data_id, and the no-LLM DLT cognify rout...
113
4,678
cognee
cognee/infrastructure/loaders/external/pypdf_loader.py
.py
from typing import Any from cognee.infrastructure.files.storage import get_file_storage, get_storage_config from cognee.infrastructure.files.utils.get_file_metadata import get_file_metadata from cognee.infrastructure.loaders.LoaderInterface import LoaderInterface from cognee.shared.logging_utils import get_logger log...
99
3,524
cognee
cognee/infrastructure/loaders/external/unstructured_loader.py
.py
from typing import Any from cognee.infrastructure.files.storage import get_file_storage, get_storage_config from cognee.infrastructure.files.utils.get_file_metadata import get_file_metadata from cognee.infrastructure.loaders.LoaderInterface import LoaderInterface from cognee.shared.logging_utils import get_logger try...
129
4,620
cognee
cognee/infrastructure/loaders/external/docling_loader.py
.py
import os import sys import types from functools import lru_cache from typing import Any from cognee.infrastructure.files.storage import get_file_storage, get_storage_config from cognee.infrastructure.files.utils.get_file_metadata import get_file_metadata from cognee.infrastructure.loaders.LoaderInterface import Loade...
160
6,210
cognee
cognee/infrastructure/loaders/external/advanced_pdf_loader.py
.py
"""Advanced PDF loader leveraging unstructured for layout-aware extraction.""" from __future__ import annotations import asyncio from dataclasses import dataclass from typing import Any from cognee.infrastructure.files.storage import get_file_storage, get_storage_config from cognee.infrastructure.files.utils.get_fil...
231
8,281
cognee
cognee/infrastructure/engine/utils/parse_id.py
.py
from typing import Any from uuid import UUID def parse_id(id: Any) -> Any: """ Parse the input ID and convert it to a UUID object if it is a valid string representation. If the input is not a string or if the string cannot be converted to a UUID, return the input unchanged. This function catches ...
32
905
cognee
cognee/infrastructure/engine/utils/generate_node_id.py
.py
from uuid import NAMESPACE_OID, UUID, uuid5 def generate_node_id(node_id: str) -> UUID: return uuid5(NAMESPACE_OID, node_id.lower().replace(" ", "_").replace("'", ""))
6
174
cognee
cognee/infrastructure/engine/models/DataPoint.py
.py
import logging from datetime import datetime, timezone from typing import Any from uuid import NAMESPACE_OID, UUID, uuid4, uuid5 from pydantic import BaseModel, ConfigDict, Field from typing_extensions import NotRequired, TypedDict from cognee.infrastructure.engine.models.FieldAnnotations import _Dedup, _Embeddable f...
376
14,799
cognee
cognee/infrastructure/engine/models/Edge.py
.py
from typing import Any from pydantic import BaseModel class Edge(BaseModel): """ Represents edge metadata for relationships between DataPoints. This class is used to define edge properties like weight when creating relationships between DataPoints using tuple syntax: Example: # Single w...
32
1,019
cognee
cognee/infrastructure/engine/models/FieldAnnotations.py
.py
""" Field role annotations for DataPoint. These make implicit DataPoint behaviors explicit and visible at definition time. They are informational markers β€” the system also supports the legacy metadata = {"index_fields": [...]} approach. Usage: from typing import Annotated from cognee.infrastructure.engine.mod...
86
2,813
cognee
cognee/infrastructure/engine/models/ExtendableDataPoint.py
.py
from .DataPoint import DataPoint class ExtendableDataPoint(DataPoint): """ Represent an extendable data point subclassing from DataPoint. """ pass
10
166
cognee
cognee/infrastructure/files/exceptions.py
.py
from fastapi import status class FileContentHashingError(Exception): """Raised when the file content cannot be hashed.""" def __init__( self, message: str = "Failed to hash content of the file.", name: str = "FileContentHashingError", status_code: int = status.HTTP_422_UNPROCE...
14
404
cognee
cognee/infrastructure/files/storage/get_file_storage.py
.py
import os from cognee.base_config import get_base_config from .StorageManager import StorageManager def get_file_storage(storage_path: str) -> StorageManager: base_config = get_base_config() # Use S3FileStorage if the storage_path is an S3 URL or if configured for S3 if storage_path.startswith("s3://")...
24
797
cognee
cognee/infrastructure/files/storage/FileBufferedReader.py
.py
from io import BufferedReader class FileBufferedReader(BufferedReader): def __init__(self, file_obj, name: str) -> None: super().__init__(file_obj) self._file = file_obj self._name = name @property def name(self) -> str: return self._name def read(self, size: int | No...
17
387
cognee
cognee/infrastructure/files/storage/storage.py
.py
from collections.abc import AsyncGenerator, Generator from contextlib import asynccontextmanager from typing import BinaryIO, Protocol from cognee.infrastructure.files.storage.FileBufferedReader import FileBufferedReader class Storage(Protocol): storage_path: str """ Abstract interface for storage opera...
158
4,257
cognee
cognee/infrastructure/files/storage/LocalFileStorage.py
.py
import os import shutil from collections.abc import AsyncGenerator from contextlib import asynccontextmanager from pathlib import Path from typing import BinaryIO from urllib.parse import urlparse from .FileBufferedReader import FileBufferedReader from .storage import Storage def get_parsed_path(file_path: str) -> s...
345
13,268
cognee
cognee/infrastructure/files/storage/config.py
.py
from contextvars import ContextVar file_storage_config = ContextVar("file_storage_config", default=None)
4
106
cognee
cognee/infrastructure/files/storage/S3FileStorage.py
.py
import os import time from collections.abc import AsyncGenerator from contextlib import asynccontextmanager from typing import TYPE_CHECKING, BinaryIO from cognee.infrastructure.files.storage.FileBufferedReader import FileBufferedReader from cognee.infrastructure.files.storage.s3_config import get_s3_config from cogne...
349
12,252
cognee
cognee/infrastructure/files/storage/s3_config.py
.py
from functools import lru_cache from typing import Optional from pydantic_settings import BaseSettings, SettingsConfigDict class S3Config(BaseSettings): aws_region: str | None = None aws_endpoint_url: str | None = None aws_access_key_id: str | None = None aws_secret_access_key: str | None = None ...
21
575
cognee
cognee/infrastructure/files/storage/StorageManager.py
.py
import inspect from contextlib import asynccontextmanager from typing import BinaryIO from cognee.infrastructure.files.storage.S3FileStorage import S3FileStorage from .storage import Storage class StorageManager: """ Manages storage operations by delegating tasks to a storage backend. Public methods in...
141
4,204
cognee
cognee/infrastructure/files/storage/get_storage_config.py
.py
from cognee.base_config import get_base_config from .config import file_storage_config def get_global_storage_config() -> dict[str, str]: base_config = get_base_config() return { "data_root_directory": base_config.data_root_directory, } def get_storage_config() -> dict[str, str]: context_c...
20
447
cognee
cognee/infrastructure/files/utils/guess_file_type.py
.py
import io from pathlib import Path from tempfile import SpooledTemporaryFile from typing import Any, BinaryIO, Optional import filetype from filetype.types.base import Type class FileTypeException(Exception): """ Represents an exception for file type errors. This exception is raised when an invalid file...
89
2,634
cognee
cognee/infrastructure/files/utils/get_file_content_hash.py
.py
import hashlib import os from os import path from typing import BinaryIO, Union from ..exceptions import FileContentHashingError from ..storage import get_file_storage from .local_path_safety import resolve_local_path async def get_file_content_hash(file_obj: str | BinaryIO) -> str: h = hashlib.md5() try: ...
48
1,693
cognee
cognee/infrastructure/files/utils/open_data_file.py
.py
import os from collections.abc import AsyncGenerator from contextlib import asynccontextmanager from os import path from urllib.parse import urlparse from cognee.infrastructure.files.storage.FileBufferedReader import FileBufferedReader from cognee.infrastructure.files.storage.LocalFileStorage import LocalFileStorage f...
70
3,034
cognee
cognee/infrastructure/files/utils/get_file_metadata.py
.py
import io import os.path from pathlib import PureWindowsPath from typing import BinaryIO, Optional, TypedDict from urllib.parse import unquote, urlparse from cognee.infrastructure.files.utils.get_file_content_hash import get_file_content_hash from cognee.shared.logging_utils import get_logger from .guess_file_type im...
111
3,956
cognee
cognee/infrastructure/files/utils/get_data_file_path.py
.py
import os import posixpath from urllib.parse import unquote, urlparse def get_data_file_path(file_path: str) -> str: """Normalize file paths from various URI schemes to filesystem paths. Handles file://, s3://, and regular filesystem paths. Decodes percent-encoded characters and preserves UNC network pat...
56
2,039
cognee
cognee/infrastructure/files/utils/extract_text_from_file.py
.py
from typing import BinaryIO import filetype from pypdf import PdfReader def extract_text_from_file(file: BinaryIO, file_type: filetype.Type) -> str | None: """ Extract text from a file based on its type. Supports extraction from PDF and plain text file formats. For PDF files, it reads the first thre...
35
1,120
cognee
cognee/infrastructure/files/utils/local_path_safety.py
.py
import os import tempfile from pathlib import Path from cognee.base_config import get_base_config ALLOWED_LOCAL_FILE_ROOTS_ENV = "COGNEE_ALLOWED_LOCAL_FILE_ROOTS" def get_allowed_local_file_roots() -> tuple[Path, ...]: configured_roots = os.getenv(ALLOWED_LOCAL_FILE_ROOTS_ENV) if configured_roots: ...
56
2,242
cognee
cognee/infrastructure/files/utils/is_text_content.py
.py
def is_text_content(content): """ Determine if the content is text-based. This function checks for various indicators of text content, including null bytes, byte order marks (BOMs), ASCII character ranges, and common line breaks. If none of these indicators are present, the function defaults to ass...
45
1,316
cognee
cognee/infrastructure/databases/hybrid/neptune_analytics/NeptuneAnalyticsAdapter.py
.py
"""Neptune Analytics Hybrid Adapter combining Vector and Graph functionality""" import asyncio import json from collections import Counter from typing import List, Optional, Any, Dict, Tuple from uuid import UUID from cognee.modules.graph.models.EdgeType import EdgeType from cognee.infrastructure.databases.exceptions...
613
24,886
cognee
cognee/infrastructure/databases/hybrid/postgres/adapter.py
.py
"""Postgres hybrid adapter combining graph and vector functionality. Composes a PostgresAdapter (graph) and PGVectorAdapter (vector) that share the same Postgres database. Implements both GraphDBInterface and VectorDBInterface by delegating to the underlying adapters. Because both adapters hit the same database, this...
688
28,015
cognee
cognee/infrastructure/databases/exceptions/exceptions.py
.py
from fastapi import status from cognee.exceptions import ( CogneeApiError, CogneeSystemError, CogneeValidationError, CogneeConfigurationError, ) class DatabaseNotCreatedError(CogneeSystemError): """ Represents an error indicating that the database has not been created. This error should be...
253
8,907
cognee
cognee/infrastructure/databases/exceptions/__init__.py
.py
""" Custom exceptions for the Cognee API. This module defines a set of exceptions for handling various database errors """ from .exceptions import ( EntityNotFoundError, EntityAlreadyExistsError, UnsupportedProvenanceCapability, DatabaseNotCreatedError, EmbeddingContextWindowTooSmallError, Emb...
21
542
cognee
cognee/infrastructure/databases/provenance/write_context.py
.py
from __future__ import annotations from typing import Any from uuid import UUID from cognee.infrastructure.databases.provenance.markers import stores_provenance_in_graph from cognee.infrastructure.databases.provenance.source_refs import make_source_ref_key def data_item_id(data_item: Any) -> Any: """Resolve the...
101
3,427
cognee
cognee/infrastructure/databases/provenance/__init__.py
.py
from .constants import ( GRAPH_DELETE_MODE_GRAPH_PROVENANCE, GRAPH_DELETE_MODE_KEY, GRAPH_PROVENANCE_VERSION, GRAPH_PROVENANCE_VERSION_KEY, SOURCE_REF_PREFIX, SOURCE_RUN_REF_PREFIX, ) from .delete_data import EdgeDeleteData, EdgeIdentity, NodeDeleteData from .source_refs import ( get_data_id...
44
1,224
cognee
cognee/infrastructure/databases/provenance/constants.py
.py
SOURCE_REF_PREFIX = "source_ref:v1" SOURCE_RUN_REF_PREFIX = "source_run_ref:v1" GRAPH_PROVENANCE_VERSION_KEY = "provenance_version" GRAPH_DELETE_MODE_KEY = "delete_mode" GRAPH_PROVENANCE_VERSION = "1" # Stored marker value written into a graph's metadata. The string stays # "graph_native" as a stable on-disk token (ch...
11
486
cognee
cognee/infrastructure/databases/provenance/source_ref_state.py
.py
"""Pure source-ref state transitions for graph provenance (COG-5522). Backend-agnostic logic shared by every graph adapter that implements the Part 0 provenance contract. It operates only on lists of contract strings β€” no storage, connection, or query concerns β€” so the set-merge / dedupe / derive / run-ref rules live ...
149
5,986
cognee
cognee/infrastructure/databases/provenance/delete_data.py
.py
from dataclasses import dataclass from typing import Any @dataclass(frozen=True) class EdgeIdentity: """Stable edge identifier used when provenance code addresses graph relationships.""" source_id: str target_id: str relationship_name: str @dataclass(frozen=True) class NodeDeleteData: """ N...
55
1,687
cognee
cognee/infrastructure/databases/provenance/markers.py
.py
"""Graph provenance markers. A graph "stores its provenance in the graph" when its graph-level metadata advertises the graph-provenance delete mode. The marker is a delete-mode boundary, not a migration flag: a graph is either graph-provenance backed or relational-ledger backed. Marking happens lazily for empty graphs...
74
2,973
cognee
cognee/infrastructure/databases/provenance/source_refs.py
.py
from uuid import UUID from .constants import SOURCE_REF_PREFIX, SOURCE_RUN_REF_PREFIX def make_source_ref_key(dataset_id: UUID, data_id: UUID) -> str: """Build the stable key for one owning dataset/data item pair.""" return f"{SOURCE_REF_PREFIX}:{dataset_id}:{data_id}" def get_dataset_id_from_source_ref_ke...
46
1,925
cognee
cognee/infrastructure/databases/vector/create_vector_engine.py
.py
import os import inspect from numbers import Number from .supported_databases import supported_databases from .embeddings import get_embedding_engine from cognee.infrastructure.databases.dataset_queue.pinning import dataset_queue_pin_predicate from cognee.infrastructure.databases.utils.closing_lru_cache import closing...
349
13,804
cognee
cognee/infrastructure/databases/vector/vector_db_interface.py
.py
from typing import List, Protocol, Optional, Any from abc import abstractmethod from cognee.infrastructure.engine import DataPoint from .models.PayloadSchema import PayloadSchema from uuid import UUID from cognee.modules.users.models import User class VectorDBInterface(Protocol): """ Defines an interface for ...
313
11,806
cognee
cognee/infrastructure/databases/vector/use_vector_adapter.py
.py
from .supported_databases import supported_databases def use_vector_adapter(vector_db_name, vector_db_adapter): supported_databases[vector_db_name] = vector_db_adapter
6
174
cognee
cognee/infrastructure/databases/vector/config.py
.py
import json import os import pydantic from pathlib import Path from functools import lru_cache from typing import Union from pydantic_settings import BaseSettings, SettingsConfigDict from cognee.base_config import get_base_config from cognee.root_dir import ensure_absolute_path class VectorConfig(BaseSettings): ...
144
5,662
cognee
cognee/infrastructure/databases/vector/get_vector_engine.py
.py
import warnings from .config import get_vectordb_context_config from .create_vector_engine import create_vector_engine class _VectorEngineHandle: """Stable reference to the current vector engine that survives cache invalidation. Database engine instances are cached via ``closing_lru_cache``. Several op...
133
6,135
cognee
cognee/infrastructure/databases/vector/exceptions/exceptions.py
.py
from fastapi import status from cognee.exceptions import CogneeValidationError class CollectionNotFoundError(CogneeValidationError): """ Represents an error that occurs when a requested collection cannot be found. This class extends the CogneeValidationError to handle specific cases where a requested ...
23
769
cognee
cognee/infrastructure/databases/vector/embeddings/utils.py
.py
from typing import List, Union from cognee.shared.logging_utils import setup_logging logger = setup_logging() def is_embeddable(s: str) -> bool: """ Check if input string is embeddable, if not it will be replaced with a dummy value to prevent API errors. Empty strings and a string with only a space chara...
52
1,767
cognee
cognee/infrastructure/databases/vector/embeddings/OpenAICompatibleEmbeddingEngine.py
.py
""" Embedding engine for OpenAI-compatible API servers (llama.cpp, vLLM, TEI, etc.). Uses the openai SDK directly instead of litellm to avoid known incompatibilities with local embedding servers: - litellm sends ``encoding_format: null`` which strict JSON parsers reject (llama.cpp: ``[json.exception.type_error.302] ...
252
9,297
cognee
cognee/infrastructure/databases/vector/embeddings/LiteLLMEmbeddingEngine.py
.py
import asyncio import logging from cognee.shared.logging_utils import get_logger from typing import List, Optional import numpy as np import math import re from tenacity import ( retry, stop_after_delay, wait_exponential_jitter, retry_if_not_exception_type, before_sleep_log, ) import litellm import...
341
14,410
cognee
cognee/infrastructure/databases/vector/embeddings/FastembedEmbeddingEngine.py
.py
import asyncio import os import logging import math from typing import List, Optional import numpy as np try: from fastembed import TextEmbedding except ImportError: raise ImportError( "fastembed is required for FastembedEmbeddingEngine but is not installed. " "Install it with: pip install 'cog...
218
7,489
cognee
cognee/infrastructure/databases/vector/embeddings/EmbeddingEngine.py
.py
from typing import Protocol class EmbeddingEngine(Protocol): """ Defines an interface for embedding text. Provides methods to embed text and get the vector size. """ async def embed_text(self, text: list[str]) -> list[list[float]]: """ Embed the provided text and return a list of ...
46
1,287
cognee
cognee/infrastructure/databases/vector/embeddings/config.py
.py
from typing import Optional from functools import lru_cache from pydantic_settings import BaseSettings, SettingsConfigDict from cognee.shared.logging_utils import get_logger logger = get_logger("embedding_config") # Hard fallback when neither litellm nor fastembed knows the model. This used # to be the uncondition...
174
7,410
cognee
cognee/infrastructure/databases/vector/embeddings/OllamaEmbeddingEngine.py
.py
import asyncio import math from cognee.shared.logging_utils import get_logger import aiohttp from typing import List, Optional import os import litellm import logging import aiohttp.http_exceptions import numpy as np from tenacity import ( retry, stop_after_delay, wait_exponential_jitter, retry_if_not_e...
246
8,859
cognee
cognee/infrastructure/databases/vector/embeddings/get_embedding_engine.py
.py
from cognee.infrastructure.databases.vector.embeddings.config import get_embedding_context_config from cognee.infrastructure.llm.config import ( get_llm_context_config, ) from .EmbeddingEngine import EmbeddingEngine from functools import lru_cache def get_embedding_engine() -> EmbeddingEngine: """ Retriev...
129
4,751
cognee
cognee/infrastructure/databases/vector/pgvector/PGVectorSharedDatasetDatabaseHandler.py
.py
from uuid import UUID from typing import Optional from cognee.modules.users.models import User from cognee.modules.users.models import DatasetDatabase from cognee.infrastructure.databases.vector import get_vectordb_config from cognee.infrastructure.databases.relational import get_relational_config from cognee.infrastr...
121
5,139
cognee
cognee/infrastructure/databases/vector/pgvector/create_db_and_tables.py
.py
from sqlalchemy import text from ..get_vector_engine import get_vector_engine_async, get_vectordb_context_config from cognee.context_global_variables import backend_access_control_enabled async def create_db_and_tables(): # Get appropriate vector db configuration based on current async context vector_config ...
15
652
cognee
cognee/infrastructure/databases/vector/pgvector/PGVectorDatasetDatabaseHandler.py
.py
from uuid import UUID from typing import Optional from sqlalchemy import text from cognee.modules.users.models import User from cognee.modules.users.models import DatasetDatabase from cognee.infrastructure.databases.vector import get_vectordb_config from cognee.infrastructure.databases.dataset_database_handler import...
104
4,318
cognee
cognee/infrastructure/databases/vector/pgvector/serialize_data.py
.py
from datetime import datetime from uuid import UUID def serialize_data(data): """ Recursively convert various data types to serializable formats. This function processes dictionaries and lists, converting any datetime objects to ISO 8601 strings, and UUID objects to their string representation. Other...
35
1,111
cognee
cognee/infrastructure/databases/vector/pgvector/PGVectorAdapter.py
.py
import asyncio from typing import Any, Dict, List, Optional, get_type_hints from uuid import UUID from sqlalchemy.inspection import inspect from sqlalchemy.orm import Mapped, mapped_column from sqlalchemy.dialects.postgresql import insert from sqlalchemy import JSON, Column, Table, select, delete, MetaData, func, text ...
829
37,129