repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
cognee
cognee/modules/tools/config.py
.py
"""Configuration for recall tool calls (external database access). Everything here is gated behind ``tool_calls_enabled`` (env ``TOOL_CALLS_ENABLED``), which defaults to **off**: recall never reaches an external database unless a deployment explicitly opts in. """ import json from functools import lru_cache from typi...
83
3,640
cognee
cognee/modules/tools/ingest_skills.py
.py
"""Explicit SKILL.md ingestion for the agentic-skills v1 scope.""" from __future__ import annotations import os from pathlib import Path from types import SimpleNamespace from typing import List, Optional, Tuple, Union from uuid import NAMESPACE_URL, UUID, uuid5 from cognee.modules.engine.models import NodeSet, Skil...
168
5,899
cognee
cognee/modules/tools/builtin/__init__.py
.py
"""Built-in tools registered at import time. Importing this package registers every built-in tool with the registry. """ from cognee.modules.tools.builtin import load_skill as _load_skill # noqa: F401 from cognee.modules.tools.builtin import memory_search as _memory_search # noqa: F401
8
291
cognee
cognee/modules/tools/builtin/load_skill.py
.py
"""Progressive-disclosure primitive: return a skill's procedure body by name. The AgenticRetriever loads only Skill descriptions into the system prompt; the full procedure is retrieved by the LLM calling this tool when it decides a skill is relevant. Active skills for the current turn live in a ContextVar so the handl...
60
2,001
cognee
cognee/modules/tools/builtin/memory_search.py
.py
"""Callable memory search: lets the agent run a fresh triplet lookup mid-loop.""" from typing import Any, Dict from cognee.modules.engine.models import Tool from cognee.modules.graph.utils import resolve_edges_to_text from cognee.modules.retrieval.utils.brute_force_triplet_search import ( brute_force_triplet_sear...
58
1,922
cognee
cognee/modules/tools/text_to_sql/__init__.py
.py
from cognee.modules.tools.text_to_sql.engine import TOOL_NAME, TextToSqlResult, run_text_to_sql from cognee.modules.tools.text_to_sql.write_proposals import ( apply_write_proposal, list_write_proposals, propose_corrections_from_contradictions, propose_sql_write, reject_write_proposal, ) __all__ = [...
20
543
cognee
cognee/modules/tools/text_to_sql/executor.py
.py
"""Rollback-only execution of guarded SQL against an external database. Never commits: the transaction is explicitly marked read-only on Postgres and always rolled back, so even a statement that somehow passed the SQL guard cannot persist a write. """ import base64 from datetime import date, datetime, time from decim...
58
1,965
cognee
cognee/modules/tools/text_to_sql/engine.py
.py
"""Text-to-SQL: natural-language question → guarded SELECT → rows. Ports the generate → execute → feed-errors-back retry loop from ``NaturalLanguageRetriever`` (NL→Cypher) to SQL, with two deliberate differences: an empty result set counts as success (no wasted LLM retries), and exhausted attempts return an explicit e...
182
6,489
cognee
cognee/modules/tools/text_to_sql/write_proposals.py
.py
"""Approval-gated write-back: correction proposals for authorized databases. When cognee determines stored data is inaccurate β€” a ``contradicts`` edge from contradiction detection, or an explicit instruction β€” this module drafts an UPDATE with the LLM, validates it (single UPDATE, mandatory WHERE, table allowlist), dr...
404
15,464
cognee
cognee/modules/tools/text_to_sql/write_guard.py
.py
"""UPDATE-only validation for approval-gated write proposals. Same philosophy as :mod:`sql_guard` (reject fast, feed errors back), but the statement shape is inverted: exactly one UPDATE, a **mandatory WHERE clause**, and an extractable target table so per-connection ``allowed_tables`` can be enforced. Everything else...
88
2,795
cognee
cognee/modules/tools/text_to_sql/engine_factory.py
.py
"""Async engines for authorized external databases, read-only by construction. Deliberately NOT :class:`SQLAlchemyAdapter`: that adapter applies write PRAGMAs (``journal_mode=WAL``) on every SQLite connection and its ``execute_query`` commits β€” both wrong for a read-only external database. These engines carry read-onl...
147
5,937
cognee
cognee/modules/tools/text_to_sql/sql_guard.py
.py
"""SELECT-only validation for LLM-generated SQL. The guard is the first of three read-only layers (guard β†’ read-only connection + rollback-only executor β†’ SELECT-only DB role). It exists to reject bad statements fast and feed a useful error back into the retry loop β€” the connection-level read-only enforcement is what ...
114
3,624
cognee
cognee/modules/tools/models/ToolConnection.py
.py
from datetime import datetime, timezone from typing import Optional from uuid import UUID, uuid4 from sqlalchemy import JSON, DateTime, LargeBinary, SmallInteger, String, UniqueConstraint from sqlalchemy import UUID as SAUUID from sqlalchemy.orm import Mapped, mapped_column from cognee.infrastructure.databases.relati...
60
2,556
cognee
cognee/modules/tools/models/__init__.py
.py
from .ToolConnection import ToolConnection from .ToolWriteProposal import ToolWriteProposal __all__ = ["ToolConnection", "ToolWriteProposal"]
5
143
cognee
cognee/modules/tools/models/ToolWriteProposal.py
.py
from datetime import datetime, timezone from typing import Optional from uuid import UUID, uuid4 from sqlalchemy import JSON, DateTime, Integer, String, Text from sqlalchemy import UUID as SAUUID from sqlalchemy.orm import Mapped, mapped_column from cognee.infrastructure.databases.relational.ModelBase import Base c...
60
2,660
cognee
cognee/modules/migration/formats.py
.py
"""Pure format emitters for graph export. Each emitter takes the ``get_graph_data()`` shapes β€” nodes as ``(node_id, properties)`` tuples, edges as ``(source_id, target_id, relationship_name, properties)`` tuples β€” and writes a file. No database access here; emitters are pure and unit-testable. """ import json from pa...
145
5,785
cognee
cognee/modules/migration/export.py
.py
"""Export a Cognee dataset's knowledge graph to portable formats. Formats: - ``pydantic`` β€” a :class:`GraphSnapshot` of typed DataPoint instances (the Pydantic-native export: real ``Entity``/``DocumentChunk``/custom-model objects, losslessly serializable via ``model_dump_json``) - ``cogx`` β€” a COGX archive dir...
310
12,279
cognee
cognee/modules/migration/__init__.py
.py
from .cogx import ( COGX_VERSION, COGXDocument, COGXEntity, COGXEpisode, COGXFact, COGXManifest, COGXMemory, COGXMemoryBlock, COGXRawNode, COGXRecord, COGXScope, COGXTurn, read_archive, read_manifest, ) from .archive import ARCHIVE_SUFFIX, find_archive_root, pack_...
79
1,716
cognee
cognee/modules/migration/snapshot.py
.py
"""Pydantic-native graph export: get your memory back as typed objects. ``cognee.export(..., format="pydantic")`` returns a :class:`GraphSnapshot` β€” a Pydantic model whose ``nodes`` are rehydrated into the same DataPoint subclasses that produced them (``Entity``, ``DocumentChunk``, your custom models, ...). Because Da...
272
10,773
cognee
cognee/modules/migration/cogx.py
.py
"""COGX β€” the Cognee eXchange format for portable memory. COGX is the hub format for memory migration: importers translate external providers (Mem0, Zep/Graphiti, Letta, ...) into COGX records, a single loader ingests COGX into Cognee, and a single dumper exports Cognee datasets into a COGX archive that emitters can t...
352
12,981
cognee
cognee/modules/migration/import_source.py
.py
"""Orchestrate importing a MemorySource into Cognee. Called by ``cognee.remember()`` when it receives a :class:`MemorySource`. Heavy Cognee imports happen lazily inside the function to avoid import cycles (remember -> migration -> remember). Two execution shapes: - **streaming** (preserve mode + replayable source): ...
540
21,765
cognee
cognee/modules/migration/loader.py
.py
"""Translate COGX records into Cognee ingestion inputs. Two targets, selected by the source's import mode: - **data items** (``re-derive``): textual records become :class:`DataItem`s with deterministic ``data_id``s, fed through the normal ``add + cognify`` path so Cognee's own extraction builds the graph. - **gra...
650
26,562
cognee
cognee/modules/migration/archive.py
.py
"""Pack and unpack COGX archive directories as ``.tar.gz`` files for transport. A COGX archive is a directory (see :mod:`cognee.modules.migration.cogx`); shipping one over HTTP requires a single file. ``pack_archive`` and ``unpack_archive`` are the two halves of that transport encoding, used by ``cognee.push()`` on th...
122
5,116
cognee
cognee/modules/migration/sources/letta.py
.py
"""Letta (MemGPT) agent-file source. Reads a Letta Agent File (``.af``, a JSON serialization of agents) and yields: - core memory blocks -> :class:`COGXMemoryBlock` - message history -> one :class:`COGXEpisode` per agent - archival memory -> one :class:`COGXDocument` per passage The parser is tolerant of key-n...
156
6,213
cognee
cognee/modules/migration/sources/__init__.py
.py
from .base import MemorySource, IMPORT_MODES from .cogx_archive import COGXArchiveSource from .langmem import LangMemSource from .letta import LettaSource from .mem0 import Mem0Source from .zep import GraphitiSource, ZepSource __all__ = [ "MemorySource", "IMPORT_MODES", "COGXArchiveSource", "LangMemSou...
18
404
cognee
cognee/modules/migration/sources/mem0.py
.py
"""Mem0 memory source. Reads a Mem0 export and yields COGX memory records. Accepts the shapes produced by the Mem0 platform export API and by the OSS ``get_all()`` call: - a plain JSON list of memory objects - ``{"results": [...]}`` / ``{"memories": [...]}`` wrappers - already-parsed Python lists/dicts (for live-API ...
83
3,482
cognee
cognee/modules/migration/sources/zep.py
.py
"""Zep / Graphiti memory source. Reads a JSON export of a Zep or Graphiti (OSS) knowledge graph and yields: - episodes (verbatim ingested content) -> :class:`COGXEpisode` - entity nodes -> :class:`COGXEntity` - relation edges ("facts") -> :class:`COGXFact` carrying the bi-tempo...
139
5,941
cognee
cognee/modules/migration/sources/langmem.py
.py
"""LangMem memory source. Reads a LangMem export/dump and yields COGX memory records. Accepts the shapes produced by LangMem memory storage: - a plain JSON list of memory objects - ``{"memories": [...]}`` / ``{"results": [...]}`` / ``{"data": [...]}`` wrappers - already-parsed Python lists/dicts (for live-API integra...
97
3,808
cognee
cognee/modules/migration/sources/cogx_archive.py
.py
"""COGX archive source: re-import an archive produced by ``cognee.export()``. This is the restore half of backup/restore and the receiving end of Cognee-to-Cognee instance migration. """ from pathlib import Path from typing import AsyncIterator, Union from cognee.modules.migration.cogx import ( COGXRecord, r...
53
2,070
cognee
cognee/modules/migration/sources/base.py
.py
"""Base class for memory-migration sources. A :class:`MemorySource` adapts an external memory system (or an export file produced by one) into a stream of COGX records. ``cognee.remember()`` accepts any MemorySource instance and routes it through the migration loader, so await cognee.remember(Mem0Source("mem0_expo...
72
3,283
cognee
cognee/modules/engine/operations/setup.py
.py
from cognee.infrastructure.databases.relational import ( create_db_and_tables as create_relational_db_and_tables, ) from cognee.infrastructure.databases.vector.pgvector import ( create_db_and_tables as create_pgvector_db_and_tables, ) async def setup(): """ Set up the necessary databases and tables. ...
24
642
cognee
cognee/modules/engine/utils/generate_timestamp_datapoint.py
.py
from datetime import datetime, timezone from cognee.modules.engine.models import Interval, Timestamp, Event from cognee.modules.engine.utils import generate_node_id def generate_timestamp_datapoint(ts: Timestamp) -> Timestamp: """ Generates a normalized Timestamp datapoint from a given Timestamp model. T...
52
1,722
cognee
cognee/modules/engine/utils/generate_edge_object_id.py
.py
from uuid import NAMESPACE_OID, uuid5 def generate_edge_object_id( source_node_id: str, target_node_id: str, relationship_name: str ) -> str: """ Deterministic, stable id for a single edge (source, target, relationship). Used for feedback mapping and stored on edges in the graph DB as edge_object_id. ...
18
572
cognee
cognee/modules/engine/utils/generate_edge_name.py
.py
def generate_edge_name(name: str) -> str: return name.lower().replace(" ", "_").replace("'", "")
3
101
cognee
cognee/modules/engine/utils/generate_event_datapoint.py
.py
from cognee.modules.engine.models import Interval, Event from cognee.modules.engine.utils.generate_timestamp_datapoint import generate_timestamp_datapoint def generate_event_datapoint(event) -> Event: """ Generates an Event datapoint from a given event model, including temporal metadata if available. The...
47
2,046
cognee
cognee/modules/engine/utils/generate_node_name.py
.py
def generate_node_name(name: str) -> str: return name.lower().replace("'", "")
3
83
cognee
cognee/modules/engine/utils/generate_edge_id.py
.py
from uuid import NAMESPACE_OID, UUID, uuid5 def generate_edge_id(edge_id: str) -> UUID: """Stable dedup slug for relational-ledger EDGE rows (upsert_edges only). NOT an EdgeType point id β€” those are EdgeType.id_for(text) (namespaced by the class, like every identity-bearing DataPoint). This bare derivati...
14
583
cognee
cognee/modules/engine/models/Entity.py
.py
from typing import List, Optional from cognee.infrastructure.engine import DataPoint from cognee.modules.engine.models.EntityType import EntityType class Entity(DataPoint): name: str is_a: Optional[EntityType] = None description: str relations: List[tuple] = [] # Optional truth-alignment fields; ...
21
873
cognee
cognee/modules/engine/models/Timestamp.py
.py
from pydantic import Field from cognee.infrastructure.engine import DataPoint class Timestamp(DataPoint): time_at: int = Field(...) year: int = Field(...) month: int = Field(...) day: int = Field(...) hour: int = Field(...) minute: int = Field(...) second: int = Field(...) timestamp_st...
14
340
cognee
cognee/modules/engine/models/Tool.py
.py
from typing import Annotated, Any, Dict, Literal, Optional from uuid import UUID from pydantic import Field from cognee.infrastructure.engine import DataPoint, Embeddable, LLMContext, Dedup PermissionVerb = Literal["read", "write", "execute", "delete", "share"] class Tool(DataPoint): """ Callable action a...
37
1,570
cognee
cognee/modules/engine/models/Interval.py
.py
from pydantic import Field from cognee.infrastructure.engine import DataPoint from cognee.modules.engine.models.Timestamp import Timestamp class Interval(DataPoint): time_from: Timestamp = Field(...) time_to: Timestamp = Field(...)
9
242
cognee
cognee/modules/engine/models/TableRow.py
.py
from cognee.infrastructure.engine import DataPoint from cognee.modules.engine.models.TableType import TableType from typing import Optional class TableRow(DataPoint): name: str description: str properties: str metadata: dict = {"index_fields": ["properties"]}
12
279
cognee
cognee/modules/engine/models/SkillImprovementProposal.py
.py
from __future__ import annotations from typing import List, Optional from pydantic import Field from cognee.infrastructure.engine import DataPoint from cognee.modules.engine.models.Skill import Skill from cognee.modules.engine.models.SkillRun import SkillRun class SkillImprovementProposal(DataPoint): """Review...
35
976
cognee
cognee/modules/engine/models/Skill.py
.py
from typing import Annotated, List from pydantic import Field from cognee.infrastructure.engine import DataPoint, Dedup, Embeddable, LLMContext class Skill(DataPoint): """A dataset-scoped procedural playbook loaded by the agentic retriever.""" name: Annotated[str, Dedup()] description: str = "" pro...
42
1,328
cognee
cognee/modules/engine/models/DltColumn.py
.py
from cognee.modules.engine.models.ColumnValue import ColumnValue class DltColumn(ColumnValue): """A shared cell-value node emitted by the DLT pipeline. Subclasses ColumnValue (the relational-migration pipeline's value node) so generic machinery treats both as one family via isinstance, while the grap...
13
521
cognee
cognee/modules/engine/models/SkillRun.py
.py
from typing import Any, Dict, List, Optional from pydantic import Field from cognee.infrastructure.engine import DataPoint UNSCORED_SKILL_RUN_SCORE = 0.5 class ToolCall(DataPoint): """A single tool invocation within a skill run.""" tool_name: str tool_input: Optional[Dict[str, Any]] = None tool_ou...
72
1,847
cognee
cognee/modules/engine/models/ColumnValue.py
.py
from cognee.infrastructure.engine import DataPoint class ColumnValue(DataPoint): name: str description: str properties: str metadata: dict = {"index_fields": ["properties"]}
10
193
cognee
cognee/modules/engine/models/Triplet.py
.py
from cognee.infrastructure.engine import DataPoint class Triplet(DataPoint): text: str from_node_id: str to_node_id: str metadata: dict = {"index_fields": ["text"]}
10
184
cognee
cognee/modules/engine/models/node_set.py
.py
from cognee.infrastructure.engine import DataPoint class NodeSet(DataPoint): """NodeSet data point.""" name: str
8
124
cognee
cognee/modules/engine/models/TableType.py
.py
from cognee.infrastructure.engine import DataPoint class TableType(DataPoint): name: str description: str metadata: dict = {"index_fields": ["name"]}
9
165
cognee
cognee/modules/engine/models/EntityType.py
.py
from typing import List from cognee.infrastructure.engine import DataPoint class EntityType(DataPoint): name: str description: str relations: List[tuple] = [] # identity_fields makes the id deterministic and namespaced by class # (``EntityType:<name>``) when constructed without an explicit id β€” t...
14
492
cognee
cognee/modules/engine/models/Event.py
.py
from typing import Optional, Any from pydantic import SkipValidation from cognee.infrastructure.engine import DataPoint from cognee.modules.engine.models.Timestamp import Timestamp from cognee.modules.engine.models.Interval import Interval class Event(DataPoint): name: str description: Optional[str] = None ...
17
518
cognee
cognee/modules/visualization/subgraph_data.py
.py
"""Bounded subgraph selection for graph visualization. ``visualize_graph()`` renders a bounded subgraph by default instead of the whole graph. Seeds are resolved by priority β€” explicit node ids, a recall/search result's graph provenance, or a query string β€” and, when none of those are given, the highest-degree nodes s...
263
9,785
cognee
cognee/modules/visualization/session_events.py
.py
"""Collect memory-operation events from the session layer for the Memory tab. The "operation bench": searches run against the backend (with a session) record which graph elements produced each answer (``used_graph_element_ids``), and feedback entries record how those answers were rated. This module turns that history ...
142
5,860
cognee
cognee/modules/visualization/semantic_clusters.py
.py
"""Cluster node embeddings and precompute nearest neighbors for the semantic map. Clustering runs on the *full-dimensional* embeddings (not the 2-D projection), so groupings reflect real semantic structure rather than a lossy layout. Output feeds the ``__SEMANTIC_CLUSTERS__`` data token: per-node cluster id + top-5 co...
172
6,693
cognee
cognee/modules/visualization/operations_catalog.py
.py
"""Catalog of cognee operations that transform the knowledge graph. This is the single source of truth for the schema view's "transformations" impact-layer: it declares, per operation, what schema types/node_sets it **produces**, **enriches**, **modifies**, or **removes**. It is corroborated at render time by the live...
201
7,282
cognee
cognee/modules/visualization/cognee_network_visualization.py
.py
"""Cognee graph visualization β€” orchestrator. Single entry point ``cognee_network_visualization(graph_data, ...)``: 1. Preprocesses the raw graph into a renderer-facing snapshot (``preprocessor.preprocess``). 2. Reads the HTML shell from ``template.html``. 3. Asks each view module (``views/*``) and layout ...
297
13,300
cognee
cognee/modules/visualization/preprocessor.py
.py
"""Visualization preprocessor. Single Python entry point that turns raw ``(nodes_data, edges_data)`` from the graph adapter into a fully-enriched ``PreprocessedGraph`` ready for the HTML/JS renderer to consume. The renderer should *only* read fields produced here β€” synthesising stage or bundling information in JavaSc...
1,406
56,197
cognee
cognee/modules/visualization/embedding_join.py
.py
"""Join graph nodes to their stored embeddings β€” the plumbing behind the semantic map. ``visualize_graph()`` forwards only nodes/links; no embeddings ride along. This module fetches the embedding for each node by looking it up in the vector store, reusing the fact that a graph node id is stored verbatim as the vector-...
195
7,927
cognee
cognee/modules/visualization/layouts/__init__.py
.py
"""Layout modules for the cognee graph visualization. Each submodule exports an ``emit_js(preprocessed) -> str`` function that returns a JavaScript chunk implementing a layout strategy. The orchestrator injects the chunk into the main story-view script block via a ``__PIPELINE_LAYOUT_JS__`` placeholder. """
8
310
cognee
cognee/modules/visualization/layouts/semantic_layout.py
.py
"""Semantic layout: project node embeddings to 2-D pinned positions. Given ``{node_id: vector}`` from ``embedding_join.fetch_node_embeddings`` and the graph's links, this computes one 2-D coordinate per node so semantically similar nodes land near each other. Positions are a deterministic pure function of the inputs β€”...
207
8,246
cognee
cognee/modules/visualization/layouts/pipeline_layout.py
.py
"""Pipeline layout: bin nodes by ``stage``, place left-to-right. Phase 1 ships an empty stub — the legacy ``computeRankedLayout`` JS function (inside the story view's IIFE) continues to provide the L→R "Flow" layout, which now uses the real ``topological_rank`` stamped in Phase 1a. Phase 1d adds a true Story-view lay...
18
623
cognee
cognee/modules/visualization/views/story_view.py
.py
"""Story view: the main canvas-based graph renderer. This is the largest JS chunk β€” the canvas/quadtree/minimap/FPS rendering loop, ranked/organic layouts, label budget, hover/search/inspector wiring, density layers, and all interaction state. Phase 1 ships the existing renderer verbatim. The actual Story view behavi...
20
649
cognee
cognee/modules/visualization/views/semantic_map.py
.py
"""Semantic view: the meaning-space scatter tab. Reads the sibling ``semantic_map.js`` chunk. The chunk carries the ``__SEMANTIC_CLUSTERS__`` token that the orchestrator substitutes with the clustering payload (positions arrive via the layout's ``__SEMANTIC_POSITIONS__`` token). Both fall back to ``null`` when there a...
18
586
cognee
cognee/modules/visualization/views/schema_view.py
.py
"""Schema view: D3-based schema graph visualization. Renders the type-graph or DLT-schema graph in the Schema tab. Reads ``__SCHEMA_DATA__`` and ``__SCHEMA_GRAPH_DATA__`` tokens that the orchestrator substitutes with the preprocessor's schema output. Phase 1 ships the existing renderer verbatim β€” extracted from the o...
20
639
cognee
cognee/modules/visualization/views/__init__.py
.py
"""View modules for the cognee graph visualization. Each submodule exports an ``emit_js(preprocessed) -> str`` function that returns a JavaScript chunk. The orchestrator (``cognee_network_visualization.py``) concatenates the chunks and substitutes them into ``template.html`` via ``__TOKEN__`` placeholders. The JS con...
11
456
cognee
cognee/modules/visualization/views/memory_map.py
.py
"""Memory view: the memory-map tab. Reads the sibling ``memory_map.js`` chunk. The chunk carries the ``__MEMORY_DATA__`` and ``__SEARCH_EVENTS__`` tokens that the orchestrator substitutes with the preprocessor's ``memory_map`` payload and the optional ``search_events`` argument. STEP 1 ships a stub JS chunk (token wi...
21
672
cognee
cognee/modules/visualization/views/inspector.py
.py
"""Inspector view: schema type side panel (PR3). Renders the JS that populates ``#schema-side-panel`` when a schema type box is clicked. The panel shows the type name + true instance count, a bounded set of sample-name chips with a "Show all" drill-down, and the per-type outgoing relationship distribution. A "Highligh...
23
892
cognee
cognee/modules/visualization/views/ui_chrome.py
.py
"""UI chrome: theme toggle + tab switching (Graph / Schema). Small, generic UI plumbing that lives outside the canvas renderer's IIFE. """ import os _JS_PATH = os.path.join(os.path.dirname(__file__), "ui_chrome.js") def emit_js(_preprocessed=None) -> str: with open(_JS_PATH, "r", encoding="utf-8") as f: ...
14
338
cognee
cognee/modules/search/exceptions/exceptions.py
.py
from cognee.exceptions import ( CogneeValidationError, ) from fastapi import status class UnsupportedSearchTypeError(CogneeValidationError): def __init__( self, search_type: str, name: str = "UnsupportedSearchTypeError", status_code: int = status.HTTP_400_BAD_REQUEST, ): ...
16
431
cognee
cognee/modules/search/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 UnsupportedSearchTypeError
8
172
cognee
cognee/modules/search/operations/get_results.py
.py
from uuid import UUID from sqlalchemy import select from cognee.infrastructure.databases.relational import get_relational_engine from ..models.Result import Result async def get_results(user_id: UUID, limit: int = 10) -> list[Result]: db_engine = get_relational_engine() async with db_engine.get_async_session...
21
608
cognee
cognee/modules/search/operations/get_history.py
.py
from typing import Any from uuid import UUID from sqlalchemy import literal, select from cognee.infrastructure.databases.relational import get_relational_engine from ..models.Query import Query from ..models.Result import Result async def get_history(user_id: UUID, limit: int = 10) -> list[dict[str, Any]]: db_...
42
1,224
cognee
cognee/modules/search/operations/log_query.py
.py
import os from typing import Optional from uuid import UUID from cognee.infrastructure.databases.relational import get_relational_engine from ..models.Query import Query _LOG_ENABLED = os.getenv("COGNEE_LOG_SEARCH_HISTORY", "true").lower() in ("true", "1", "yes") async def log_query( query_text: str, query_t...
32
762
cognee
cognee/modules/search/operations/get_queries.py
.py
from uuid import UUID from sqlalchemy import select from cognee.infrastructure.databases.relational import get_relational_engine from ..models.Query import Query async def get_queries(user_id: UUID, limit: int) -> list[Query]: db_engine = get_relational_engine() async with db_engine.get_async_session() as se...
21
597
cognee
cognee/modules/search/operations/select_search_type.py
.py
from cognee.infrastructure.llm.prompts import read_query_prompt from cognee.modules.search.types import SearchType from cognee.shared.logging_utils import get_logger from cognee.infrastructure.llm.LLMGateway import LLMGateway logger = get_logger("SearchTypeSelector") async def select_search_type( query: str, ...
54
2,103
cognee
cognee/modules/search/operations/log_search_history.py
.py
from typing import Any, List, Optional from uuid import UUID from .log_query import log_query from .log_result import log_result def _completion_of(payload: Any) -> Optional[str]: """The text a user saw, preferring the completion over raw context.""" for attribute in ("completion", "context"): value ...
42
1,690
cognee
cognee/modules/search/operations/log_result.py
.py
import os from typing import Optional from uuid import UUID from cognee.infrastructure.databases.relational import get_relational_engine from ..models.Result import Result _LOG_ENABLED = os.getenv("COGNEE_LOG_SEARCH_HISTORY", "true").lower() in ("true", "1", "yes") async def log_result( query_id: UUID, resul...
32
762
cognee
cognee/modules/search/utils/transform_triplets_to_graph.py
.py
from typing import List from cognee.modules.graph.cognee_graph.CogneeGraphElements import Edge def transform_triplets_to_graph(input_triplets: List[Edge]): nodes = {} edges = {} for triplet in input_triplets: nodes[triplet.node1.id] = { "id": triplet.node1.id, "label": tr...
39
1,253
cognee
cognee/modules/search/utils/transform_insights_to_graph.py
.py
from typing import Dict, List, Tuple def transform_insights_to_graph(input_triplets: List[Tuple[Dict, Dict, Dict]]): nodes = {} edges = {} for triplet in input_triplets: nodes[triplet[0]["id"]] = { "id": triplet[0]["id"], "label": triplet[0]["name"] if "name" in triplet[0]...
29
939
cognee
cognee/modules/search/methods/get_retriever_output.py
.py
from cognee.infrastructure.databases.graph import get_graph_engine from cognee.modules.retrieval.session_aware_completion import run_session_aware_completion from cognee.modules.search.methods.get_search_type_retriever_instance import ( get_search_type_retriever_instance, ) from cognee.modules.search.models.SearchR...
62
2,321
cognee
cognee/modules/search/methods/get_search_type_retriever_instance.py
.py
import os from typing import Callable, List, Optional, Type, Tuple from cognee.base_config import get_base_config from cognee.modules.retrieval.base_retriever import BaseRetriever from cognee.modules.engine.models.node_set import NodeSet from cognee.modules.retrieval.triplet_retriever import TripletRetriever from cog...
404
18,848
cognee
cognee/modules/search/methods/search.py
.py
import asyncio from typing import Any, List, Optional, Tuple, Type, Union from uuid import UUID from cognee import __version__ as cognee_version from cognee.base_config import get_base_config from cognee.context_global_variables import ( backend_access_control_enabled, set_database_global_context_variables, ) ...
461
19,521
cognee
cognee/modules/search/models/Query.py
.py
from uuid import uuid4 from datetime import datetime, timezone from sqlalchemy import Column, DateTime, String, UUID from cognee.infrastructure.databases.relational import Base class Query(Base): __tablename__ = "queries" id = Column(UUID, primary_key=True, default=uuid4) text = Column(String) query...
26
919
cognee
cognee/modules/search/models/SearchResultPayload.py
.py
from uuid import UUID from typing import Optional, Any, List, Union from pydantic import BaseModel, ConfigDict, field_serializer from pydantic.alias_generators import to_camel from cognee.modules.search.types.SearchType import SearchType class SearchResultPayload(BaseModel): """Result payload from retriever class...
81
3,029
cognee
cognee/modules/search/models/Result.py
.py
from datetime import datetime, timezone from uuid import uuid4 from sqlalchemy import Column, DateTime, Text, UUID from cognee.infrastructure.databases.relational import Base class Result(Base): __tablename__ = "results" id = Column(UUID, primary_key=True, default=uuid4) value = Column(Text) query_i...
24
795
cognee
cognee/modules/search/types/SearchType.py
.py
from enum import Enum class SearchType(str, Enum): SUMMARIES = "SUMMARIES" CHUNKS = "CHUNKS" RAG_COMPLETION = "RAG_COMPLETION" HYBRID_COMPLETION = "HYBRID_COMPLETION" TRIPLET_COMPLETION = "TRIPLET_COMPLETION" GRAPH_COMPLETION = "GRAPH_COMPLETION" GRAPH_COMPLETION_DECOMPOSITION = "GRAPH_COM...
24
825
cognee
cognee/modules/search/types/SearchResult.py
.py
from uuid import UUID from pydantic import BaseModel from typing import Any, Optional class SearchResultDataset(BaseModel): id: UUID name: str class SearchResult(BaseModel): search_result: Any dataset_id: Optional[UUID] dataset_name: Optional[str]
15
272
cognee
cognee/modules/observability/get_observe.py
.py
import functools from cognee.base_config import get_base_config from .observers import Observer from .exceptions import UnsupportedObserverError # Cap span input/output like the DB adapters cap query text (redact_secrets(query[:500])). _MAX_OBSERVED_CHARS = 8000 def _set_generation_attributes(span, adapter, func, ...
240
9,180
cognee
cognee/modules/observability/logs.py
.py
"""OpenTelemetry log bridge for Cognee. Bridges Python's standard logging to OTel LogRecords so log entries from the core memory operations appear in any connected OTel backend (Grafana, Dash0, Langfuse, etc.). Call setup_log_bridge() once during application startup alongside setup_tracing() / setup_metrics(). """ i...
154
5,184
cognee
cognee/modules/observability/__init__.py
.py
from typing import Optional from contextlib import contextmanager from .trace_context import ( enable_tracing, disable_tracing, is_tracing_enabled, get_last_trace, get_all_traces, clear_traces, ) from .tracing import ( CogneeTrace, redact_secrets, get_tracer, COGNEE_DB_SYSTEM, ...
119
3,116
cognee
cognee/modules/observability/tracing.py
.py
"""OpenTelemetry-native tracing for Cognee. Provides CogneeSpanExporter (in-memory span buffer), setup_tracing(), get_tracer(), CogneeTrace, semantic attribute constants, and redaction. """ import os import re import threading from collections import defaultdict from typing import Optional, Sequence try: from op...
462
17,103
cognee
cognee/modules/observability/metrics.py
.py
"""OpenTelemetry metrics for Cognee β€” memory-semconv v0.1.0. Provides setup_metrics(), get_meter(), and pre-built instruments for the core memory operations: store, retrieve, process, and delete. All instruments are created lazily; if the OTel SDK is not installed or metrics have not been set up, every call is a no-o...
337
10,925
cognee
cognee/modules/observability/trace_context.py
.py
"""Public tracing API: enable/disable tracing and retrieve traces.""" import os from typing import Optional from cognee.modules.observability.tracing import ( CogneeTrace, setup_tracing, shutdown_tracing, get_exporter, ) _tracing_enabled: bool = False def enable_tracing(console_output: bool = False...
124
3,673
cognee
cognee/modules/observability/observers.py
.py
from enum import Enum class Observer(str, Enum): """Monitoring tools""" NONE = "none" LLMLITE = "llmlite" LANGSMITH = "langsmith"
10
149
cognee
cognee/modules/observability/exceptions/exceptions.py
.py
from cognee.exceptions import CogneeConfigurationError from fastapi import status class UnsupportedObserverError(CogneeConfigurationError): """ Raised when an unsupported observer (monitoring tool) is specified in the configuration. """ def __init__( self, observer: str, name:...
18
572
cognee
cognee/modules/observability/exceptions/__init__.py
.py
from .exceptions import UnsupportedObserverError __all__ = ["UnsupportedObserverError"]
4
89
cognee
cognee/modules/cognify/rollback.py
.py
from typing import Any, Optional from uuid import UUID from sqlalchemy import and_, delete, distinct, select from sqlalchemy.orm import aliased, attributes as orm_attributes from cognee.context_global_variables import multi_user_support_possible from cognee.infrastructure.databases.relational import get_relational_en...
266
10,102
cognee
cognee/modules/cognify/estimator.py
.py
"""Dry-run token and cost estimation for the default cognify pipeline. Estimates the two LLM-heavy stages β€” structured graph extraction and chunk summarization β€” without making LLM calls, ingesting data, or writing graph results. Reuses the real pipeline pieces (document classifiers, chunker, prompt templates, graph-m...
599
22,671
cognee
cognee/modules/cognify/config.py
.py
from functools import lru_cache from pydantic_settings import BaseSettings, SettingsConfigDict from cognee.shared.data_models import DefaultContentPrediction, SummarizedContent from typing import Optional import os class CognifyConfig(BaseSettings): classification_model: object = DefaultContentPrediction summ...
39
1,635