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 | distributed/deploy/islo_sandbox.py | .py | """
Cognee on Islo β deploy Cognee API inside an Islo cloud sandbox.
Islo (https://islo.dev) provides isolated cloud sandbox VMs for autonomous
agents, built by the Incredibuild team. This script uses the official Islo
Python SDK to create a sandbox, install Cognee, start the API server, and print
a temporary public s... | 285 | 9,725 |
cognee | kuzu/database.py | .py | """Compatibility shim for ``kuzu.database`` imports."""
from ladybug.database import * # noqa: F403
from ladybug.database import Database # noqa: F401
| 5 | 154 |
cognee | tools/write_docs_assessment_outputs.py | .py | #!/usr/bin/env python3
"""Write workflow outputs derived from a docs assessment result."""
from __future__ import annotations
import argparse
import json
import os
from pathlib import Path
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Write docs assessment workflow output... | 38 | 1,240 |
cognee | tools/prepare_docs_pr_content.py | .py | #!/usr/bin/env python3
"""Prepare pull request title, body, and changed-file outputs for docs drafts."""
from __future__ import annotations
import argparse
import json
import os
import subprocess
from pathlib import Path
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Prepa... | 84 | 2,983 |
cognee | tools/generate_release_notes.py | .py | #!/usr/bin/env python3
"""
Generate human-friendly release notes by analyzing git diff with LLM.
This script compares changes between two branches (typically main and dev)
and uses an LLM to generate readable, user-focused release notes.
Uses litellm + instructor directly to avoid cognee's dotenv.load_dotenv(override... | 589 | 21,671 |
cognee | tools/send_failure_email.py | .py | #!/usr/bin/env python3
"""Send a workflow failure notification email."""
from __future__ import annotations
import os
import smtplib
import textwrap
from email.message import EmailMessage
def main() -> None:
subject = "dev_previous_day_commits.yml failed"
body = textwrap.dedent(
f"""\
The pr... | 49 | 1,388 |
cognee | tools/prepare_docs_edit_scope.py | .py | #!/usr/bin/env python3
"""Prepare source and documentation candidates for automated docs edits."""
from __future__ import annotations
import argparse
import json
import os
import urllib.request
from pathlib import Path
from typing import Any
MAX_SOURCE_FILES_TO_INSPECT = 8
MAX_DOC_FILES_TO_CONSIDER = 5
IGNORED_KEY... | 386 | 12,943 |
cognee | tools/generate_branch_notes.py | .py | #!/usr/bin/env python3
"""
Generate notes for a single merged branch.
Matches the LLM integration style used by tools/generate_release_notes.py.
"""
from __future__ import annotations
import argparse
import asyncio
import base64
import json
import os
from pathlib import Path
from typing import Any
try:
from too... | 206 | 6,878 |
cognee | tools/assess_branch_notes.py | .py | #!/usr/bin/env python3
"""
Assess whether generated dev notes imply a documentation update is needed.
Matches the LLM integration style used by tools/generate_release_notes.py:
- uses litellm + instructor directly
- reads LLM_API_KEY / LLM_MODEL from the environment
- raises on missing dependencies, missing credential... | 143 | 4,815 |
cognee | tools/write_docs_scope_plan_outputs.py | .py | #!/usr/bin/env python3
"""Write workflow outputs derived from a docs scope plan."""
from __future__ import annotations
import argparse
import os
import re
from pathlib import Path
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Write docs scope plan workflow outputs")
p... | 47 | 1,346 |
cognee | tools/manage_docs_pr.py | .py | #!/usr/bin/env python3
"""Create or update an automated draft PR in the docs repository."""
from __future__ import annotations
import argparse
import json
import os
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Any
def parse_args() -> argparse.Namespace:
... | 123 | 3,559 |
cognee | tools/check-lockfile.py | .py | import sys
# File and string to search for
lockfile_name = "poetry.lock"
hash_string = "hash = "
threshold = 100
try:
count = 0
with open(lockfile_name, "r", encoding="utf8") as file:
for line in file:
if hash_string in line:
count += 1
if count >= threshold... | 29 | 893 |
cognee | tools/simulate_agent.py | .py | """Simulate an agent connecting to a Cognee instance.
Usage:
python tools/simulate_agent.py --type SecFilingAgent --port 8000
python tools/simulate_agent.py --type SupportBot --port 8000 --data-file /path/to/doc.txt
python tools/simulate_agent.py --type ResearchAgent --port 8000 --search "What is Cognee?"
... | 173 | 5,871 |
cognee | tools/prepare_merged_branches.py | .py | #!/usr/bin/env python3
"""
Collect PRs merged into a target branch within a configurable UTC lookback window.
When GITHUB_OUTPUT and GITHUB_STEP_SUMMARY are present, this script writes the same
workflow outputs and summary content expected by dev_previous_day_commits.yml.
"""
from __future__ import annotations
impor... | 344 | 11,416 |
cognee | tools/merge_branch_diff.py | .py | #!/usr/bin/env python3
"""Utilities for extracting the actual branch delta from a merge commit."""
from __future__ import annotations
import subprocess
import sys
from pathlib import Path
def run_git_command(command: list[str], cwd: str | Path | None = None) -> str:
try:
result = subprocess.run(
... | 70 | 2,115 |
cognee | tools/sync_release_docs.py | .py | #!/usr/bin/env python3
"""
Sync release docs artifacts into a checked-out cognee-docs repository.
This script is intended for CI usage from the core `cognee` repository:
1) Generate OpenAPI spec from the current codebase.
2) Copy spec to docs repo.
3) Prepend changelog entry for the release.
"""
from __future__ impor... | 224 | 6,889 |
cognee | cognee/run_migrations.py | .py | """Compatibility shim β migration orchestration lives in
``cognee.modules.migrations.startup``.
This module is imported by ``cognee/__init__.py`` at package-import time, so
it must stay dependency-free: the real implementations are imported lazily
inside each function (the modules tree pulls in ORM models and database... | 24 | 870 |
cognee | cognee/__main__.py | .py | from cognee.cli._cognee import main
if __name__ == "__main__":
main()
| 5 | 75 |
cognee | cognee/__init__.py | .py | """Public Python API for Cognee.
This module exposes the main functions and objects intended for direct use
through ``import cognee``. It groups the stable V1 API, memory-oriented V2 API,
visualization helpers, tracing utilities, migration helpers, and session models
behind a single package-level entrypoint.
Common e... | 112 | 3,677 |
cognee | cognee/get_token.py | .py | import jwt
import os
import datetime
SECRET_KEY = os.getenv("FASTAPI_USERS_JWT_SECRET", "super_secret")
def create_jwt(user_id: str, tenant_id: str, roles: list[str]):
payload = {
"user_id": user_id,
"tenant_id": tenant_id,
"roles": roles,
"exp": datetime.datetime.now(datetime.tim... | 25 | 660 |
cognee | cognee/version.py | .py | import os
from contextlib import suppress
import importlib.metadata
from pathlib import Path
def get_cognee_version() -> str:
"""Returns either the version of installed cognee package or the one
found in nearby pyproject.toml"""
with suppress(FileNotFoundError, StopIteration):
with open(
... | 25 | 874 |
cognee | cognee/base_config.py | .py | import os
import base64
from pathlib import Path
from typing import Optional
from functools import lru_cache
from cognee.root_dir import get_absolute_path, ensure_absolute_path
from cognee.modules.observability.observers import Observer
from pydantic_settings import BaseSettings, SettingsConfigDict
import pydantic
de... | 115 | 5,446 |
cognee | cognee/root_dir.py | .py | from pathlib import Path
from typing import Optional
ROOT_DIR = Path(__file__).resolve().parent
def get_absolute_path(path_from_root: str) -> str:
absolute_path = ROOT_DIR / path_from_root
return str(absolute_path.resolve())
def ensure_absolute_path(path: str) -> str:
"""Ensures a path is absolute.
... | 33 | 793 |
cognee | cognee/context_global_variables.py | .py | import os
import warnings
from contextvars import ContextVar
from typing import Optional
from uuid import UUID
from cognee.base_config import get_base_config
from cognee.exceptions import CogneeValidationError
from cognee.infrastructure.llm.config import LLMConfig
from cognee.infrastructure.databases.vector.embeddings... | 372 | 18,687 |
cognee | cognee/exceptions/exceptions.py | .py | from fastapi import status
from cognee.shared.logging_utils import get_logger
logger = get_logger()
class CogneeApiError(Exception):
"""Base exception class"""
def __init__(
self,
message: str = "Service is unavailable.",
name: str = "Cognee",
status_code=status.HTTP_500_INTE... | 92 | 2,754 |
cognee | cognee/exceptions/__init__.py | .py | """
Custom exceptions for the Cognee API.
This module defines a set of exceptions for handling various application errors,
such as System, Validation, Configuration or TransientErrors
"""
from .exceptions import (
CogneeApiError,
CogneeSystemError,
CogneeValidationError,
CogneeConfigurationError,
... | 15 | 344 |
cognee | cognee/tasks/temporal_graph/enrich_events.py | .py | from typing import List
from cognee.infrastructure.llm.extraction import extract_event_entities
from cognee.modules.engine.models import Event
from cognee.tasks.temporal_graph.models import EventWithEntities, EventEntityList
async def enrich_events(events: List[Event]) -> List[EventWithEntities]:
"""
Enriche... | 35 | 1,109 |
cognee | cognee/tasks/temporal_graph/add_entities_to_event.py | .py | from cognee.modules.engine.models import Event
from cognee.tasks.temporal_graph.models import EventWithEntities
from cognee.modules.engine.models.Entity import Entity
from cognee.modules.engine.models.EntityType import EntityType
from cognee.infrastructure.engine.models.Edge import Edge
from cognee.modules.engine.utils... | 86 | 3,167 |
cognee | cognee/tasks/temporal_graph/extract_events_and_entities.py | .py | import asyncio
from typing import Type, List
from cognee.infrastructure.llm.extraction import extract_event_graph
from cognee.modules.chunking.models import DocumentChunk
from cognee.tasks.temporal_graph.models import EventList
from cognee.modules.engine.utils.generate_event_datapoint import generate_event_datapoint
... | 37 | 1,414 |
cognee | cognee/tasks/temporal_graph/models.py | .py | from typing import Optional, List
from pydantic import BaseModel, Field
class Timestamp(BaseModel):
year: int = Field(
...,
ge=1,
le=9999,
description="Always required. If only a year is known, use it.",
)
month: int = Field(1, ge=1, le=12, description="If unknown, default ... | 55 | 1,390 |
cognee | cognee/tasks/temporal_graph/__init__.py | .py | """
Temporal graph construction and event-based enrichment tasks.
This module provides a pipeline for transforming unstructured document chunks into a structured
temporal knowledge graph. It focuses on identifying Events within text, assigning them precise
timestamps, and extracting the entities involved to create a r... | 8 | 366 |
cognee | cognee/tasks/temporal_graph/extract_knowledge_graph_from_events.py | .py | from typing import List
from cognee.modules.chunking.models import DocumentChunk
from cognee.modules.engine.models import Event
from cognee.tasks.temporal_graph.enrich_events import enrich_events
from cognee.tasks.temporal_graph.add_entities_to_event import add_entities_to_event
from cognee.modules.pipelines.tasks.ta... | 46 | 1,550 |
cognee | cognee/tasks/chunks/create_chunk_associations.py | .py | """
Chunk association task for creating semantic links between document chunks.
This module uses vector similarity search to identify candidate chunk pairs,
then applies LLM-based comparison to determine whether chunks should be
linked with weighted "associated_with" edges in the knowledge graph.
"""
from typing impo... | 231 | 8,721 |
cognee | cognee/tasks/chunks/__init__.py | .py | """
Text chunking and chunk management tasks.
This module provides functionality for splitting text into chunks using
different strategies (word, sentence, paragraph, or row-based), cleaning
up disconnected or obsolete chunks, and creating semantic association
edges between related chunks to support downstream process... | 17 | 672 |
cognee | cognee/tasks/chunks/chunk_by_word.py | .py | import re
from typing import Iterator, Tuple
SENTENCE_ENDINGS = r"[.;!?β¦γοΌοΌ]"
PARAGRAPH_ENDINGS = r"[\n\r]"
def is_real_paragraph_end(last_char: str, current_pos: int, text: str) -> bool:
"""
Determine if the current position represents a valid paragraph end.
The function checks if the last character i... | 91 | 2,467 |
cognee | cognee/tasks/chunks/remove_disconnected_chunks.py | .py | from cognee.infrastructure.databases.graph import get_graph_engine
from cognee.modules.chunking.models.DocumentChunk import DocumentChunk
async def remove_disconnected_chunks(data_chunks: list[DocumentChunk]) -> list[DocumentChunk]:
"""
Removes disconnected or obsolete chunks from the graph database.
Not... | 39 | 1,416 |
cognee | cognee/tasks/chunks/chunk_by_sentence.py | .py | from uuid import uuid4, UUID
from typing import Optional, Iterator, Tuple
from .chunk_by_word import chunk_by_word
from cognee.infrastructure.databases.vector.embeddings import get_embedding_engine
def get_word_size(word: str) -> int:
"""
Calculate the size of a given word in terms of tokens.
If an embed... | 103 | 3,781 |
cognee | cognee/tasks/chunks/chunk_by_paragraph.py | .py | from typing import Any, Dict, Iterator
from uuid import NAMESPACE_OID, uuid5
from .chunk_by_sentence import chunk_by_sentence
def chunk_by_paragraph(
data: str,
max_chunk_size,
batch_paragraphs: bool = True,
) -> Iterator[Dict[str, Any]]:
"""
Chunk the input text by paragraph while enabling exact... | 97 | 3,415 |
cognee | cognee/tasks/chunks/chunk_by_row.py | .py | from typing import Any, Dict, Iterator
from uuid import NAMESPACE_OID, uuid5
from cognee.infrastructure.databases.vector.embeddings import get_embedding_engine
def _get_pair_size(pair_text: str) -> int:
"""
Calculate the size of a given text in terms of tokens.
If an embedding engine's tokenizer is avai... | 105 | 3,604 |
cognee | cognee/tasks/translation/translate_content.py | .py | import asyncio
from typing import List, Optional
from uuid import uuid5
from cognee.modules.chunking.models import DocumentChunk
from cognee.shared.logging_utils import get_logger
from .config import get_translation_config, TranslationProviderType
from .detect_language import detect_language_async, LanguageDetectionR... | 283 | 10,512 |
cognee | cognee/tasks/translation/exceptions.py | .py | class TranslationError(Exception):
"""Base exception for translation errors."""
def __init__(self, message: str, original_error: Exception = None):
self.message = message
self.original_error = original_error
super().__init__(self.message)
if original_error:
self.__ca... | 63 | 1,912 |
cognee | cognee/tasks/translation/models.py | .py | from datetime import datetime, timezone
from typing import Optional
from uuid import UUID
from cognee.infrastructure.engine import DataPoint
from cognee.modules.chunking.models import DocumentChunk
class TranslatedContent(DataPoint):
"""
Represents translated content with quality metrics.
This class sto... | 73 | 2,638 |
cognee | cognee/tasks/translation/__init__.py | .py | """
Translation task for Cognee.
This module provides multilingual content translation capabilities,
allowing automatic detection and translation of non-English content
to a target language while preserving original text and metadata.
Main Components:
- translate_content: Main task function for translating document c... | 97 | 2,742 |
cognee | cognee/tasks/translation/config.py | .py | from functools import lru_cache
from typing import Literal, Optional
from pydantic import AliasChoices, Field
from pydantic_settings import BaseSettings, SettingsConfigDict
TranslationProviderType = Literal["llm", "google", "azure"]
class TranslationConfig(BaseSettings):
"""
Configuration settings for the ... | 111 | 4,052 |
cognee | cognee/tasks/translation/detect_language.py | .py | from dataclasses import dataclass
from typing import Optional
from cognee.shared.logging_utils import get_logger
from .config import get_translation_config
from .exceptions import LanguageDetectionError
logger = get_logger(__name__)
# ISO 639-1 language code to name mapping
LANGUAGE_NAMES = {
"af": "Afrikaans"... | 191 | 5,400 |
cognee | cognee/tasks/translation/providers/llm_provider.py | .py | import asyncio
from typing import Optional
from pydantic import BaseModel
from cognee.infrastructure.llm.LLMGateway import LLMGateway
from cognee.infrastructure.llm.config import get_llm_config
from cognee.infrastructure.llm.prompts import read_query_prompt
from cognee.shared.logging_utils import get_logger
from .ba... | 144 | 5,184 |
cognee | cognee/tasks/translation/providers/azure_provider.py | .py | from typing import Optional
import aiohttp
from cognee.shared.logging_utils import get_logger
from .base import TranslationProvider, TranslationResult
from ..config import get_translation_config
from ..exceptions import TranslationProviderError
logger = get_logger(__name__)
class AzureTranslationProvider(Translat... | 193 | 6,757 |
cognee | cognee/tasks/translation/providers/__init__.py | .py | from .base import TranslationProvider, TranslationResult
from .llm_provider import LLMTranslationProvider
from .google_provider import GoogleTranslationProvider
from .azure_provider import AzureTranslationProvider
__all__ = [
"TranslationProvider",
"TranslationResult",
"LLMTranslationProvider",
"Google... | 45 | 1,343 |
cognee | cognee/tasks/translation/providers/google_provider.py | .py | import asyncio
from typing import Optional
from cognee.shared.logging_utils import get_logger
from .base import TranslationProvider, TranslationResult
from ..config import get_translation_config
logger = get_logger(__name__)
class GoogleTranslationProvider(TranslationProvider):
"""
Translation provider usi... | 159 | 5,231 |
cognee | cognee/tasks/translation/providers/base.py | .py | """
Base classes for translation providers.
This module defines the abstract interface that all translation providers must implement.
Providers handle the actual translation of text using external services like OpenAI,
Google Translate, or Azure Translator.
"""
from abc import ABC, abstractmethod
from dataclasses imp... | 86 | 2,410 |
cognee | cognee/tasks/provenance/record_provenance.py | .py | """Opt-in cognify task writing the audit-grade provenance ledger.
Pipeline seam: spliced in by ``get_default_tasks`` right after
``add_data_points`` (node ids are persisted and stable) and before the
contradiction-detection spread, when the ``provenance_tracking`` CognifyConfig
flag is on (env ``PROVENANCE_TRACKING``,... | 276 | 12,188 |
cognee | cognee/tasks/provenance/__init__.py | .py | from .record_provenance import record_provenance
__all__ = ["record_provenance"]
| 4 | 82 |
cognee | cognee/tasks/code_graph/models.py | .py | from typing import Any, Optional
from pydantic import Field
from cognee.infrastructure.engine.models.DataPoint import DataPoint
class CodeRepository(DataPoint):
"""The repository an enola snapshot was extracted from.
last_snapshot_id records the enola snapshot identity of the last fully
loaded (and swe... | 90 | 2,728 |
cognee | cognee/tasks/code_graph/resolve_repo.py | .py | """Resolve repository specs (local paths or remote git URLs) to local clones.
Used by ``remember(..., content_type="code")`` so callers can pass a GitHub
URL (or a list of them) and get the enola code-graph pipeline run on a local
shallow clone. Clones live under ``~/.cognee/repos`` and are reused across
calls; an exi... | 125 | 4,466 |
cognee | cognee/tasks/code_graph/__init__.py | .py | """Code graph extraction tasks backed by enola.
These tasks build an architectural knowledge graph of a code repository using
enola (https://github.com/enola-labs/enola) by Enola Labs, licensed under
Apache-2.0. Cognee invokes the external enola binary (`enola --generate`) and
parses its documented output (`.enola/fac... | 42 | 1,055 |
cognee | cognee/tasks/code_graph/extract_code_graph.py | .py | """Map enola snapshot facts to cognee DataPoints and typed graph edges."""
import hashlib
import json
from datetime import datetime, timezone
from pathlib import Path
import posixpath
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
from uuid import NAMESPACE_OID, UUID, uuid5
from pydantic im... | 927 | 37,273 |
cognee | cognee/tasks/code_graph/code_files.py | .py | """The cognify CODE-route adapter for code files.
Recognition happens at add time through the loader system: the code loader
(infrastructure/loaders/core/code_loader.py) claims supported code files, and
ingest_data tags them with ``system_metadata = {"source": "code"}``.
Classification maps that tag to CodeFileDocumen... | 158 | 6,925 |
cognee | cognee/tasks/code_graph/code_repo.py | .py | """Code-project detection and repo-level ingestion for directory adds.
When ``add()`` receives a directory that IS a code project (it carries a
project marker such as pyproject.toml or go.mod), flattening it file-by-file
is the wrong granularity: every source file would run its own enola pass in
its own one-file "repo... | 325 | 12,593 |
cognee | cognee/tasks/code_graph/enola.py | .py | """Run the enola binary and parse the snapshot it produces.
enola (https://github.com/enola-labs/enola) is an external Go CLI that
deterministically extracts an architectural graph from a codebase.
`enola --generate` writes a `.enola/` directory containing `facts.jsonl`
(one graph node per line) and `receipt.json` (pr... | 298 | 10,394 |
cognee | cognee/tasks/code_graph/install_enola.py | .py | """Download and install a pinned enola release on first use.
The enola binary (https://github.com/enola-labs/enola, Apache-2.0 by Enola
Labs) is a compiled Go CLI that cannot be installed from PyPI. When it is not
already available, cognee downloads the pinned release for the current
platform straight from the author'... | 191 | 7,700 |
cognee | cognee/tasks/storage/index_data_points.py | .py | import asyncio
from cognee.shared.logging_utils import get_logger
from cognee.infrastructure.databases.vector import get_vector_engine_async
from cognee.infrastructure.databases.vector.embeddings.config import get_embedding_context_config
from cognee.infrastructure.engine import DataPoint
logger = get_logger("index_d... | 150 | 5,643 |
cognee | cognee/tasks/storage/__init__.py | .py | """
Graph persistence and indexing tasks.
This module provides tasks for adding structured DataPoints to the graph database,
deduplicating extracted nodes and edges, and managing vector-based indexing for both
nodes and relationship types.
"""
from .add_data_points import add_data_points
from .index_data_points impor... | 12 | 389 |
cognee | cognee/tasks/storage/index_graph_edges.py | .py | from collections import Counter
from typing import Optional, Dict, Any, List, Tuple, Union
from cognee.shared.logging_utils import get_logger
from cognee.infrastructure.databases.graph import get_graph_engine
from cognee.modules.graph.utils.prepare_edges_for_storage import get_edge_retrieval_text
from cognee.modules.g... | 93 | 3,153 |
cognee | cognee/tasks/storage/close_node.py | .py | """Bi-temporal helper: close a graph node by stamping its ``valid_to`` timestamp.
When a fact changes (e.g. "Alice works at X" -> "Alice works at Y"), call
``close_node(old_node_id)`` to mark the old node as no longer valid β instead of
deleting it β and then write the replacement. Consumers filter stale facts with
``... | 58 | 2,349 |
cognee | cognee/tasks/storage/add_data_points.py | .py | import asyncio
from typing import TYPE_CHECKING, Dict, List, Optional
from cognee.modules.pipelines.tasks.task import task_summary
from cognee.infrastructure.engine import DataPoint
from cognee.infrastructure.databases.unified import get_unified_engine
from cognee.infrastructure.databases.unified.capabilities import E... | 377 | 14,585 |
cognee | cognee/tasks/storage/exceptions/exceptions.py | .py | from cognee.exceptions import (
CogneeValidationError,
)
from fastapi import status
class InvalidDataPointsInAddDataPointsError(CogneeValidationError):
def __init__(self, detail: str):
super().__init__(
message=f"Invalid data_points: {detail}",
name="InvalidDataPointsInAddDataP... | 14 | 396 |
cognee | cognee/tasks/storage/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 (
InvalidDataPointsInAddDataPointsError,
)
| 10 | 192 |
cognee | cognee/tasks/documents/__init__.py | .py | """
Document classification and chunking tasks.
This module provides tasks for classifying raw data into document objects
based on file extensions and extracting structured chunks from documents
for downstream processing and storage.
"""
from .classify_documents import classify_documents
from .extract_chunks_from_doc... | 11 | 364 |
cognee | cognee/tasks/documents/extract_chunks_from_documents.py | .py | from uuid import UUID
from sqlalchemy import select
from typing import AsyncGenerator
from cognee.modules.pipelines.tasks.task import task_summary
from cognee.shared.logging_utils import get_logger
from cognee.modules.data.processing.document_types.Document import Document
from cognee.modules.data.models import Data
f... | 61 | 2,421 |
cognee | cognee/tasks/documents/classify_documents.py | .py | from cognee.modules.data.models import Data
import json
from cognee.modules.pipelines.tasks.task import task_summary
from cognee.modules.data.processing.document_types import (
Document,
PdfDocument,
AudioDocument,
ImageDocument,
TextDocument,
UnstructuredDocument,
CsvDocument,
DltSource... | 182 | 6,395 |
cognee | cognee/tasks/documents/exceptions/exceptions.py | .py | from cognee.exceptions import (
CogneeValidationError,
CogneeConfigurationError,
)
from fastapi import status
class WrongDataDocumentInputError(CogneeValidationError):
"""Raised when a wrong data document is provided."""
def __init__(
self,
field: str,
name: str = "WrongDataDo... | 37 | 1,091 |
cognee | cognee/tasks/documents/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 (
WrongDataDocumentInputError,
InvalidChunkSizeError,
InvalidChunkerError,
)
| 12 | 234 |
cognee | cognee/tasks/codingagents/__init__.py | .py | """
Coding agent tasks.
This module leverages language models to extract coding rules and best practices
from developer text, linking them to structured data sources and persisting
these relationships within graph systems for downstream use.
"""
| 8 | 247 |
cognee | cognee/tasks/codingagents/coding_rule_associations.py | .py | from uuid import NAMESPACE_OID, uuid5
from cognee.infrastructure.databases.graph import get_graph_engine
from cognee.infrastructure.databases.provenance import graph_provenance_write_kwargs
from cognee.infrastructure.databases.vector import get_vector_engine_async
from cognee.low_level import DataPoint
from cognee.in... | 152 | 5,466 |
cognee | cognee/tasks/cleanup/cleanup_unused_data.py | .py | """
Task for automatically deleting unused data from the memify pipeline.
This task identifies and removes entire documents that haven't
been accessed by retrievers for a specified period, helping maintain system
efficiency and storage optimization through whole-document removal.
"""
import json
from datetime import ... | 171 | 5,932 |
cognee | cognee/tasks/web_scraper/types.py | .py | from typing import TypeAlias
UrlsToHtmls: TypeAlias = dict[str, str]
| 5 | 71 |
cognee | cognee/tasks/web_scraper/default_url_crawler.py | .py | import asyncio
from dataclasses import dataclass, field
from functools import lru_cache
import time
from typing import Any, Union, List, Dict, Optional
from urllib.parse import urlparse
import httpx
import os
from cognee.shared.logging_utils import get_logger
from cognee.tasks.web_scraper.types import UrlsToHtmls
from... | 462 | 17,314 |
cognee | cognee/tasks/web_scraper/utils.py | .py | """Utilities for fetching web content using BeautifulSoup, Tavily, or Keenable.
This module provides functions to fetch and extract content from web pages, supporting
BeautifulSoup for custom extraction rules and Tavily or Keenable for API-based scraping.
"""
import asyncio
import os
from typing import List, Optional... | 245 | 9,580 |
cognee | cognee/tasks/web_scraper/models.py | .py | from cognee.infrastructure.engine import DataPoint
from typing import Optional, Dict, Any, List
from datetime import datetime
class WebPage(DataPoint):
"""Represents a scraped web page with metadata"""
name: Optional[str]
content: str
content_hash: str
scraped_at: datetime
last_modified: Opti... | 47 | 1,300 |
cognee | cognee/tasks/web_scraper/__init__.py | .py | """Web scraping module for cognee.
This module provides tools for scraping web content, managing scraping jobs, and storing
data in a graph database. It includes classes and functions for crawling web pages using
BeautifulSoup, Tavily, or Keenable, defining data models, and handling scraping
configurations.
"""
from ... | 36 | 1,148 |
cognee | cognee/tasks/web_scraper/ssrf_protection.py | .py | """Server-Side Request Forgery (SSRF) protection for outbound URL fetching.
Cognee fetches user-supplied ``http(s)`` URLs server-side during ingestion
(``add()`` -> ``save_data_item_to_storage``) and web scraping. Without
validation, a caller can point Cognee at internal-only addresses -- loopback,
private ranges, lin... | 140 | 5,002 |
cognee | cognee/tasks/web_scraper/web_scraper_task.py | .py | """Web scraping tasks for storing scraped data in a graph database.
This module provides functions to scrape web content, create or update WebPage, WebSite,
and ScrapingJob data points, and store them in a Ladybug graph database. It supports
scheduled scraping tasks and ensures that node updates preserve existing grap... | 428 | 16,132 |
cognee | cognee/tasks/web_scraper/config.py | .py | from pydantic import BaseModel, Field
from typing import Dict, Optional, Literal
import os
class TavilyConfig(BaseModel):
api_key: Optional[str] = os.getenv("TAVILY_API_KEY")
extract_depth: Literal["basic", "advanced"] = "basic"
proxies: Optional[Dict[str, str]] = None
timeout: Optional[int] = Field(d... | 36 | 1,316 |
cognee | cognee/tasks/completion/exceptions/exceptions.py | .py | from cognee.exceptions import CogneeValidationError
from fastapi import status
class NoRelevantDataError(CogneeValidationError):
"""
Represents an error when no relevant data is found during a search. This class is a
subclass of CogneeValidationError.
Public methods:
- __init__
Instance var... | 28 | 619 |
cognee | cognee/tasks/completion/exceptions/__init__.py | .py | """
Custom exceptions for the Cognee API.
This module defines a set of exceptions for handling various compute errors
"""
from .exceptions import (
NoRelevantDataError,
)
| 10 | 177 |
cognee | cognee/tasks/memify/consolidate_entities.py | .py | """Detect and merge semantically near-duplicate ``Entity`` nodes.
These two tasks back the ``consolidate_entities`` memify pipeline:
* :func:`detect_entity_duplicates` (extraction) loads every ``Entity`` node,
embeds its name, and clusters near-duplicates by cosine similarity and/or
normalized-name equality.
* :f... | 563 | 22,711 |
cognee | cognee/tasks/memify/extract_agent_trace_feedbacks.py | .py | import json
from typing import Optional
from cognee.context_global_variables import session_user
from cognee.exceptions import CogneeSystemError
from cognee.infrastructure.session.get_session_manager import get_session_manager
from cognee.modules.users.models import User
from cognee.shared.logging_utils import get_log... | 135 | 5,226 |
cognee | cognee/tasks/memify/extract_feedback_qas.py | .py | from typing import List, Optional
from cognee.context_global_variables import session_user
from cognee.exceptions import CogneeSystemError, CogneeValidationError
from cognee.infrastructure.databases.cache import SessionQAEntry
from cognee.infrastructure.session.get_session_manager import get_session_manager
from cogne... | 95 | 3,218 |
cognee | cognee/tasks/memify/__init__.py | .py | """
Memory and subgraph extraction tasks.
This module provides tasks for extracting subgraphs, document chunks, and
user session data, as well as initiating session cognification workflows,
to support memory enrichment and downstream knowledge graph processing.
"""
from .extract_subgraph import extract_subgraph
from ... | 18 | 820 |
cognee | cognee/tasks/memify/get_triplet_datapoints.py | .py | from typing import AsyncGenerator, Dict, Any, List, Optional
from cognee.infrastructure.databases.graph.get_graph_engine import get_graph_engine
from cognee.modules.engine.utils import generate_node_id
from cognee.shared.logging_utils import get_logger
from cognee.modules.graph.utils.convert_node_to_data_point import g... | 290 | 10,713 |
cognee | cognee/tasks/memify/apply_feedback_weights.py | .py | from collections.abc import Awaitable, Callable, Iterable
from typing import Any, TypedDict
from cognee.context_global_variables import session_user
from cognee.exceptions import CogneeSystemError, CogneeValidationError
from cognee.infrastructure.databases.graph.get_graph_engine import get_graph_engine
from cognee.inf... | 247 | 7,717 |
cognee | cognee/tasks/memify/cross_connect_entities.py | .py | from collections import Counter, defaultdict
from itertools import combinations
from typing import Any
from pydantic import BaseModel, Field
from cognee.infrastructure.databases.graph import get_graph_engine
from cognee.infrastructure.databases.vector import get_vector_engine
from cognee.infrastructure.llm import LLM... | 239 | 8,919 |
cognee | cognee/tasks/memify/extract_subgraph_chunks.py | .py | from cognee.modules.graph.cognee_graph.CogneeGraph import CogneeGraph
async def extract_subgraph_chunks(subgraphs: list[CogneeGraph]):
"""
Get all Document Chunks from subgraphs and forward to next task in pipeline
"""
for subgraph in subgraphs:
for node in subgraph.nodes.values():
... | 12 | 414 |
cognee | cognee/tasks/memify/extract_user_sessions.py | .py | from typing import Optional, List
from cognee.context_global_variables import session_user
from cognee.exceptions import CogneeSystemError
from cognee.infrastructure.session.get_session_manager import get_session_manager
from cognee.infrastructure.session.session_persist_watermark import (
SessionPersistWindow,
... | 124 | 5,024 |
cognee | cognee/tasks/memify/extract_subgraph.py | .py | from cognee.modules.graph.cognee_graph.CogneeGraph import CogneeGraph
async def extract_subgraph(subgraphs: list[CogneeGraph]):
for subgraph in subgraphs:
for edge in subgraph.edges:
yield edge
| 8 | 220 |
cognee | cognee/tasks/memify/cognify_agent_trace_feedback.py | .py | from typing import Optional
from uuid import UUID
import cognee
from cognee.exceptions import CogneeSystemError, CogneeValidationError
from cognee.modules.users.models import User
from cognee.shared.logging_utils import get_logger
logger = get_logger("cognify_agent_trace_feedback")
async def cognify_agent_trace_fe... | 63 | 2,265 |
cognee | cognee/tasks/memify/cognify_session.py | .py | from typing import Optional, Union
from uuid import UUID
import cognee
from cognee.exceptions import CogneeValidationError, CogneeSystemError
from cognee.infrastructure.session.get_session_manager import get_session_manager
from cognee.infrastructure.session.session_persist_watermark import (
SessionPersistWindow... | 87 | 3,359 |
cognee | cognee/tasks/memify/apply_frequency_weights.py | .py | from collections.abc import Awaitable, Callable, Iterable
from typing import Any, TypedDict
from cognee.context_global_variables import session_user
from cognee.exceptions import CogneeSystemError, CogneeValidationError
from cognee.infrastructure.databases.graph.get_graph_engine import get_graph_engine
from cognee.inf... | 216 | 6,570 |
cognee | cognee/tasks/memify/global_context_index/ids.py | .py | from __future__ import annotations
from uuid import NAMESPACE_OID, UUID, uuid5
def create_bucket_id(dataset_id: str, level: int, child_ids: list[str]) -> UUID:
child_key = ",".join(sorted(child_ids))
return uuid5(NAMESPACE_OID, f"GlobalContextSummary:{dataset_id}:{level}:{child_key}")
def create_root_summa... | 13 | 427 |
cognee | cognee/tasks/memify/global_context_index/models.py | .py | from __future__ import annotations
from dataclasses import dataclass, field
from pydantic import BaseModel
class GlobalContextSummaryContent(BaseModel):
summary: str
@dataclass
class SummaryNode:
id: str
text: str
type: str
level: int | None = None
is_root: bool = False
dataset_id: str... | 75 | 2,008 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.