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
examples/demos/session_context_growth_demo.py
.py
"""Print a deterministic JSON demo of session-context growth. Run with: uv run python examples/demos/session_context_growth_demo.py This demo isolates the session loop. It does not call a live LLM or retriever. Instead, it feeds simulated feedback-analysis results into ``SessionManager.prepare_session_turn`` and...
379
12,744
cognee
examples/demos/session_flow_stepwise_demo.py
.py
"""Step-by-step trace of the cognee 1.0 memory loop, driven by remember() + recall(). Run with: uv run python examples/demos/session_flow_stepwise_demo.py This is a *narrated trace*: at every hop it prints the actual data so you can watch memory move through the system using only the two top-level verbs, `cognee...
346
15,302
cognee
examples/demos/comprehensive_example/cognee_comprehensive_example.py
.py
# ruff: noqa: E402 import os import asyncio from pathlib import Path # provide your OpenAI key here # Set os.environ before importing Cognee: Cognee reads env-backed settings at import time, so values # assigned later may not override defaults or `.env`. See https://docs.cognee.ai/setup-configuration/overview#using-os...
88
3,357
cognee
examples/demos/session_feedback_lifecycle_demo/backend/app.py
.py
import json import os from datetime import datetime, timezone from pathlib import Path from typing import Any, Optional # Configure cache/session behavior before importing cognee internals. # Set os.environ before importing Cognee: Cognee reads env-backed settings at import time, so values # assigned later may not ove...
830
26,869
cognee
examples/demos/complex_relational_database_migration_example/complex_relational_database_migration_example.py
.py
# ruff: noqa: E402 import asyncio import os import sqlalchemy as sa # This example uses a local Postgres migration database and no backend ACL. # Set os.environ before importing Cognee: Cognee reads env-backed settings at import time, so values # assigned later may not override defaults or `.env`. See https://docs.co...
325
10,918
cognee
examples/demos/skill_feedback_loop/skill_feedback_loop_demo.py
.py
"""Small local demo for ingesting skills, recording a weak run, and proposing an improvement. Run from the repo root: uv run python examples/demos/skill_feedback_loop/skill_feedback_loop_demo.py Requires: LLM_API_KEY set in .env or environment. """ # ruff: noqa: E402 from __future__ import annotations imp...
196
6,720
cognee
examples/demos/simple_relational_database_migration_example/simple_relational_database_migration_example.py
.py
# ruff: noqa: E402 import asyncio import os import sqlalchemy as sa # This example uses a local Postgres migration database and no backend ACL. # Set os.environ before importing Cognee: Cognee reads env-backed settings at import time, so values # assigned later may not override defaults or `.env`. See https://docs.co...
183
9,420
cognee
examples/pocs/disambiguation/disambiguate_entities.py
.py
import asyncio from pydantic import BaseModel from typing import Union, Optional from uuid import UUID from cognee import run_custom_pipeline from cognee.modules.cognify.config import get_cognify_config from cognee.modules.ontology.ontology_env_config import get_ontology_env_config from cognee.shared.logging_utils imp...
254
10,518
cognee
examples/pocs/disambiguation/disambiguate_entities_example.py
.py
import asyncio import os from pathlib import Path from typing import Optional from disambiguate_entities import disambiguate_entities_pipeline import cognee from cognee import visualize_graph async def main( example, use_poc, vector_search_limit: Optional[int] = None, custom_prompt: Optional[str] = None ): ...
61
1,607
cognee
examples/pocs/disambiguation/extract_graph_from_data_with_entity_disambiguation.py
.py
import asyncio from typing import Type, List, Optional, Dict from pydantic import BaseModel from cognee.modules.ontology.ontology_config import Config from cognee.modules.ontology.get_default_ontology_resolver import get_configured_ontology_resolver from cognee.modules.chunking.models.DocumentChunk import DocumentChun...
81
2,911
cognee
examples/pocs/post_extraction_canonicalization/post_extraction_canonicalization.py
.py
import asyncio import os import time import cognee import numpy as np from typing import Dict, Type, List, Optional, Any import pandas as pd from pandas import DataFrame from pydantic import BaseModel from cognee.infrastructure.databases.graph import get_graph_engine from cognee.infrastructure.databases.vector import ...
195
6,635
cognee
examples/pocs/post_extraction_canonicalization/post_extraction_canonicalization_example.py
.py
import asyncio import os import time from pathlib import Path from typing import Any, Awaitable, Callable, Optional import cognee from cognee import visualize_graph from examples.pocs.post_extraction_canonicalization.post_extraction_canonicalization import ( post_extraction_canonicalization, ) async def main( ...
63
1,941
cognee
examples/pocs/prefetch_disambiguation/prefetch_disambiguation_example.py
.py
import asyncio import os import time from pathlib import Path from typing import Any, Awaitable, Callable, Optional import nltk from nltk.tokenize import sent_tokenize import cognee from cognee import visualize_graph from examples.pocs.prefetch_disambiguation.prefetch_disambiguation import ( prefetch_disambiguati...
71
2,211
cognee
examples/pocs/prefetch_disambiguation/prefetch_disambiguation.py
.py
import asyncio import os import time import cognee import numpy as np import pandas as pd from pandas import DataFrame from typing import Optional, List, Type from pydantic import BaseModel from nltk.tokenize import sent_tokenize from cognee.infrastructure.databases.graph import get_graph_engine from cognee.infrastr...
249
8,431
cognee
examples/tutorials/migrate_from_mem0_tutorial.py
.py
""" Migrate from mem0 to Cognee using Mem0Source. Demonstrates how to import a mem0 export (platform JSON or OSS dump) into Cognee's knowledge graph and query the migrated memory. Three import modes: - ``"preserve"`` β€” map mem0 memories straight to graph nodes (no LLM). - ``"re-derive"`` β€” ingest raw text and ru...
97
3,626
cognee
examples/tutorials/migrate_from_letta_and_zep_tutorial.py
.py
""" Migrate from Letta (MemGPT) and Zep / Graphiti to Cognee. Demonstrates how to import a Letta agent file (``.af`` JSON) and a Zep / Graphiti graph export into Cognee's knowledge graph, then query the migrated memory with ``cognee.recall``. Letta import (``re-derive`` mode by default): - Core memory blocks -> ...
190
7,877
cognee
examples/configurations/permissions_example/tenant_role_constraints_example.py
.py
import asyncio from uuid import UUID import cognee from cognee.modules.engine.operations.setup import setup from cognee.modules.users.exceptions import PermissionDeniedError from cognee.modules.users.methods import create_user from cognee.modules.users.permissions.methods import authorized_give_permission_on_datasets ...
110
4,974
cognee
examples/configurations/permissions_example/tenant_role_setup_example.py
.py
import cognee from cognee import SearchType from cognee.modules.engine.operations.setup import setup from cognee.modules.users.methods import create_user, get_user from cognee.modules.users.permissions.methods import authorized_give_permission_on_datasets from cognee.modules.users.roles.methods import add_user_to_role,...
111
4,893
cognee
examples/configurations/permissions_example/data_access_control_example.py
.py
# ruff: noqa: E402 import os import pathlib import asyncio from uuid import UUID import cognee from cognee.modules.users.exceptions import PermissionDeniedError from cognee.shared.logging_utils import get_logger from cognee.modules.search.types import SearchType from cognee.modules.users.methods import create_user fro...
137
5,271
cognee
examples/configurations/permissions_example/user_permissions_and_access_control_example.py
.py
# ruff: noqa: E402 import os import pathlib from uuid import UUID import cognee from cognee import SearchType from cognee.modules.engine.operations.setup import setup from cognee.modules.users.exceptions import PermissionDeniedError from cognee.modules.users.methods import create_user from cognee.modules.users.permiss...
228
10,068
cognee
examples/advanced_guides/remember_recall_improve_example.py
.py
# ruff: noqa: E402 """ V2 Memory-Oriented API: remember, recall, improve, forget, status. The advanced companion to ``examples/guides/simple_cognee_example.py`` and ``examples/guides/improve_quickstart.py``. Those show a single remember β†’ recall flow and a minimal before/after ``improve()``; this one tours the whole m...
155
5,956
cognee
examples/advanced_guides/conversation_session_persistence_example.py
.py
""" Persist conversation sessions into the knowledge graph. The advanced companion to ``examples/guides/sessions.py``. That guide shows recall keeping two ``session_id`` conversations apart; this one runs six turns across two sessions, then goes further: it persists both sessions into the permanent knowledge graph wit...
110
3,697
cognee
examples/advanced_guides/global_context_index_smoke_demo.py
.py
""" Smoke demo for the global context index. The advanced companion to ``examples/guides/global_context_index.py``. That guide shows the flag on a five-turn conversation; this one runs a multi-day scheduling thread where meetings are booked, moved, and cancelled, then asks three questions whose answers depend on the w...
125
5,098
cognee
examples/advanced_guides/truth_centroid_slots_demo.py
.py
"""End-to-end demo of truth centroid slots changing HybridRetriever ranking. The advanced companion to ``examples/demos/truth_subspace_reranking_demo.py``: that demo shows what truth-subspace weighting does to ranking; this one shows how it works underneath β€” the deterministic centroid slots and their epochs, includin...
268
10,746
cognee
examples/advanced_guides/session_distillation_demo.py
.py
"""Session vector retrieval + distillation demo. The advanced companion to ``examples/guides/session_distillation.py``. That guide runs a minimal before/after distillation experiment on one stated preference; this one replays an eight-message scripted session, adds hybrid vector recall over the indexed QA turns, and v...
193
7,581
cognee
examples/advanced_guides/simple_document_qa/simple_document_qa_demo.py
.py
# ruff: noqa: E402 """ Q&A over a full real document. The advanced companion to ``examples/guides/simple_cognee_example.py``. Same remember β†’ recall flow, but instead of a short inline string it ingests a bundled real document (``data/alice_in_wonderland.txt``, the full text of Alice in Wonderland) and asks questions ...
54
1,704
cognee
examples/advanced_guides/temporal_awareness_example/temporal_awareness_example.py
.py
""" Temporal search over real biography documents. The advanced companion to ``examples/guides/temporal_recall.py``. That guide inlines a four-sentence timeline; this one ingests two bundled real biographies (``data/biography_1.txt``, ``data/biography_2.txt``) with ``temporal_cognify=True`` and runs ``SearchType.TEMPO...
66
2,162
cognee
examples/advanced_guides/ontology_reference_vocabulary/ontology_as_reference_vocabulary_example.py
.py
""" Ontology as a reference vocabulary for extraction. The advanced companion to ``examples/guides/ontology_quickstart.py``. That guide applies a bundled ontology to two inline sentences; this one grounds two bundled real documents (``data/text_1.txt``, ``data/text_2.txt``) in ``data/basic_ontology.owl``, building the...
74
2,380
cognee
examples/custom_pipelines/custom_cognify_pipeline_example.py
.py
import asyncio import cognee from cognee import SearchType from cognee.modules.engine.operations.setup import setup from cognee.modules.pipelines import Task from cognee.modules.users.methods import get_default_user from cognee.shared.logging_utils import INFO, setup_logging # Prerequisites: # 1. Copy `.env.template`...
86
2,870
cognee
examples/custom_pipelines/memify_coding_agent_rule_extraction_example.py
.py
import asyncio import os import pathlib import cognee from cognee import memify, visualize_graph from cognee.modules.pipelines.tasks.task import Task from cognee.shared.logging_utils import ERROR, setup_logging from cognee.tasks.codingagents.coding_rule_associations import add_rule_associations from cognee.tasks.memif...
107
4,489
cognee
examples/custom_pipelines/relational_database_to_knowledge_graph_migration_example.py
.py
# ruff: noqa: E402 import asyncio import os from pathlib import Path from dotenv import load_dotenv load_dotenv(override=True) # Set os.environ before importing Cognee: Cognee reads env-backed settings at import time, so values # assigned later may not override defaults or `.env`. See https://docs.cognee.ai/setup-co...
118
4,843
cognee
examples/custom_pipelines/agentic_reasoning_procurement_example.py
.py
# ruff: noqa: E402 import asyncio import logging import os from dotenv import load_dotenv load_dotenv() # Notes: Nodesets cognee feature only works with Ladybug and Neo4j graph databases # Set os.environ before importing Cognee: Cognee reads env-backed settings at import time, so values # assigned later may not over...
209
8,118
cognee
examples/custom_pipelines/dynamic_steps_resume_analysis_hr_example.py
.py
import asyncio import cognee from cognee import SearchType from cognee.shared.logging_utils import ERROR, setup_logging job_1 = """ CV 1: Relevant Name: Dr. Emily Carter Contact Information: Email: emily.carter@example.com Phone: (555) 123-4567 Summary: Senior Data Scientist with over 8 years of experience in machi...
213
6,565
cognee
examples/custom_pipelines/organizational_hierarchy/organizational_hierarchy_pipeline_low_level_example.py
.py
"""Cognee demo with simplified structure.""" from __future__ import annotations import asyncio import json import logging from collections import defaultdict from pathlib import Path from typing import Any, Iterable, List, Mapping from cognee import config, prune, search, SearchType, visualize_graph from cognee.low_...
267
8,231
cognee
examples/custom_pipelines/organizational_hierarchy/organizational_hierarchy_pipeline_example.py
.py
import os import json import asyncio from typing import List, Any, Dict from uuid import uuid5, NAMESPACE_OID, UUID from pydantic import BaseModel from cognee import prune from cognee import visualize_graph from cognee.low_level import setup, DataPoint from cognee.modules.data.methods import load_or_create_datasets f...
140
4,407
cognee
examples/guides/custom_prompts.py
.py
import asyncio import cognee from cognee import SearchType custom_prompt = """ Extract only people and cities as entities. Connect people to cities with the relationship "lives_in". Ignore all other entities. """ async def main(): await cognee.forget(everything=True) await cognee.remember( [ ...
34
876
cognee
examples/guides/low_level_llm.py
.py
import asyncio from pydantic import BaseModel from typing import List from cognee.infrastructure.llm.LLMGateway import LLMGateway class MiniEntity(BaseModel): name: str type: str class MiniGraph(BaseModel): nodes: List[MiniEntity] async def main(): system_prompt = ( "Extract entities as n...
32
707
cognee
examples/guides/entity_deduplication.py
.py
import asyncio import cognee from os import path from cognee.api.v1.visualize.visualize import visualize_graph from cognee.memify_pipelines.consolidate_entities import consolidate_entities_pipeline custom_prompt = """ Extract every place mentioned in the text as an entity, keeping the exact surface form used in the t...
49
1,589
cognee
examples/guides/langfuse_telemetry.py
.py
"""Send cognee traces to Langfuse natively over OpenTelemetry. Cognee already emits rich OpenTelemetry (OTEL) spans. Instead of double-instrumenting with a separate Langfuse SDK, you point cognee's existing OTLP exporter at Langfuse β€” Langfuse is just another OTLP destination, like Dash0 or Datadog. To run: 1. Crea...
47
1,666
cognee
examples/guides/references_example.py
.py
"""Lightweight references (Evidence) in recall answers. ``include_references=True`` appends an Evidence section to the answer text itself, so you can see which chunks the answer is grounded in. Each bullet cites a document name, a chunk number, and a snippet. Off (the default), you get the concise answer alone. The E...
79
2,912
cognee
examples/guides/neo4j_example.py
.py
"""Use Neo4j as cognee's graph database. Prerequisites: 1. Install the Neo4j extra: `uv pip install "cognee[neo4j]"` 2. Start a Neo4j server, e.g. with Docker: docker run -p 7474:7474 -p 7687:7687 -e NEO4J_AUTH=neo4j/yourpassword neo4j:5 3. Set the password (and any non-default connection values) in `.env` or the ...
131
5,080
cognee
examples/guides/simple_cognee_example.py
.py
import asyncio import cognee from cognee import SearchType from cognee.shared.logging_utils import ERROR, setup_logging # Prerequisites: # 1. Copy `.env.template` and rename it to `.env`. # 2. Add your OpenAI API key to the `.env` file in the `LLM_API_KEY` field: # LLM_API_KEY = "your_key_here" async def main():...
36
1,024
cognee
examples/guides/consolidate_entity_descriptions_example.py
.py
import asyncio from os import path import cognee from cognee import visualize_graph from cognee.memify_pipelines.consolidate_entity_descriptions import ( consolidate_entity_descriptions_pipeline, ) custom_prompt = """ Extract only people and cities as entities. Connect people to cities with the relationship "live...
46
1,465
cognee
examples/guides/custom_data_models.py
.py
import asyncio from typing import Any from pydantic import SkipValidation import cognee from cognee.infrastructure.engine import DataPoint from cognee.infrastructure.engine.models.Edge import Edge from cognee.tasks.storage import add_data_points class Person(DataPoint): name: str # Keep it simple for forward...
39
1,099
cognee
examples/guides/code_graph_example.py
.py
"""Build a code knowledge graph with enola + cognee, then query it. What it shows: - Running the enola-backed code graph pipeline (extract -> load nodes -> load edges) - Querying the resulting graph deterministically with SearchType.CODE Requirements: - The enola binary β€” installed automatically on first ...
77
2,881
cognee
examples/guides/multimedia_audio_image_processing_example.py
.py
import asyncio import os import pathlib import cognee from cognee import SearchType from cognee.shared.logging_utils import ERROR, setup_logging # Prerequisites: # 1. Copy `.env.template` and rename it to `.env`. # 2. Add your OpenAI API key to the `.env` file in the `LLM_API_KEY` field: # LLM_API_KEY = "your_key_...
51
1,684
cognee
examples/guides/custom_graph_model.py
.py
import asyncio import os from typing import List from cognee import forget, remember, visualize_graph from cognee.low_level import DataPoint CUSTOM_PROMPT = ( "Extract all people mentioned in the text. " "For each person, extract ALL activities they like, including shared activities." ) class Activity(DataP...
52
1,239
cognee
examples/guides/graph_visualization.py
.py
"""Render a knowledge graph to an interactive HTML file. ``visualize_graph`` renders a *bounded subgraph* by default β€” seed nodes plus their k-hop neighborhood, capped at ``max_nodes`` β€” instead of the whole graph. This guide writes one HTML file per seeding mode so you can compare them: 1. default β€” highest-degr...
63
2,349
cognee
examples/guides/agent_memory_quickstart.py
.py
""" Two agents, two types of memory. support_agent β€” remembers everything within the active session. Traces are saved to the knowledge graph over time. faq_bot β€” reads only from the knowledge graph. It learns only what support_agent has already filed. """ import asyncio import o...
116
3,924
cognee
examples/guides/temporal_recall.py
.py
"""Time-bounded recall over an ingested timeline. ``remember(..., temporal_cognify=True)`` extracts events with their dates, so ``SearchType.TEMPORAL`` can answer questions that depend on ordering β€” before, after, and between a pair of dates β€” rather than on embedding similarity alone. """ import asyncio import cogn...
49
1,245
cognee
examples/guides/start_local_ui_frontend_example.py
.py
#!/usr/bin/env python3 """ Example showing how to use cognee.start_ui() to launch the frontend. This demonstrates the new UI functionality that works similar to DuckDB's start_ui(). """ import asyncio import time import cognee async def main(): # First, let's add some data to cognee for the UI to display p...
59
1,734
cognee
examples/guides/custom_tasks_and_pipelines.py
.py
import asyncio import os from typing import Any, Dict, List from uuid import NAMESPACE_OID, UUID, uuid5 from pydantic import BaseModel import cognee from cognee import visualize_graph from cognee.infrastructure.engine import DataPoint from cognee.infrastructure.llm.LLMGateway import LLMGateway from cognee.modules.eng...
97
2,970
cognee
examples/guides/recall_core.py
.py
import asyncio import cognee async def main(): # Start clean (optional in your app) await cognee.forget(everything=True) # Prepare knowledge base await cognee.remember( [ "Alice moved to Paris in 2010. She works as a software engineer.", "Bob lives in New York. He is a ...
26
714
cognee
examples/guides/sessions.py
.py
import asyncio import cognee from cognee import SearchType async def main(): # Start clean (optional in your app) await cognee.forget(everything=True) # Prepare knowledge base await cognee.remember( [ "Alice moved to Paris in 2010. She works as a software engineer.", "...
49
1,563
cognee
examples/guides/improve_quickstart.py
.py
import asyncio import cognee DATASET = "demo_dataset" SESSION = "demo_session" async def main(): await cognee.forget(everything=True) await cognee.remember( "Einstein developed general relativity.", dataset_name=DATASET, self_improvement=False, ) await cognee.remember( ...
42
918
cognee
examples/guides/global_context_index.py
.py
"""Global context index: a dataset-level summary prepended to retrieval context. ``improve(..., build_global_context_index=True)`` builds a compact summary of the whole dataset β€” a world summary plus the areas it covers. When ``include_global_context_index`` is on, the retriever **prepends that summary to the context ...
79
3,003
cognee
examples/guides/nodeset_grouping_example.py
.py
import asyncio import os import cognee from cognee import visualize_graph from cognee.shared.logging_utils import ERROR, setup_logging text_a = """ AI is revolutionizing financial services through intelligent fraud detection and automated customer service platforms. """ text_b = """ Advances in AI ar...
43
1,178
cognee
examples/guides/s3_storage.py
.py
import asyncio import cognee async def main(): # Single file: ingest and build the graph in one call await cognee.remember( "s3://cognee-s3-small-test/Natural_language_processing.txt", dataset_name="s3_single_demo", self_improvement=False, ) # Folder/prefix (recursively expand...
33
774
cognee
examples/guides/memory_provenance.py
.py
"""Memory provenance: tracing a fact back to the file it came from. ``get_memory_provenance_graph()`` reads the bookkeeping cognee keeps in its relational database and projects it into a ``(nodes, edges)`` graph whose edges form an ownership chain: Tenant --has_member--> User --owns--> Dataset --contains--> TextD...
77
3,488
cognee
examples/guides/web_url_content_ingestion_example.py
.py
"""Ingest a web page with a custom loader and CSS extraction rules. Requires network access: this fetches a live Wikipedia endpoint rather than a local file, so it is also sensitive to that page's HTML structure changing. """ import asyncio from os import path import cognee async def main(): await cognee.forge...
45
1,209
cognee
examples/guides/pgvector_example.py
.py
"""Use PostgreSQL with the PGVector extension as cognee's vector (and relational) store. Prerequisites: 1. Install the Postgres extra: `uv pip install "cognee[postgres]"` 2. Start a Postgres server with the pgvector extension, e.g. with Docker: docker run -p 5432:5432 -e POSTGRES_USER=cognee -e POSTGRES_PASSWORD=co...
122
4,398
cognee
examples/guides/ontology_quickstart.py
.py
import asyncio import cognee import os from cognee.modules.ontology.ontology_config import Config from cognee.modules.ontology.rdf_xml.RDFLibOntologyResolver import RDFLibOntologyResolver async def main(): # Prune data and system metadata before running, only if we want "fresh" state. await cognee.forget(ever...
30
882
cognee
examples/guides/video_processing_example.py
.py
import asyncio import os import sys import cognee from cognee import SearchType from cognee.shared.logging_utils import ERROR, setup_logging # Prerequisites: # 1. Copy `.env.template` and rename it to `.env`. # 2. Add your OpenAI API key to the `.env` file in the `LLM_API_KEY` field: # LLM_API_KEY = "your_key_here...
55
1,834
cognee
examples/guides/schema_inventory.py
.py
"""Schema and entity inventory in the rendered graph. ``visualize_graph`` writes an HTML file with a schema side panel: every entity type cognee extracted, how many instances of each, sample names, and which relationships connect the types. This guide ingests a handful of sentences about one domain so several distinct...
45
1,504
cognee
examples/guides/image_ocr_extraction_check.py
.py
"""Print the text an image becomes: the vision-model transcription plus appended OCR text. Requires LLM_API_KEY (copy `.env.template` -> `.env`) and the OCR engine: pip install "cognee[rapidocr]". """ import asyncio import os import pathlib from cognee.infrastructure.loaders.core.image_loader import ImageLoader os....
30
782
cognee
examples/guides/neptune_analytics_example.py
.py
"""Use Amazon Neptune Analytics as cognee's graph and vector database. Prerequisites β€” unlike the other backend guides, this one needs a cloud account, not a local server: 1. An AWS account with a **provisioned Neptune Analytics graph** (https://docs.aws.amazon.com/neptune-analytics/latest/userguide/create-graph-us...
129
5,219
cognee
examples/guides/session_distillation.py
.py
import asyncio import os import sys # Let the session capture the user's stated preference as learned guidance. os.environ["AUTO_FEEDBACK"] = "true" os.environ.setdefault("LOG_LEVEL", "ERROR") import cognee from cognee import SearchType from cognee.infrastructure.session.get_session_manager import get_session_manager...
129
4,767
cognee
examples/guides/ladybug_example.py
.py
"""Use Ladybug β€” cognee's default embedded graph database β€” as the graph store. Prerequisites: none beyond a configured LLM (`LLM_API_KEY` in `.env`). Ladybug is embedded and ships with cognee, so this guide runs as-is β€” no server to start, no pip extra to install. """ import asyncio import pathlib import cognee fro...
89
3,146
cognee
examples/guides/importance_weight.py
.py
import asyncio import os import cognee from cognee import visualize_graph async def main(): await cognee.forget(everything=True) await cognee.remember( "Diana and Tom were born and raised in Helsinki. Diana currently resides in Berlin, while Tom never moved.", dataset_name="importance_demo",...
43
1,145
cognee
examples/guides/semantic_memory_map.py
.py
"""Demo: the Semantic Memory Map. Runs a real cognee pipeline (add β†’ cognify) and renders the knowledge graph with ``visualize_graph``. The resulting HTML has a **Semantic** tab that lays the graph out by *meaning*: every node is placed at the 2-D projection of its embedding, so semantically similar nodes cluster toge...
67
2,544
cognee
evals/old/falkor_01042025/hotpot_qa_falkor_graphrag_sdk.py
.py
from dotenv import load_dotenv import json import os from dataclasses import dataclass from graphrag_sdk.source import URL, STRING from graphrag_sdk import KnowledgeGraph, Ontology from graphrag_sdk.models.litellm import LiteModel from graphrag_sdk.model_config import KnowledgeGraphModelConfig from falkordb import Falk...
228
7,506
cognee
evals/old/mem0_01042025/hotpot_qa_mem0.py
.py
from dotenv import load_dotenv import json from dataclasses import dataclass from openai import OpenAI from mem0 import Memory from tqdm import tqdm load_dotenv() def load_corpus_to_memory( memory: Memory, corpus_file: str = "hotpot_50_corpus.json", user_id: str = "hotpot_qa_user", limit: int = None,...
164
5,117
cognee
evals/old/comparative_eval/helpers/modal_evaluate_answers.py
.py
import modal import os import asyncio import datetime import hashlib import json from cognee.shared.logging_utils import get_logger from cognee.eval_framework.eval_config import EvalConfig from cognee.eval_framework.evaluation.run_evaluation_module import run_evaluation from cognee.eval_framework.metrics_dashboard impo...
162
5,923
cognee
evals/old/comparative_eval/helpers/calculate_aggregate_metrics.py
.py
#!/usr/bin/env python3 """Simple script to calculate aggregate metrics for multiple JSON files.""" import os from cognee.eval_framework.analysis.metrics_calculator import calculate_metrics_statistics from cognee.shared.logging_utils import get_logger logger = get_logger() def calculate_aggregates_for_files(json_pat...
39
1,441
cognee
evals/old/comparative_eval/helpers/convert_metrics.py
.py
import json import os from pathlib import Path from typing import List, Dict, Any import pandas as pd def convert_metrics_file(json_path: str, metrics: List[str] = None) -> Dict[str, Any]: """Convert a single metrics JSON file to the desired format.""" if metrics is None: metrics = ["correctness", "f1...
108
3,464
cognee
evals/old/graphiti_01042025/hotpot_qa_graphiti.py
.py
import asyncio import json import os from dataclasses import dataclass from datetime import datetime, timezone from dotenv import load_dotenv from langchain_openai import ChatOpenAI from openai import OpenAI from tqdm import tqdm from graphiti_core import Graphiti from graphiti_core.nodes import EpisodeType load_dot...
187
5,882
cognee
evals/old/hotpot_qa_24_2025/plot_metrics.py
.py
import json import sys from pathlib import Path from typing import Any, Dict, List import matplotlib.pyplot as plt import numpy as np INPUT_COGNEE = Path("evals/benchmark_summary_cognee.json") INPUT_COMPETITION = Path("evals/benchmark_summary_competition.json") OUT_OPTIMISED = "evals/optimized_cognee_configurations....
157
4,609
cognee
evals/old/hotpot_qa_24_2025/src/hotpotqa_instances.py
.py
from cognee.eval_framework.benchmark_adapters.hotpot_qa_adapter import HotpotQAAdapter import json INSTANCE_FILTER = [ "5a8e341c5542995085b373d6", "5ab2a308554299340b52553b", "5a79c1095542996c55b2dc62", "5a8c52685542995e66a475bb", "5a734dad5542994cef4bc522", "5a74ab6055429916b01641b9", "5ae...
41
1,228
cognee
evals/old/hotpot_qa_24_2025/src/visualize_benchmarks.py
.py
import json import matplotlib.pyplot as plt import numpy as np import sys def load_benchmark_data(filename): """Load benchmark data from JSON file.""" with open(filename, "r") as f: return json.load(f) def visualize_benchmarks(benchmark_file, output_file=None): """Visualize benchmark results wit...
96
3,105
cognee
evals/old/hotpot_qa_24_2025/src/create_benchmark_summary_json.py
.py
#!/usr/bin/env python3 """ Postprocessing script to create benchmark summary JSON from cross-benchmark analysis results. Converts CSV data into JSON format with confidence intervals. """ import os import json import pandas as pd from pathlib import Path from typing import Dict, List, Any, Tuple import numpy as np de...
540
19,712
cognee
evals/old/hotpot_qa_24_2025/src/run_cross_benchmark_analysis.py
.py
#!/usr/bin/env python3 """ Cross-benchmark analysis orchestration script. Downloads qa-benchmarks volume and processes each benchmark folder. """ import os import subprocess import sys from pathlib import Path import pandas as pd from analysis.analyze_single_benchmark import analyze_single_benchmark_folder def downl...
256
8,613
cognee
evals/old/hotpot_qa_24_2025/src/analysis/analyze_single_benchmark.py
.py
import os import subprocess import sys from pathlib import Path from analysis.process_results import ( process_results, transform_results, validate_question_consistency, create_answers_df, create_all_metrics_df, ) from analysis.analyze_results import create_aggregate_metrics_df, cumulative_all_metri...
131
4,492
cognee
evals/old/hotpot_qa_24_2025/src/analysis/get_results.py
.py
import json import os from pathlib import Path from typing import Dict, List, Any def read_results(dir_path: str) -> Dict[str, Any]: """Read all JSON files from the specified directory path.""" results = {} dir_path = Path(dir_path) if not dir_path.exists(): raise FileNotFoundError(f"Director...
141
4,799
cognee
evals/old/hotpot_qa_24_2025/src/analysis/analyze_results.py
.py
import os import pandas as pd def create_aggregate_metrics_df( metrics_dfs: dict, metrics: list, save_folder: str = None, save_prefix: str = None ) -> pd.DataFrame: """Create aggregate dataframe with mean and std for each metric across files.""" # Check that all requested metrics exist missing_metrics...
122
4,514
cognee
evals/old/hotpot_qa_24_2025/src/analysis/process_results.py
.py
import os import pandas as pd from analysis.get_results import read_results, validate_folder_results from analysis.analyze_results import create_aggregate_metrics_df def process_results(dir_path: str) -> dict: """Read and validate results from the specified directory.""" # Read results results = read_resu...
183
6,769
cognee
evals/old/hotpot_qa_24_2025/src/modal_apps/modal_qa_benchmark_graphiti.py
.py
import datetime import os import socket import subprocess import time from dataclasses import asdict from pathlib import Path import modal from modal_apps.modal_image import graphiti_image, neo4j_env_dict, neo4j_image APP_NAME = "qa-benchmark-graphiti" VOLUME_NAME = "qa-benchmarks" BENCHMARK_NAME = "graphiti" CORPUS...
180
6,062
cognee
evals/old/hotpot_qa_24_2025/src/modal_apps/modal_qa_benchmark_cognee.py
.py
import asyncio import datetime import os from dataclasses import asdict from pathlib import Path import modal from qa.qa_benchmark_cognee import CogneeConfig, QABenchmarkCognee from modal_apps.modal_image import image APP_NAME = "qa-benchmark-cognee" VOLUME_NAME = "qa-benchmarks" BENCHMARK_NAME = "cognee" QA_PAIRS_F...
119
4,049
cognee
evals/old/hotpot_qa_24_2025/src/modal_apps/modal_qa_benchmark_mem0.py
.py
import asyncio import datetime import os from dataclasses import asdict from pathlib import Path import modal from qa.qa_benchmark_mem0 import Mem0Config, QABenchmarkMem0 from modal_apps.modal_image import image APP_NAME = "qa-benchmark-mem0" VOLUME_NAME = "qa-benchmarks" BENCHMARK_NAME = "mem0" CORPUS_FILE = Path("...
99
2,975
cognee
evals/old/hotpot_qa_24_2025/src/modal_apps/modal_qa_benchmark_lightrag.py
.py
import asyncio import datetime import os from dataclasses import asdict from pathlib import Path import modal from qa.qa_benchmark_lightrag import LightRAGConfig, QABenchmarkLightRAG from modal_apps.modal_image import image APP_NAME = "qa-benchmark-lightrag" VOLUME_NAME = "qa-benchmarks" BENCHMARK_NAME = "lightrag" ...
101
3,099
cognee
evals/old/hotpot_qa_24_2025/src/modal_apps/modal_image.py
.py
import os import modal import dotenv dotenv.load_dotenv() # --- Configuration --- CORPUS_FILE = "hotpot_qa_24_corpus.json" QA_PAIRS_FILE = "hotpot_qa_24_qa_pairs.json" INSTANCE_FILTER_FILE = "hotpot_qa_24_instance_filter.json" # --- Shared Image Definition --- image = ( modal.Image.debian_slim(python_version="...
80
2,365
cognee
evals/old/hotpot_qa_24_2025/src/modal_apps/modal_evaluate_qa.py
.py
import modal from modal_apps.modal_image import image APP_NAME = "volume-reader" VOLUME_NAME = "qa-benchmarks" # Create volume reference volume = modal.Volume.from_name(VOLUME_NAME, create_if_missing=True) app = modal.App(APP_NAME, image=image) @app.function( volumes={f"/{VOLUME_NAME}": volume}, timeout=30...
219
8,244
cognee
evals/old/hotpot_qa_24_2025/src/modal_apps/test_neo4j_server.py
.py
import socket import subprocess import time from pathlib import Path import modal from modal_apps.modal_image import neo4j_env_dict, neo4j_image APP_NAME = "test-neo4j-server" app = modal.App(APP_NAME, secrets=[modal.Secret.from_dotenv()]) @app.function( image=neo4j_image, timeout=3600, cpu=2, me...
99
3,282
cognee
evals/old/hotpot_qa_24_2025/src/qa/run_graphiti_benchmark.py
.py
#!/usr/bin/env python3 """Run Graphiti QA benchmark.""" from qa.qa_benchmark_graphiti import QABenchmarkGraphiti, GraphitiConfig def main(): """Run Graphiti benchmark.""" config = GraphitiConfig( corpus_limit=None, # Small test qa_limit=None, print_results=True, ) benchmark ...
27
573
cognee
evals/old/hotpot_qa_24_2025/src/qa/qa_benchmark_graphiti.py
.py
import asyncio import os from dataclasses import dataclass from datetime import datetime, timezone from typing import Any from dotenv import load_dotenv from langchain_openai import ChatOpenAI from graphiti_core import Graphiti from graphiti_core.nodes import EpisodeType from .qa_benchmark_base import QABenchmarkRAG,...
136
4,729
cognee
evals/old/hotpot_qa_24_2025/src/qa/qa_benchmark_mem0.py
.py
import asyncio from dataclasses import dataclass from typing import Any from dotenv import load_dotenv from openai import OpenAI from mem0 import Memory from .qa_benchmark_base import QABenchmarkRAG, QABenchmarkConfig load_dotenv() @dataclass class Mem0Config(QABenchmarkConfig): """Configuration for Mem0 QA be...
117
3,714
cognee
evals/old/hotpot_qa_24_2025/src/qa/qa_benchmark_cognee.py
.py
import asyncio import os from dataclasses import dataclass from typing import Any, List, Dict, Optional from dotenv import load_dotenv import cognee from cognee.api.v1.search import SearchType from .qa_benchmark_base import QABenchmarkRAG, QABenchmarkConfig from cognee.eval_framework.benchmark_adapters.hotpot_qa_adap...
183
6,439
cognee
evals/old/hotpot_qa_24_2025/src/qa/qa_benchmark_lightrag.py
.py
import asyncio import os from dataclasses import dataclass from typing import Any from dotenv import load_dotenv from lightrag import LightRAG, QueryParam from lightrag.llm.openai import gpt_4o_mini_complete, gpt_4o_complete, openai_embed from lightrag.kg.shared_storage import initialize_pipeline_status from lightrag...
95
2,788
cognee
evals/old/hotpot_qa_24_2025/src/qa/qa_benchmark_base.py
.py
import asyncio import json from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Any, Dict, List, Optional from dotenv import load_dotenv from tqdm import tqdm load_dotenv() @dataclass class QABenchmarkConfig: """Base configuration for QA benchmark pipelines.""" corpus_li...
160
5,307
cognee
working_dir_error_replication/run_subprocess_test.py
.py
""" Run writer and reader in separate subprocesses to test Kuzu locks. """ import subprocess import time import os def main(): print("=== Kuzu Subprocess Lock Test ===") print("Starting writer and reader in separate subprocesses...") print("Writer will hold the database lock, reader should block or fail\...
32
764
graphiti
conftest.py
.py
import os import sys # This code adds the project root directory to the Python path, allowing imports to work correctly when running tests. # Without this file, you might encounter ModuleNotFoundError when trying to import modules from your project, especially when running tests. sys.path.insert(0, os.path.abspath(os....
14
601