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/data/exceptions/exceptions.py
.py
from fastapi import status from cognee.exceptions import ( CogneeValidationError, ) class KeywordExtractionError(CogneeValidationError): """ Raised when a provided value is syntactically valid but semantically unacceptable for the given operation. Example: - Passing an empty string to a ...
24
644
cognee
cognee/infrastructure/data/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 KeywordExtractionError
8
168
cognee
cognee/infrastructure/data/chunking/HaystackChunkEngine.py
.py
from collections.abc import Iterable from cognee.shared.data_models import ChunkStrategy class HaystackChunkEngine: """ Manage chunking of source data using specified strategies and parameters. The class provides functionality to process source data into manageable chunks according to defined strate...
27
903
cognee
cognee/infrastructure/data/chunking/LangchainChunkingEngine.py
.py
from __future__ import annotations import re from collections.abc import Iterable from typing import Any from cognee.infrastructure.data.chunking.DefaultChunkEngine import DefaultChunkEngine from cognee.shared.data_models import ChunkStrategy class LangchainChunkEngine: """ Handles chunking of data using sp...
159
5,594
cognee
cognee/infrastructure/data/chunking/get_chunking_engine.py
.py
from typing import Any from cognee.infrastructure.data.chunking.DefaultChunkEngine import DefaultChunkEngine from cognee.infrastructure.data.chunking.HaystackChunkEngine import HaystackChunkEngine from cognee.infrastructure.data.chunking.LangchainChunkingEngine import LangchainChunkEngine from .config import get_chun...
22
739
cognee
cognee/infrastructure/data/chunking/DefaultChunkEngine.py
.py
"""Chunking strategies for splitting text into smaller parts.""" from __future__ import annotations import re from collections.abc import Iterable from typing import Any from cognee.shared.data_models import ChunkStrategy # /Users/vasa/Projects/cognee/cognee/infrastructure/data/chunking/DefaultChunkEngine.py clas...
219
7,892
cognee
cognee/infrastructure/data/chunking/create_chunking_engine.py
.py
from typing import Any from cognee.infrastructure.data.chunking.DefaultChunkEngine import DefaultChunkEngine from cognee.infrastructure.data.chunking.HaystackChunkEngine import HaystackChunkEngine from cognee.infrastructure.data.chunking.LangchainChunkingEngine import LangchainChunkEngine from cognee.shared.data_model...
71
2,821
cognee
cognee/infrastructure/data/chunking/config.py
.py
from functools import lru_cache from typing import Any from pydantic_settings import BaseSettings, SettingsConfigDict from cognee.infrastructure.data.chunking.DefaultChunkEngine import DefaultChunkEngine from cognee.shared.data_models import ChunkEngine, ChunkStrategy class ChunkConfig(BaseSettings): """ Ma...
56
1,725
cognee
cognee/infrastructure/locks/dataset_lock.py
.py
"""Per-dataset lock primitives β€” in-process asyncio registry. Serializes operations that mutate the same dataset β€” pipeline runs (``add``/``cognify``/``memify``) and delete operations β€” while letting different datasets proceed in parallel. Both acquire the lock from the same registry, so a delete waits for an in-fligh...
67
2,480
cognee
cognee/infrastructure/locks/__init__.py
.py
from .dataset_lock import dataset_lock, get_dataset_lock, held_datasets from .session_lock import ( release_improve_lock, session_lock, session_turn_lock, try_acquire_improve_lock, ) __all__ = [ "dataset_lock", "get_dataset_lock", "held_datasets", "release_improve_lock", "session_lo...
18
384
cognee
cognee/infrastructure/locks/session_lock.py
.py
"""Per-session lock primitives β€” in-process asyncio registry. Three primitives: * ``session_lock(session_id, op)`` β€” async context manager that serializes concurrent tasks on the same ``(session_id, op)`` key. Used for short read-modify-write flows (``update_qa``, ``add_feedback``, ``delete_qa``). * ``session_...
138
4,771
cognee
cognee/eval_framework/run_beam_eval.py
.py
"""Run BEAM benchmark evaluation on a single conversation. Usage: uv run python cognee/eval_framework/run_beam_eval.py """ import asyncio from cognee.shared.logging_utils import get_logger from cognee.eval_framework.eval_config import EvalConfig from cognee.eval_framework.corpus_builder.run_corpus_builder import...
83
2,704
cognee
cognee/eval_framework/modal_eval_dashboard.py
.py
import os import json import shlex import subprocess import modal import streamlit as st # ---------------------------------------------------------------------------- # Volume and Image Setup # ---------------------------------------------------------------------------- metrics_volume = modal.Volume.from_name("evalu...
112
3,585
cognee
cognee/eval_framework/runner.py
.py
"""One-command runner for the cognee evaluation harness. This module puts a thin, testable surface in front of the existing eval pipeline (corpus -> answers -> evaluation -> dashboard). It exposes: - ``run_eval(config) -> EvalResult``: a programmatic entry point that runs the full pipeline for a single deterministi...
325
11,544
cognee
cognee/eval_framework/__main__.py
.py
"""Module entry point: ``python -m cognee.eval_framework [options]``. Thin wrapper around :func:`cognee.eval_framework.runner.run_eval` that shares its argument surface with the ``cognee eval`` CLI command. """ import argparse import asyncio from cognee.eval_framework.runner import ( add_eval_arguments, conf...
36
865
cognee
cognee/eval_framework/eval_config.py
.py
from functools import lru_cache from pydantic_settings import BaseSettings, SettingsConfigDict from typing import List, Optional class EvalConfig(BaseSettings): # Corpus builder params building_corpus_from_scratch: bool = True number_of_samples_in_corpus: int = 1 benchmark: str = "Dummy" # Options: '...
92
3,691
cognee
cognee/eval_framework/run_eval.py
.py
"""Legacy script entry point for the eval harness. Kept for backward compatibility. New code should prefer the one-command runner: from cognee.eval_framework.runner import run_eval result = await run_eval(EvalConfig()) or the CLI: ``cognee eval ...`` / ``python -m cognee.eval_framework``. """ import asynci...
34
852
cognee
cognee/eval_framework/modal_run_eval.py
.py
import modal import os import asyncio import datetime import json from cognee.shared.logging_utils import get_logger from cognee.eval_framework.eval_config import EvalConfig from cognee.eval_framework.corpus_builder.run_corpus_builder import run_corpus_builder from cognee.eval_framework.answer_generation.run_question_a...
132
4,458
cognee
cognee/eval_framework/metrics_dashboard.py
.py
import html import json import plotly.graph_objects as go from typing import Dict, List, Tuple from collections import defaultdict metrics_fields = { "contextual_relevancy": ["question", "retrieval_context"], "context_coverage": ["question", "retrieval_context", "golden_context"], } default_metrics_fields = ["...
173
5,914
cognee
cognee/eval_framework/benchmark_adapters/base_benchmark_adapter.py
.py
from abc import ABC, abstractmethod from typing import List, Optional, Any, Union, Tuple import os import json from cognee.shared.logging_utils import get_logger logger = get_logger() class BaseBenchmarkAdapter(ABC): async def prepare_corpus(self) -> None: return None def _filter_instances( ...
59
2,306
cognee
cognee/eval_framework/benchmark_adapters/hotpot_qa_adapter.py
.py
import os import json import random from typing import Optional, Any, List, Union, Tuple from cognee.eval_framework.benchmark_adapters.base_benchmark_adapter import BaseBenchmarkAdapter class HotpotQAAdapter(BaseBenchmarkAdapter): dataset_info = { "filename": "hotpot_benchmark.json", "url": "http:...
107
4,331
cognee
cognee/eval_framework/benchmark_adapters/dummy_adapter.py
.py
from typing import Optional, Any, List, Union, Tuple from cognee.eval_framework.benchmark_adapters.base_benchmark_adapter import BaseBenchmarkAdapter class DummyAdapter(BaseBenchmarkAdapter): def load_corpus( self, limit: Optional[int] = None, seed: int = 42, load_golden_context: ...
33
1,167
cognee
cognee/eval_framework/benchmark_adapters/logistics_system_adapter.py
.py
from __future__ import annotations import json import random from pathlib import Path from typing import Any, List, Optional, Tuple, Union from cognee.eval_framework.benchmark_adapters.base_benchmark_adapter import ( BaseBenchmarkAdapter, ) from cognee.eval_framework.benchmark_adapters.logistics_system_utils.corp...
229
8,659
cognee
cognee/eval_framework/benchmark_adapters/benchmark_adapters.py
.py
from enum import Enum from typing import Type from cognee.eval_framework.benchmark_adapters.hotpot_qa_adapter import HotpotQAAdapter from cognee.eval_framework.benchmark_adapters.logistics_system_adapter import ( LogisticsSystemAdapter, ) from cognee.eval_framework.benchmark_adapters.musique_adapter import Musique...
30
1,153
cognee
cognee/eval_framework/benchmark_adapters/twowikimultihop_adapter.py
.py
from typing import Any from cognee.eval_framework.benchmark_adapters.hotpot_qa_adapter import HotpotQAAdapter class TwoWikiMultihopAdapter(HotpotQAAdapter): dataset_info = { "filename": "2wikimultihop_dev.json", "url": "https://huggingface.co/datasets/voidful/2WikiMultihopQA/resolve/main/dev.json"...
25
913
cognee
cognee/eval_framework/benchmark_adapters/beam_adapter.py
.py
"""BEAM benchmark adapter β€” loads synthetic long-context conversations. Dataset: https://huggingface.co/datasets/Mohammadta/BEAM Paper: "Beyond a Million Tokens: Benchmarking Long-Term Memory in LLMs" Each conversation contains multi-session batches with 20 probing questions across 10 skill categories (information_ex...
258
9,198
cognee
cognee/eval_framework/benchmark_adapters/musique_adapter.py
.py
import os import json import random from typing import Optional, Any, List, Union, Tuple import zipfile from cognee.eval_framework.benchmark_adapters.base_benchmark_adapter import BaseBenchmarkAdapter class MusiqueQAAdapter(BaseBenchmarkAdapter): """Adapter for the Musique QA dataset with local file loading and ...
142
5,613
cognee
cognee/eval_framework/benchmark_adapters/logistics_system_utils/ontology.py
.py
from __future__ import annotations import random import json from pathlib import Path from cognee.eval_framework.benchmark_adapters.logistics_system_utils.entities.package import Package from cognee.eval_framework.benchmark_adapters.logistics_system_utils.entities.retailer import ( retailer_possible_values, ) from...
228
7,874
cognee
cognee/eval_framework/benchmark_adapters/logistics_system_utils/rule_engine.py
.py
from __future__ import annotations from math import inf from typing import Any from cognee.eval_framework.benchmark_adapters.logistics_system_utils.entities.delivery_models import ( DeliveryPlan, RejectedOption, TransportEvaluation, ) from cognee.eval_framework.benchmark_adapters.logistics_system_utils.en...
730
28,317
cognee
cognee/eval_framework/benchmark_adapters/logistics_system_utils/entities/transportation.py
.py
from __future__ import annotations from dataclasses import dataclass from cognee.eval_framework.benchmark_adapters.logistics_system_utils.entities.enums import ( Region, ShippingRange, TransportMode, ) transport_possible_values = { "region": [region.label for region in Region], "temperature_cont...
44
1,319
cognee
cognee/eval_framework/benchmark_adapters/logistics_system_utils/entities/user.py
.py
from __future__ import annotations from dataclasses import dataclass from cognee.eval_framework.benchmark_adapters.logistics_system_utils.entities.enums import ( Region, ShippingRange, UserTier, ) user_possible_values = { "weekend_delivery_eligible": [True, False], "user_tier": [tier.label for t...
47
1,215
cognee
cognee/eval_framework/benchmark_adapters/logistics_system_utils/entities/enums.py
.py
from enum import Enum class UserTier(Enum): STANDARD = ("standard", 0, 1) BUSINESS = ("business", 1, 2) ENTERPRISE = ("enterprise", 2, 3) @property def label(self) -> str: return self.value[0] @property def priority_bonus(self) -> int: return self.value[1] @property ...
238
6,247
cognee
cognee/eval_framework/benchmark_adapters/logistics_system_utils/entities/package.py
.py
from __future__ import annotations from dataclasses import dataclass from cognee.eval_framework.benchmark_adapters.logistics_system_utils.entities.enums import ( DeliveryPriority, PackageCategory, PackageState, ShippingRange, ) package_possible_values = { "weight_kg": [1.0, 5.0, 25.0, 150.0, 900...
134
4,340
cognee
cognee/eval_framework/benchmark_adapters/logistics_system_utils/entities/delivery_models.py
.py
from __future__ import annotations import json from dataclasses import dataclass, field from cognee.eval_framework.benchmark_adapters.logistics_system_utils.entities.enums import ( TransportMode, ) from cognee.eval_framework.benchmark_adapters.logistics_system_utils.entities.package import Package from cognee.eva...
165
6,337
cognee
cognee/eval_framework/benchmark_adapters/logistics_system_utils/entities/retailer.py
.py
from __future__ import annotations from dataclasses import dataclass from cognee.eval_framework.benchmark_adapters.logistics_system_utils.entities.enums import ( Region, ShippingRange, ) retailer_possible_values = { "region": [region.label for region in Region], "shipping_range": [shipping_range.lab...
49
1,285
cognee
cognee/eval_framework/benchmark_adapters/logistics_system_utils/entities/post_office.py
.py
from __future__ import annotations from dataclasses import dataclass from cognee.eval_framework.benchmark_adapters.logistics_system_utils.entities.enums import ( PostOfficeType, Region, ShippingRange, ) post_office_possible_values = { "office_type": [office_type.label for office_type in PostOfficeTy...
51
1,465
cognee
cognee/eval_framework/benchmark_adapters/logistics_system_utils/utils/utils.py
.py
from __future__ import annotations import json import re from pathlib import Path from cognee.eval_framework.benchmark_adapters.logistics_system_utils.entities.package import Package from cognee.eval_framework.benchmark_adapters.logistics_system_utils.entities.post_office import ( PostOffice, ) from cognee.eval_f...
352
14,265
cognee
cognee/eval_framework/benchmark_adapters/logistics_system_utils/utils/world_creation_utils.py
.py
import random from cognee.eval_framework.benchmark_adapters.logistics_system_utils.entities.enums import ( DeliveryPriority, PackageCategory, PackageState, PostOfficeType, Region, ShippingRange, TransportMode, ) from cognee.eval_framework.benchmark_adapters.logistics_system_utils.entities.p...
799
27,411
cognee
cognee/eval_framework/benchmark_adapters/logistics_system_utils/corpus_generator/narrativize_corpus.py
.py
from __future__ import annotations import asyncio import os from pathlib import Path from pydantic import BaseModel from cognee.eval_framework.benchmark_adapters.logistics_system_utils.utils.utils import ( _entity_entries, _format_packages, _safe_filename, load_world, ) from cognee.eval_framework.ben...
240
9,276
cognee
cognee/eval_framework/reporting/io.py
.py
import json from pathlib import Path from typing import Any def write_json(path: str, payload: Any) -> None: Path(path).parent.mkdir(parents=True, exist_ok=True) with open(path, "w", encoding="utf-8") as handle: json.dump(payload, handle, ensure_ascii=False, indent=2) def read_json(path: str) -> Any...
15
409
cognee
cognee/eval_framework/analysis/dashboard_generator.py
.py
import html import json import plotly.graph_objects as go from typing import Dict, List, Tuple from collections import defaultdict def create_distribution_plots(metrics_data: Dict[str, List[float]]) -> List[str]: """Create distribution histogram plots for each metric.""" figures = [] for metric, scores in...
175
5,903
cognee
cognee/eval_framework/analysis/metrics_calculator.py
.py
import json from collections import defaultdict import numpy as np from typing import Dict, List, Tuple def bootstrap_ci(scores, num_samples=10000, confidence_level=0.95): """Calculate bootstrap confidence intervals for a list of scores.""" means = [] n = len(scores) for _ in range(num_samples): ...
95
3,392
cognee
cognee/eval_framework/sweeps/retriever_sweep_runner.py
.py
"""Generic multi-strategy answer + scoring sweep.""" from __future__ import annotations import asyncio import re from copy import deepcopy from dataclasses import dataclass, field from pathlib import Path from typing import Any, Awaitable, Callable, Optional from cognee.eval_framework.answer_generation.question_type...
381
12,451
cognee
cognee/eval_framework/beam/session_io.py
.py
"""Scale-agnostic ingestion-ready BEAM session-JSON contract. One implementation of the read/parse/write primitives that both the local and Modal ingestion paths need for BEAM's JSON-list session files, previously duplicated (with a ``_``-prefixed naming convention on the Modal side) between ``beam_ingest_conversation...
78
3,000
cognee
cognee/eval_framework/beam/local_ingest.py
.py
"""Sequentially ingest BEAM JSON-list sessions with parallel session distillation. Given one conversation folder created by the preprocessing stage, this script ingests each session/batch file one at a time: 1. write a limited copy of the session file into a run folder, 2. parse the known user/assistant turns for ses...
608
21,140
cognee
cognee/eval_framework/beam/preprocessing/loaders.py
.py
"""BEAM / BEAM-10M dataset loading, reworked to load once per run. ``cognee.eval_framework.benchmark_adapters.beam_adapter``/``beam_10m_adapter`` reload the HuggingFace dataset on every call (``load_beam_row``/``load_beam_10m_row``), which is fine for loading a single conversation for an eval run but wasteful for prep...
89
3,192
cognee
cognee/eval_framework/beam/preprocessing/preprocess.py
.py
"""Preprocess BEAM/BEAM-10M conversations into audited + ingestion-ready JSON documents. Usage example: HF_HUB_OFFLINE=1 HF_DATASETS_OFFLINE=1 uv run python \ -m cognee.eval_framework.beam.preprocessing.preprocess \ --dataset both --execute-compressions --output-dir temp/beam_preprocessed_documents...
1,141
40,312
cognee
cognee/eval_framework/beam/preprocessing/conversation_preprocessing.py
.py
"""Shared BEAM-aware conversation preprocessing helpers.""" from __future__ import annotations from dataclasses import dataclass from functools import lru_cache import re _TURN_START = re.compile( r"^(?:\[(?P<time_anchor>.*?)\]\s*)?(?P<role>User|Assistant):\s?(?P<content>.*)$" ) _SESSION_MARKER = re.compile(r"^-...
955
30,422
cognee
cognee/eval_framework/beam/preprocessing/compression.py
.py
from __future__ import annotations import argparse import asyncio import hashlib import json from collections import Counter from collections.abc import Callable, Iterable from dataclasses import dataclass from typing import Any from pydantic import BaseModel, Field from cognee.eval_framework.beam.preprocessing.conv...
572
19,797
cognee
cognee/eval_framework/beam/eval/beam_eval_adapter.py
.py
import asyncio import os from dataclasses import dataclass from typing import Any, Dict, List, Optional from cognee.eval_framework.evaluation.base_eval_adapter import BaseEvalAdapter from cognee.eval_framework.beam.eval.metrics.beam_rubric import BEAMRubricMetric from cognee.eval_framework.beam.eval.metrics.kendall_ta...
121
4,207
cognee
cognee/eval_framework/beam/eval/aggregate_cross_run.py
.py
"""Aggregate BEAM metrics across repeated runs for one retriever.""" import argparse import json import re import statistics from collections import Counter, defaultdict from pathlib import Path from cognee.eval_framework.analysis.metrics_calculator import bootstrap_ci ARTIFACT_PREFIX = "beam_existing_ingestion" MET...
181
5,914
cognee
cognee/eval_framework/beam/eval/registry.py
.py
from dataclasses import dataclass, field from typing import Any, Literal, Optional from cognee.modules.retrieval.completion_retriever import CompletionRetriever from cognee.modules.retrieval.graph_completion_context_extension_retriever import ( GraphCompletionContextExtensionRetriever, ) from cognee.modules.retrie...
119
3,978
cognee
cognee/eval_framework/beam/eval/run_sweep.py
.py
"""Run BEAM answer/eval sweep against an already-ingested Cognee corpus.""" from __future__ import annotations import argparse import asyncio import logging import os import time from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path import sys from typing import Any, Optio...
446
16,525
cognee
cognee/eval_framework/beam/eval/sweep.py
.py
from __future__ import annotations import json from copy import deepcopy from datetime import datetime, timezone from pathlib import Path from typing import Any, Optional from cognee.eval_framework.beam.eval.registry import ANSWERING_STRATEGIES from cognee.eval_framework.eval_config import EvalConfig from cognee.eval...
231
8,252
cognee
cognee/eval_framework/beam/eval/metrics/kendall_tau.py
.py
"""Kendall's tau-b metric for BEAM event_ordering questions. Computes Kendall's tau-b rank correlation between the predicted and reference event orderings, combined with F1 for event coverage. Final score = tau_b_normalized Γ— event_f1. Only applies to event_ordering questions; returns None for all other types. Refer...
273
9,274
cognee
cognee/eval_framework/beam/eval/metrics/beam_rubric.py
.py
"""BEAM rubric metric with 3-level scoring (0.0, 0.5, 1.0). Uses the judge prompt from the official BEAM paper repository. Each rubric criterion is scored independently by an LLM judge. Final score = mean across all criteria for that question. Reference: https://github.com/mohammadtavakoli78/BEAM/blob/main/src/evalua...
241
9,483
cognee
cognee/eval_framework/corpus_builder/run_corpus_builder.py
.py
from cognee.shared.logging_utils import get_logger, ERROR import json from typing import List, Optional from cognee.infrastructure.files.storage import get_file_storage from cognee.eval_framework.corpus_builder.corpus_builder_executor import CorpusBuilderExecutor from cognee.modules.data.models.questions_base import Q...
78
3,049
cognee
cognee/eval_framework/corpus_builder/corpus_builder_executor.py
.py
import cognee from cognee.shared.logging_utils import get_logger, ERROR from typing import Optional, Tuple, List, Dict, Union, Any, Callable, Awaitable from cognee.eval_framework.benchmark_adapters.benchmark_adapters import BenchmarkAdapter from cognee.modules.chunking.TextChunker import TextChunker from cognee.module...
82
2,924
cognee
cognee/eval_framework/corpus_builder/task_getters/get_default_tasks_by_indices.py
.py
from typing import List from cognee.api.v1.cognify.cognify import get_default_tasks from cognee.modules.pipelines.tasks.task import Task from cognee.modules.chunking.TextChunker import TextChunker from cognee.tasks.graph import extract_graph_from_data from cognee.tasks.storage import add_data_points from cognee.shared....
61
2,325
cognee
cognee/eval_framework/corpus_builder/task_getters/TaskGetters.py
.py
from enum import Enum from typing import Callable, Awaitable, List from cognee.api.v1.cognify.cognify import get_default_tasks from cognee.modules.pipelines.tasks.task import Task from cognee.eval_framework.corpus_builder.task_getters.get_cascade_graph_tasks import ( get_cascade_graph_tasks, ) from cognee.eval_fram...
34
1,184
cognee
cognee/eval_framework/corpus_builder/task_getters/get_cascade_graph_tasks.py
.py
from typing import List from pydantic import BaseModel from cognee.modules.cognify.config import get_cognify_config from cognee.modules.pipelines.tasks.task import Task from cognee.modules.users.methods import get_default_user from cognee.modules.users.models import User from cognee.shared.data_models import Knowledge...
50
1,830
cognee
cognee/eval_framework/evaluation/evaluator_adapters.py
.py
from enum import Enum from importlib import import_module from typing import Optional, Type class EvaluatorAdapter(Enum): """Registry of evaluation engines. The adapter class is resolved lazily through an import path instead of being imported at module load time. This keeps optional dependencies (e.g. ...
65
2,221
cognee
cognee/eval_framework/evaluation/direct_llm_eval_adapter.py
.py
from typing import Any, Dict, List from pydantic import BaseModel from cognee.eval_framework.evaluation.base_eval_adapter import BaseEvalAdapter from cognee.eval_framework.eval_config import EvalConfig from cognee.infrastructure.llm.prompts import render_prompt, read_query_prompt from cognee.infrastructure.llm import ...
60
2,167
cognee
cognee/eval_framework/evaluation/deep_eval_adapter.py
.py
from deepeval.metrics import GEval from deepeval.test_case import LLMTestCase, LLMTestCaseParams from cognee.eval_framework.eval_config import EvalConfig from cognee.eval_framework.evaluation.base_eval_adapter import BaseEvalAdapter from cognee.eval_framework.evaluation.metrics.exact_match import ExactMatchMetric from ...
106
4,532
cognee
cognee/eval_framework/evaluation/base_eval_adapter.py
.py
from abc import ABC, abstractmethod from typing import Any, Dict, List class BaseEvalAdapter(ABC): @abstractmethod async def evaluate_answers( self, data: List[Dict[str, Any]], evaluator_metrics: List[str] ) -> List[Dict[str, Any]]: pass
11
268
cognee
cognee/eval_framework/evaluation/run_evaluation_module.py
.py
from cognee.shared.logging_utils import get_logger import json from typing import List from cognee.eval_framework.evaluation.evaluation_executor import EvaluationExecutor from cognee.eval_framework.analysis.metrics_calculator import calculate_metrics_statistics from cognee.infrastructure.files.storage import get_file_s...
81
3,217
cognee
cognee/eval_framework/evaluation/evaluation_executor.py
.py
from typing import List, Dict, Any, Union from cognee.eval_framework.evaluation.evaluator_adapters import EvaluatorAdapter class EvaluationExecutor: def __init__( self, evaluator_engine: Union[str, EvaluatorAdapter, Any] = "DeepEval", evaluate_contexts: bool = False, ) -> None: ...
29
1,208
cognee
cognee/eval_framework/evaluation/metrics/context_coverage.py
.py
from deepeval.metrics import SummarizationMetric from deepeval.test_case import LLMTestCase from deepeval.metrics.summarization.schema import ScoreType from deepeval.metrics.indicator import metric_progress_indicator from deepeval.utils import get_or_create_event_loop class ContextCoverageMetric(SummarizationMetric):...
51
2,028
cognee
cognee/eval_framework/evaluation/metrics/rubric.py
.py
"""Rubric-based evaluation metric for BEAM benchmark. Scores an LLM response against a list of rubric criteria using an LLM judge. Each rubric item describes something the response "should contain" or "should state". The score is the fraction of rubric items satisfied (0.0 to 1.0). Unlike DeepEval's GEval, this metri...
165
5,242
cognee
cognee/eval_framework/evaluation/metrics/f1.py
.py
from collections import Counter from deepeval.test_case import LLMTestCase import re from typing import Optional, Any class F1ScoreMetric: def __init__(self) -> None: self.score: Optional[float] = None self.reason: Optional[str] = None def measure(self, test_case: "LLMTestCase") -> float: ...
47
1,652
cognee
cognee/eval_framework/evaluation/metrics/exact_match.py
.py
from deepeval.test_case import LLMTestCase from typing import Optional class ExactMatchMetric: def __init__(self) -> None: self.score: Optional[float] = None self.reason: Optional[str] = None def measure(self, test_case: "LLMTestCase") -> float: actual = test_case.actual_output.strip(...
16
628
cognee
cognee/eval_framework/answer_generation/run_question_answering_module.py
.py
from cognee.shared.logging_utils import get_logger import json from typing import List, Optional from cognee.eval_framework.answer_generation.answer_generation_executor import ( AnswerGeneratorExecutor, retriever_options, ) from cognee.infrastructure.files.storage import get_file_storage from cognee.infrastruct...
77
2,995
cognee
cognee/eval_framework/answer_generation/beam_router.py
.py
"""BEAM question-type router β€” routes probing questions to appropriate retrievers. Each BEAM question type maps to a retriever + system prompt strategy. The router classifies the question (using pre-labeled types from the dataset) and delegates to the matching retrieval strategy. """ from typing import Any, Dict, Lis...
190
8,034
cognee
cognee/eval_framework/answer_generation/answer_generation_executor.py
.py
from typing import List, Dict, Any from cognee.modules.retrieval.completion_retriever import CompletionRetriever from cognee.modules.retrieval.graph_completion_context_extension_retriever import ( GraphCompletionContextExtensionRetriever, ) from cognee.modules.retrieval.graph_completion_cot_retriever import GraphCo...
60
2,310
cognee
cognee/eval_framework/answer_generation/question_type_prompts.py
.py
from __future__ import annotations from functools import lru_cache from pathlib import Path from typing import Mapping, Optional QUESTION_TYPE_DEFAULT_KEY = "DEFAULT" def get_question_type_prompt( prompt_paths: Mapping[str, str], question_type: str, ) -> Optional[str]: prompt_path = prompt_paths.get(que...
28
708
cognee
cognee/eval_framework/token_usage_analysis/cost_model.py
.py
"""Cost comparison between full-context prompting and cognee persistent memory. Pure arithmetic, no IO. The two querying strategies are modelled as objects that each compute their own cumulative token cost over a number of queries. Every other figure (parity, reduction milestones) is derived from those two objects. ""...
115
4,137
cognee
cognee/eval_framework/token_usage_analysis/analyze.py
.py
"""Estimate the token cost of cognee memory vs. full-context prompting. Measure a few representative chunks of an input, then extrapolate the full-context-vs-cognee cost comparison to the whole corpus. See README.md. """ from __future__ import annotations import json from pathlib import Path from dotenv import load...
47
1,263
cognee
cognee/eval_framework/token_usage_analysis/plot.py
.py
"""Optional plotting: one cumulative-cost cross-over figure per llm_model. Matplotlib is imported lazily so a JSON-only run needs no extra dependency. The curves are rebuilt from the four numbers already in the report, so this stays a pure consumer of the report with no cost-model knowledge. """ from __future__ impor...
62
2,119
cognee
cognee/eval_framework/token_usage_analysis/measure.py
.py
"""Measure the real token cost of ingesting a chunk with cognee. This is the only module that calls the LLM. Each sampled chunk is run through cognee's summary and graph-extraction calls, and the real prompt/completion token usage is read off each response (so instruction and schema overhead are included). Multiple ll...
110
4,172
cognee
cognee/eval_framework/token_usage_analysis/cli.py
.py
"""Command-line interface: argument definitions and default resolution. Kept separate so analyze.py reads as pure orchestration. """ from __future__ import annotations import argparse from pathlib import Path from corpus import DEFAULT_MAX_CHUNK_SIZE DESCRIPTION = "Estimate the token cost of cognee memory vs. full...
82
3,026
cognee
cognee/eval_framework/token_usage_analysis/corpus.py
.py
"""Turn an input (file, directory, or raw string) into sampled chunks. No LLM calls and no cost math here β€” just reading text and running cognee's TextChunker so the sampled chunks match what ingestion would actually see. """ from __future__ import annotations import asyncio import importlib import random from pathl...
74
2,771
cognee
cognee/eval_framework/token_usage_analysis/report.py
.py
"""Per-llm_model orchestration: turn measurements into the JSON report. Reads as: take this llm_model's chunk measurements, size the corpus, build the two query-cost strategies, and read the reduction milestones off them. """ from __future__ import annotations from cost_model import ( ChunkMeasurement, Cogne...
99
3,530
cognee
cognee/modules/session_distillation/models.py
.py
"""Data models and tunables for session distillation. Distillation turns a finished session's distillable context entries into standalone lesson documents in the knowledge graph. The flow: select -> batch (qa + candidates) -> curate per batch -> judge + write per lesson -> persist Curator calls run in parallel b...
99
3,270
cognee
cognee/modules/session_distillation/__init__.py
.py
from .distill import distill_session from .models import ( CuratorBatchOutput, DistillationResult, ProposedLesson, WrittenLesson, ) __all__ = [ "distill_session", "CuratorBatchOutput", "DistillationResult", "ProposedLesson", "WrittenLesson", ]
16
281
cognee
cognee/modules/session_distillation/distill.py
.py
"""Distill a finished session's learnings into the persistent knowledge graph. Flow (curator calls parallel by batch; accept/write calls parallel by lesson): 1. LOAD session QA turns + distillable session-context entries. 2. CURATE pack the session timeline into batches; one curator LLM call per batch. 3. ACCEPT ...
406
14,243
cognee
cognee/modules/settings/save_vector_db_config.py
.py
from typing import Union, Literal from pydantic import BaseModel from cognee.infrastructure.databases.vector import get_vectordb_config class VectorDBConfig(BaseModel): url: str api_key: str provider: Union[Literal["lancedb"], Literal["pgvector"]] async def save_vector_db_config(vector_db_config: Vector...
20
652
cognee
cognee/modules/settings/get_current_settings.py
.py
from typing import TypedDict from cognee.infrastructure.llm import get_llm_config from cognee.infrastructure.databases.graph import get_graph_config from cognee.infrastructure.databases.vector import get_vectordb_config from cognee.infrastructure.databases.relational.config import get_relational_config class LLMConfi...
61
1,642
cognee
cognee/modules/settings/get_settings.py
.py
from enum import Enum from typing import Optional from pydantic import BaseModel from cognee.infrastructure.databases.vector import get_vectordb_config from cognee.infrastructure.llm import get_llm_config class ConfigChoice(BaseModel): value: str label: str class ModelName(Enum): openai = "openai" o...
192
5,820
cognee
cognee/modules/settings/save_llm_config.py
.py
import os from pydantic import BaseModel from cognee.infrastructure.llm import get_llm_config class LLMConfig(BaseModel): api_key: str model: str provider: str async def save_llm_config(new_llm_config: LLMConfig): llm_config = get_llm_config() llm_config.llm_provider = new_llm_config.provider ...
24
730
cognee
cognee/modules/provenance/storage.py
.py
"""Async repository for the provenance ledger over the shared relational DB. Hash-chain appends must be race-free under async SQLAlchemy on SQLite AND Postgres, possibly multi-process. Three layers of defense: 1. A process-local per-event-loop ``asyncio.Lock`` (cheap serialization of the common case). 2. A Postgre...
302
12,722
cognee
cognee/modules/provenance/manager.py
.py
"""Async ProvenanceManager over the audit-grade provenance ledger. Port of semantica's ProvenanceManager onto cognee's shared relational DB (SQLite + Postgres) via the async repository in ``storage.py``. The manager is stateless (sessions per call), so acquisition is a trivial cached factory. Tracking methods (``trac...
708
29,036
cognee
cognee/modules/provenance/__init__.py
.py
"""Audit-grade provenance ledger (append-only, tamper-evident). This module is the fourth β€” and only audit-grade β€” provenance system in cognee. It is deliberately distinct from the other three: - ``cognee/infrastructure/databases/provenance/`` β€” graph source-refs used for delete/rollback ownership (``source_ref:v1:...
26
1,312
cognee
cognee/modules/provenance/integrity.py
.py
"""Integrity primitives for the provenance ledger (pure, sync). Checksum canonicalization is a deliberate break from semantica's byte format, which had two defects: no-separator concatenation (field-boundary ambiguity) and ``None`` hashing differently on the object vs dict path. Cognee ships no semantica databases to ...
126
4,570
cognee
cognee/modules/provenance/models/ProvenanceEntryRow.py
.py
from sqlalchemy import JSON, Boolean, Float, Index, Integer, String, Text, text from sqlalchemy.orm import Mapped, mapped_column from cognee.infrastructure.databases.relational import Base class ProvenanceEntryRow(Base): """One row of the append-only provenance ledger. PK is a plain string, not a UUID colum...
95
5,091
cognee
cognee/modules/provenance/models/ProvenanceEntry.py
.py
from datetime import datetime, timezone from typing import Any, Dict, List, Optional from pydantic import BaseModel, ConfigDict, Field from .ProvenanceEntryRow import ProvenanceEntryRow def utc_now_iso() -> str: """Timezone-aware ISO-8601 timestamp (fixes semantica's naive-utcnow quirk).""" return datetime....
107
3,794
cognee
cognee/modules/provenance/models/__init__.py
.py
"""Provenance ledger models. Importing this package registers ``ProvenanceEntryRow`` on the shared ``Base.metadata`` so both the startup ``create_all`` path and alembic's ``env.py`` see the ``provenance_entries`` table. """ from .ProvenanceEntry import ProvenanceEntry from .ProvenanceEntryRow import ProvenanceEntryRo...
12
375
cognee
cognee/modules/run_custom_pipeline/run_custom_pipeline.py
.py
from typing import Union, Optional, List, Type, Any from uuid import UUID from cognee.shared.logging_utils import get_logger from cognee.modules.pipelines import run_pipeline from cognee.modules.pipelines.tasks.task import Task from cognee.modules.users.models import User from cognee.modules.pipelines.layers.pipeline...
87
4,632
cognee
cognee/modules/storage/utils/__init__.py
.py
import json import copy from uuid import UUID from decimal import Decimal from datetime import date, datetime from pydantic_core import PydanticUndefined from pydantic import create_model, ConfigDict, BaseModel, Field from cognee.infrastructure.engine import DataPoint class JSONEncoder(json.JSONEncoder): def def...
79
2,596
cognee
cognee/modules/chunking/Chunker.py
.py
class Chunker: def __init__(self, document, get_text: callable, max_chunk_size: int): self.chunk_index = 0 self.chunk_size = 0 self.token_count = 0 self.document = document self.max_chunk_size = max_chunk_size self.get_text = get_text def read(self): rai...
13
343
cognee
cognee/modules/chunking/LangchainChunker.py
.py
from cognee.shared.logging_utils import get_logger from os.path import basename from uuid import NAMESPACE_OID, uuid5 from cognee.modules.chunking.Chunker import Chunker from .models.DocumentChunk import DocumentChunk from langchain_text_splitters import RecursiveCharacterTextSplitter from cognee.infrastructure.databa...
67
2,790