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/api/v1/skills/list_skills.py | .py | """List / fetch dataset-scoped Skill nodes for UI consumption.
Reads the knowledge graph scoped to one dataset and returns Skill nodes with
their publisher/provenance metadata. Uses the indexed ``get_nodes_by_type``
lookup (via ``resolve_skills``) and only falls back to a full graph scan when a
backend does not suppor... | 198 | 7,450 |
cognee | cognee/api/v1/skills/routers/__init__.py | .py | from .get_skills_router import get_skills_router
__all__ = ["get_skills_router"]
| 4 | 82 |
cognee | cognee/api/v1/skills/routers/get_skills_router.py | .py | """HTTP router for listing, fetching and toggling dataset-scoped skills.
Exposes the skills SDK helpers over HTTP with explicit response schemas and
caller-scoped authorization, mirroring the schema-inventory router.
"""
from typing import Optional
from uuid import UUID
from fastapi import APIRouter, Depends, Query
... | 248 | 9,877 |
cognee | cognee/api/v1/report/report.py | .py | from pathlib import Path
from typing import List, Optional, Union
from cognee.context_global_variables import set_database_global_context_variables
from cognee.modules.data.methods import get_authorized_existing_datasets
from cognee.modules.users.methods import get_default_user
from cognee.modules.users.models.User im... | 74 | 2,822 |
cognee | cognee/api/v1/sync/__init__.py | .py | from .sync import (
sync,
SyncResponse,
LocalFileInfo,
CheckMissingHashesRequest,
CheckHashesDiffResponse,
PruneDatasetRequest,
)
__all__ = [
"sync",
"SyncResponse",
"LocalFileInfo",
"CheckMissingHashesRequest",
"CheckHashesDiffResponse",
"PruneDatasetRequest",
]
| 18 | 313 |
cognee | cognee/api/v1/sync/sync.py | .py | import io
import os
import uuid
import asyncio
import aiohttp
from pydantic import BaseModel
from typing import List, Optional
from datetime import datetime, timezone
from dataclasses import dataclass
from cognee.api.v1.cognify import cognify
from cognee.infrastructure.files.storage import get_file_storage
from cogne... | 909 | 35,438 |
cognee | cognee/api/v1/sync/routers/__init__.py | .py | from .get_sync_router import get_sync_router
__all__ = ["get_sync_router"]
| 4 | 76 |
cognee | cognee/api/v1/sync/routers/get_sync_router.py | .py | from uuid import UUID
from typing import Optional, List
from fastapi import APIRouter, Depends
from fastapi.responses import JSONResponse
from cognee.api.DTO import InDTO
from cognee.modules.users.models import User
from cognee.modules.users.methods import get_authenticated_user
from cognee.modules.users.permissions.... | 245 | 9,953 |
cognee | cognee/api/v1/delete/__init__.py | .py | from uuid import UUID
from typing import Optional
from deprecated import deprecated
from cognee.api.v1.datasets import datasets
from cognee.modules.users.models import User
@deprecated(
reason="cognee.delete is deprecated. Use `datasets.delete_data` instead.", version="0.3.9"
)
async def delete(data_id: UUID, d... | 40 | 1,305 |
cognee | cognee/api/v1/delete/routers/get_delete_router.py | .py | from uuid import UUID
from deprecated import deprecated
from fastapi import Depends
from fastapi.responses import JSONResponse
from fastapi import APIRouter
from cognee.shared.logging_utils import get_logger
from cognee.modules.users.models import User
from cognee.modules.users.methods import get_authenticated_user
fr... | 72 | 2,355 |
cognee | cognee/api/v1/remember/remember.py | .py | import asyncio
import time
from pathlib import Path
from uuid import UUID
from typing import Union, BinaryIO, List, Optional, Any, Literal, TYPE_CHECKING
try:
from typing import Unpack
except ImportError:
from typing_extensions import Unpack
from typing_extensions import TypedDict
if TYPE_CHECKING:
from ... | 1,320 | 51,585 |
cognee | cognee/api/v1/remember/routers/get_remember_router.py | .py | import json
from uuid import UUID
from fastapi import APIRouter, HTTPException
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from fastapi import Form, File, UploadFile as UF, Depends
from typing import List, Optional, Union, Literal, Annotated
from pydantic import BaseModel, ... | 557 | 25,305 |
cognee | cognee/api/v1/validate/__init__.py | .py | from .validate import (
validate,
ValidationReport,
ValidationIssue,
ValidationStatus,
IssueSeverity,
IssueType,
)
| 9 | 139 |
cognee | cognee/api/v1/validate/validate.py | .py | """Knowledge-graph integrity checker for cognee.
``cognify()`` writes each node's id as a primary key in up to three stores at
once (graph, vector, relational — see
``modules/migrations/versions/namespace_entity_type_node_ids.py``, which exists
because those three drifted apart once already: topoteretes/cognee#2515). ... | 266 | 10,696 |
cognee | cognee/api/v1/validate/routers/get_validate_router.py | .py | from typing import List
from fastapi import APIRouter, Depends, Query
from fastapi.responses import JSONResponse
from typing_extensions import Annotated
from cognee.api.v1.validate.validate import ValidationReport, ValidationStatus, validate
from cognee.modules.data.constants import DEFAULT_DATASET_NAME
from cognee.m... | 49 | 1,893 |
cognee | cognee/api/v1/ui/node_setup.py | .py | import os
import platform
import subprocess
import tempfile
from pathlib import Path
import requests
from cognee.shared.logging_utils import get_logger
logger = get_logger()
def get_nvm_dir() -> Path:
"""
Get the nvm directory path following standard nvm installation logic.
Uses XDG_CONFIG_HOME if set,... | 361 | 13,714 |
cognee | cognee/api/v1/ui/ui.py | .py | import os
import platform
import signal
import socket
import subprocess
import threading
import time
import webbrowser
import zipfile
import requests
from pathlib import Path
from typing import Callable, Optional, Tuple, List
import tempfile
import shutil
from cognee.shared.logging_utils import get_logger
from cognee.... | 771 | 29,731 |
cognee | cognee/api/v1/ui/npm_utils.py | .py | import platform
import subprocess
from pathlib import Path
from typing import List
from cognee.shared.logging_utils import get_logger
from .node_setup import get_nvm_sh_path
logger = get_logger()
def run_npm_command(cmd: List[str], cwd: Path, timeout: int = 300) -> subprocess.CompletedProcess:
"""
Run an np... | 51 | 1,616 |
cognee | cognee/api/v1/responses/models.py | .py | import time
import uuid
from typing import Any, Dict, List, Optional, Union
from pydantic import BaseModel, Field
from enum import Enum
from cognee.api.DTO import InDTO, OutDTO
class CogneeModel(str, Enum):
"""Enum for supported model types"""
COGNEEV1 = "cognee-v1"
class FunctionParameters(BaseModel):
... | 103 | 2,476 |
cognee | cognee/api/v1/responses/default_tools.py | .py | DEFAULT_TOOLS = [
{
"type": "function",
"name": "search",
"description": "Search for information within the knowledge graph",
"parameters": {
"type": "object",
"properties": {
"search_query": {
"type": "string",
... | 109 | 4,366 |
cognee | cognee/api/v1/responses/dispatch_function.py | .py | import json
import logging
from typing import Any, Dict, Union
from cognee.api.v1.responses.models import ToolCall
from cognee.modules.search.types import SearchType
from cognee.api.v1.add import add
from cognee.api.v1.search import search
from cognee.api.v1.cognify import cognify
from cognee.api.v1.prune import prune... | 114 | 3,725 |
cognee | cognee/api/v1/responses/__init__.py | .py | from cognee.api.v1.responses.routers import get_responses_router
__all__ = ["get_responses_router"]
| 4 | 101 |
cognee | cognee/api/v1/responses/routers/default_tools.py | .py | DEFAULT_TOOLS = [
{
"type": "function",
"name": "search",
"description": "Search for information within the knowledge graph",
"parameters": {
"type": "object",
"properties": {
"search_query": {
"type": "string",
... | 128 | 5,061 |
cognee | cognee/api/v1/responses/routers/get_responses_router.py | .py | """
Get router for the OpenAI-compatible responses API.
"""
import logging
import uuid
from typing import Dict, List, Optional, Any
import openai
from fastapi import APIRouter, Depends
from cognee.api.v1.responses.models import (
ResponseRequest,
ResponseBody,
ResponseToolCall,
ChatUsage,
FunctionC... | 174 | 5,979 |
cognee | cognee/api/v1/responses/routers/__init__.py | .py | from cognee.api.v1.responses.routers.get_responses_router import get_responses_router
__all__ = ["get_responses_router"]
| 4 | 122 |
cognee | cognee/api/v1/integrations/routers/__init__.py | .py | from .get_integrations_router import get_integrations_router
__all__ = ["get_integrations_router"]
| 4 | 100 |
cognee | cognee/api/v1/integrations/routers/get_integrations_router.py | .py | """Integrations router: OAuth install flow and connection state for every
registered provider, dispatched generically on ``{provider}``.
Route roles differ sharply in their auth model, which is the point:
* ``POST /{provider}/authorize`` — authenticated. Minting the signed OAuth
state is the permission gate for the... | 211 | 9,847 |
cognee | cognee/api/v1/agents/__init__.py | .py | from cognee.api.v1.agents.routers import get_agents_router
__all__ = ["get_agents_router"]
| 4 | 92 |
cognee | cognee/api/v1/agents/agents.py | .py | from __future__ import annotations
from typing import Optional, Union
from uuid import UUID
from cognee.modules.users.models import User
from cognee.modules.users.methods import get_default_user
from cognee.modules.users.exceptions import PermissionDeniedError
from cognee.modules.users.permissions.methods import give... | 274 | 10,019 |
cognee | cognee/api/v1/agents/routers/get_agents_router.py | .py | from typing import Literal, Optional
from uuid import UUID
from cognee.api.DTO import OutDTO
from cognee.modules.agents.agent_mode import register_agent, unregister_agent
from cognee.modules.agents.models import RegisterAgentRequest, UnregisterAgentRequest
from cognee.modules.agents.create_agent import create_agent
fr... | 208 | 7,399 |
cognee | cognee/cli/_cognee.py | .py | import sys
import os
import argparse
import logging
import signal
import subprocess
import warnings
from typing import Any, Sequence, Dict, Type, cast, List
import click
try:
import rich_argparse
from rich.markdown import Markdown
HAS_RICH = True
except ImportError:
HAS_RICH = False
from cognee.cli ... | 448 | 16,400 |
cognee | cognee/cli/minimal_cli.py | .py | #!/usr/bin/env python3
"""
Minimal CLI entry point for cognee that avoids early initialization
"""
import sys
import os
from typing import Any, Sequence
# CRITICAL: Prevent verbose logging initialization for CLI-only usage
# This must be set before any cognee imports to be effective
os.environ["COGNEE_MINIMAL_LOGGING... | 98 | 3,112 |
cognee | cognee/cli/echo.py | .py | """CLI output formatting utilities"""
import sys
import click
from typing import Any
def echo(message: str = "", color: str = None, err: bool = False) -> None:
"""Echo a message to stdout or stderr with optional color"""
click.secho(message, fg=color, err=err)
def note(message: str) -> None:
"""Print a... | 46 | 1,128 |
cognee | cognee/cli/exceptions.py | .py | from typing import Optional
class CliCommandException(Exception):
"""Exception raised by CLI commands with additional context"""
def __init__(
self,
message: str,
error_code: int = -1,
docs_url: Optional[str] = None,
raiseable_exception: Optional[Exception] = None,
... | 24 | 617 |
cognee | cognee/cli/reference.py | .py | from abc import abstractmethod
from typing import Protocol, Optional
import argparse
class SupportsCliCommand(Protocol):
"""Protocol for defining one cognee cli command"""
command_string: str
"""name of the command"""
help_string: str
"""the help string for argparse"""
description: Optional[s... | 27 | 824 |
cognee | cognee/cli/__init__.py | .py | from cognee.cli.reference import SupportsCliCommand
from cognee.cli.exceptions import CliCommandException
DEFAULT_DOCS_URL = "https://docs.cognee.ai"
__all__ = [
"SupportsCliCommand",
"CliCommandException",
"DEFAULT_DOCS_URL",
]
| 11 | 243 |
cognee | cognee/cli/hints.py | .py | """Next-step hints printed after the primary CLI commands succeed.
Each primary command (``remember``, ``recall``, ``cognify``, ``forget``)
ends with a single ``Next: ...`` line naming the natural follow-up command,
formatted so the user can copy-paste it. The copy lives here so it stays
consistent across commands and... | 34 | 1,300 |
cognee | cognee/cli/debug.py | .py | """Provides a global debug setting for the CLI - following dlt patterns"""
_DEBUG_FLAG = False
def enable_debug() -> None:
"""Enable debug mode for CLI"""
global _DEBUG_FLAG
_DEBUG_FLAG = True
def disable_debug() -> None:
"""Disable debug mode for CLI"""
global _DEBUG_FLAG
_DEBUG_FLAG = Fal... | 22 | 444 |
cognee | cognee/cli/api_client.py | .py | """Thin HTTP client that delegates CLI commands to a running Cognee API server.
When ``--api-url`` is supplied (e.g. ``--api-url http://localhost:8000``),
every CLI command is forwarded as an HTTP request to the server instead of
being executed in-process. This avoids file-based database locking issues
(SQLite, Ladyb... | 391 | 13,936 |
cognee | cognee/cli/remediation.py | .py | """First-run error remediation table.
The failure modes that show up most often on a clean install are:
1. **Invalid API key** — key is set but rejected upstream (401).
2. **Key rejected for permission / quota** — provider accepts the key but
denies the request (403, or an exhausted-quota / billing error).
3. **Mi... | 85 | 3,896 |
cognee | cognee/cli/config.py | .py | """
CLI configuration and constants to avoid hardcoded values
"""
# CLI Constants
CLI_DESCRIPTION = "Cognee CLI - Manage your knowledge graphs and cognitive processing pipelines."
DEFAULT_DOCS_URL = "https://docs.cognee.ai"
# Command descriptions - these should match the actual command implementations
COMMAND_DESCRIP... | 52 | 2,441 |
cognee | cognee/cli/api_dispatch.py | .py | """Dispatch CLI commands via the Cognee HTTP API instead of in-process.
When ``--api-url`` is set, this module intercepts the normal in-process
execution and forwards the command to a running API server. This ensures
a single process owns all file-based database connections.
"""
from __future__ import annotations
i... | 395 | 15,186 |
cognee | cognee/cli/suppress_logging.py | .py | """
Module to suppress verbose logging before any cognee imports.
This must be imported before any other cognee modules.
"""
import os
# Set CLI mode to suppress verbose logging
os.environ["COGNEE_CLI_MODE"] = "true"
# Also set log level to ERROR for extra safety
os.environ["LOG_LEVEL"] = "ERROR"
| 13 | 301 |
cognee | cognee/cli/user_resolution.py | .py | """Resolve a CLI --user-id flag into a User object."""
from typing import Optional
from uuid import UUID
import cognee.cli.echo as fmt
async def resolve_cli_user(user_id: Optional[str] = None, strict: bool = False):
"""Return the User for the given --user-id, or the default user when omitted.
Raises ValueE... | 65 | 2,427 |
cognee | cognee/cli/samples/__init__.py | .py | """Bundled sample fixtures for calm first-run demos.
Kept as a package so ``importlib.resources`` can resolve the file path
without depending on the source-tree layout.
"""
| 6 | 174 |
cognee | cognee/cli/commands/feedback_command.py | .py | import argparse
import asyncio
from cognee.cli.reference import SupportsCliCommand
from cognee.cli import DEFAULT_DOCS_URL
import cognee.cli.echo as fmt
from cognee.cli.exceptions import CliCommandException
class FeedbackCommand(SupportsCliCommand):
command_string = "feedback"
help_string = "Add or remove fe... | 94 | 3,428 |
cognee | cognee/cli/commands/eval_command.py | .py | import argparse
import asyncio
from cognee.cli.reference import SupportsCliCommand
from cognee.cli import DEFAULT_DOCS_URL
import cognee.cli.echo as fmt
from cognee.cli.exceptions import CliCommandException, CliCommandInnerException
class EvalCommand(SupportsCliCommand):
command_string = "eval"
help_string =... | 72 | 2,778 |
cognee | cognee/cli/commands/improve_command.py | .py | import argparse
import asyncio
from cognee.cli.reference import SupportsCliCommand
from cognee.cli import DEFAULT_DOCS_URL
import cognee.cli.echo as fmt
from cognee.cli.exceptions import CliCommandException, CliCommandInnerException
from cognee.modules.data.constants import DEFAULT_DATASET_NAME
class ImproveCommand(... | 97 | 3,483 |
cognee | cognee/cli/commands/add_command.py | .py | import argparse
import asyncio
from typing import Optional
from cognee.cli.reference import SupportsCliCommand
from cognee.cli import DEFAULT_DOCS_URL
import cognee.cli.echo as fmt
from cognee.cli.exceptions import CliCommandException, CliCommandInnerException
from cognee.modules.data.constants import DEFAULT_DATASET_... | 86 | 3,427 |
cognee | cognee/cli/commands/sessions_command.py | .py | import argparse
import asyncio
import json
from cognee.cli.reference import SupportsCliCommand
from cognee.cli import DEFAULT_DOCS_URL
import cognee.cli.echo as fmt
from cognee.cli.exceptions import CliCommandException
class SessionsCommand(SupportsCliCommand):
command_string = "sessions"
help_string = "View... | 97 | 3,262 |
cognee | cognee/cli/commands/cognify_command.py | .py | import argparse
import asyncio
import os
from typing import Optional
from cognee.cli.reference import SupportsCliCommand
from cognee.cli import DEFAULT_DOCS_URL
from cognee.cli.config import CHUNKER_CHOICES
import cognee.cli.echo as fmt
from cognee.cli.exceptions import CliCommandException, CliCommandInnerException
fr... | 196 | 8,492 |
cognee | cognee/cli/commands/migrate_command.py | .py | """Alembic-style CLI commands for graph/vector database migrations.
cognee upgrade [revision] apply migrations up to a revision (default: head)
cognee downgrade <revision> revert migrations down to a revision ('base' = all)
cognee history show the migration chains (newest first)
co... | 395 | 16,158 |
cognee | cognee/cli/commands/agents_command.py | .py | import argparse
import asyncio
import json
from uuid import UUID
from cognee.cli.reference import SupportsCliCommand
from cognee.cli import DEFAULT_DOCS_URL
import cognee.cli.echo as fmt
from cognee.cli.exceptions import CliCommandException
class AgentsCommand(SupportsCliCommand):
command_string = "agents"
h... | 263 | 9,974 |
cognee | cognee/cli/commands/datasets_command.py | .py | import argparse
import asyncio
import json
from uuid import UUID
from cognee.cli.reference import SupportsCliCommand
from cognee.cli import DEFAULT_DOCS_URL
import cognee.cli.echo as fmt
from cognee.cli.exceptions import CliCommandException
class DatasetsCommand(SupportsCliCommand):
command_string = "datasets"
... | 194 | 7,579 |
cognee | cognee/cli/commands/search_command.py | .py | import argparse
import asyncio
import json
from typing import Optional
from cognee.cli.reference import SupportsCliCommand
from cognee.cli import DEFAULT_DOCS_URL
from cognee.cli.config import SEARCH_TYPE_CHOICES, OUTPUT_FORMAT_CHOICES
import cognee.cli.echo as fmt
from cognee.cli.exceptions import CliCommandException... | 155 | 6,368 |
cognee | cognee/cli/commands/recall_command.py | .py | import argparse
import asyncio
import json
from cognee.cli.reference import SupportsCliCommand
from cognee.cli import DEFAULT_DOCS_URL
from cognee.cli.config import SEARCH_TYPE_CHOICES, OUTPUT_FORMAT_CHOICES
import cognee.cli.echo as fmt
from cognee.cli.exceptions import CliCommandException, CliCommandInnerException
f... | 176 | 7,291 |
cognee | cognee/cli/commands/memify_command.py | .py | import argparse
import asyncio
from cognee.cli.reference import SupportsCliCommand
from cognee.cli import DEFAULT_DOCS_URL
import cognee.cli.echo as fmt
from cognee.cli.exceptions import CliCommandException, CliCommandInnerException
class MemifyCommand(SupportsCliCommand):
command_string = "memify"
help_stri... | 98 | 3,209 |
cognee | cognee/cli/commands/serve_command.py | .py | import argparse
import asyncio
from cognee.cli.reference import SupportsCliCommand
from cognee.cli import DEFAULT_DOCS_URL
import cognee.cli.echo as fmt
class ServeCommand(SupportsCliCommand):
command_string = "serve"
help_string = "Connect to a Cognee instance (cloud or local)"
docs_url = DEFAULT_DOCS_U... | 74 | 2,385 |
cognee | cognee/cli/commands/remember_command.py | .py | import argparse
import asyncio
from importlib import resources
from cognee.cli.reference import SupportsCliCommand
from cognee.cli import DEFAULT_DOCS_URL
from cognee.cli.config import CHUNKER_CHOICES
import cognee.cli.echo as fmt
from cognee.cli.exceptions import CliCommandException, CliCommandInnerException
from cog... | 172 | 6,658 |
cognee | cognee/cli/commands/forget_command.py | .py | import argparse
import asyncio
from uuid import UUID
from cognee.cli.reference import SupportsCliCommand
from cognee.cli import DEFAULT_DOCS_URL
import cognee.cli.echo as fmt
from cognee.cli.exceptions import CliCommandException, CliCommandInnerException
from cognee.cli.hints import hint_remember
class ForgetCommand... | 83 | 3,071 |
cognee | cognee/cli/commands/delete_command.py | .py | import argparse
import asyncio
from cognee.cli.reference import SupportsCliCommand
from cognee.cli import DEFAULT_DOCS_URL
import cognee.cli.echo as fmt
from cognee.cli.exceptions import CliCommandException, CliCommandInnerException
from cognee.api.v1.datasets.datasets import datasets as cognee_datasets
from cognee.mo... | 112 | 4,622 |
cognee | cognee/cli/commands/config_command.py | .py | import argparse
import json
from typing import Optional, Any
from cognee.cli.reference import SupportsCliCommand
from cognee.cli import DEFAULT_DOCS_URL
import cognee.cli.echo as fmt
from cognee.cli.exceptions import CliCommandException, CliCommandInnerException
from cognee.api.v1.exceptions.exceptions import InvalidC... | 221 | 9,205 |
cognee | cognee/cli/commands/push_command.py | .py | import argparse
import asyncio
from cognee.cli.reference import SupportsCliCommand
from cognee.cli import DEFAULT_DOCS_URL
import cognee.cli.echo as fmt
from cognee.cli.exceptions import CliCommandException, CliCommandInnerException
# Tiny constants-only import; the cognee package is already loaded by the CLI.
from c... | 129 | 5,077 |
cognee | cognee/cli/commands/report_command.py | .py | import argparse
import asyncio
from cognee.cli import DEFAULT_DOCS_URL
from cognee.cli.exceptions import CliCommandException, CliCommandInnerException
from cognee.cli.reference import SupportsCliCommand
import cognee.cli.echo as fmt
from cognee.modules.data.constants import DEFAULT_DATASET_NAME
class ReportCommand(S... | 74 | 2,776 |
cognee | cognee/memify_pipelines/consolidate_entities.py | .py | """Memify pipeline that merges near-duplicate ``Entity`` nodes into one.
Mirrors the structure of the sibling graph-mutating enrichment pipelines (e.g.
``apply_feedback_weights``): it resolves the target dataset, enters that
dataset's database context, and runs a single detect (extraction) task followed
by a single me... | 117 | 4,753 |
cognee | cognee/memify_pipelines/persist_agent_trace_feedbacks_in_knowledge_graph.py | .py | from typing import Optional
from cognee import memify
from cognee.context_global_variables import (
set_database_global_context_variables,
set_session_user_context_variable,
)
from cognee.exceptions import CogneeValidationError
from cognee.modules.data.methods import get_authorized_existing_datasets
from cogne... | 102 | 3,712 |
cognee | cognee/memify_pipelines/apply_feedback_weights.py | .py | from typing import List
from cognee import memify
from cognee.context_global_variables import (
set_database_global_context_variables,
set_session_user_context_variable,
)
from cognee.exceptions import CogneeValidationError
from cognee.modules.data.methods import get_authorized_existing_datasets
from cognee.mo... | 88 | 3,135 |
cognee | cognee/memify_pipelines/global_context_index.py | .py | from typing import Union
from uuid import UUID
from cognee import memify
from cognee.modules.pipelines.tasks.task import Task
from cognee.modules.users.models import User
from cognee.tasks.memify.global_context_index import (
extract_global_context_index_input,
update_global_context_index,
)
from cognee.tasks.... | 80 | 2,769 |
cognee | cognee/memify_pipelines/cross_connect_entities.py | .py | import cognee
from cognee.modules.pipelines.tasks.task import Task
from cognee.tasks.memify.cross_connect_entities import (
cross_connect_entities,
get_entity_nodes,
)
async def cross_connect_entities_pipeline(
similarity_threshold: float = 0.5,
overlap_threshold: float = 0.2,
max_new_edges_per_no... | 34 | 933 |
cognee | cognee/memify_pipelines/memify_default_tasks.py | .py | from cognee.modules.pipelines.tasks.task import Task
from cognee.tasks.memify.get_triplet_datapoints import get_triplet_datapoints
from cognee.tasks.memify.extract_user_sessions import extract_user_sessions
from cognee.tasks.memify.cognify_session import cognify_session
from cognee.tasks.storage.index_data_points impor... | 26 | 908 |
cognee | cognee/memify_pipelines/consolidate_entity_descriptions.py | .py | import asyncio
import logging
from uuid import UUID
import cognee
from typing import Any, Dict, List, Optional, Set
import json
from pydantic import BaseModel
from cognee.infrastructure.databases.graph import get_graph_engine
from cognee.infrastructure.engine.models.DataPoint import DataPoint
from cognee.infrastructu... | 225 | 7,605 |
cognee | cognee/memify_pipelines/create_triplet_embeddings.py | .py | from typing import Any
from cognee import memify
from cognee.context_global_variables import (
set_database_global_context_variables,
)
from cognee.exceptions import CogneeValidationError
from cognee.modules.data.methods import get_authorized_existing_datasets
from cognee.shared.logging_utils import get_logger
fro... | 54 | 1,799 |
cognee | cognee/memify_pipelines/memify_task_registry.py | .py | """Registry of memify tasks that can be selected by name.
The memify HTTP endpoint (and ``cognee.memify()``) accept task names as plain
strings. This module maps those names onto ready-to-run ``Task`` instances so
the string-based contract advertised by the API actually works.
Only tasks that are runnable without req... | 112 | 4,853 |
cognee | cognee/memify_pipelines/apply_frequency_weights.py | .py | from typing import List
from cognee import memify
from cognee.context_global_variables import (
set_database_global_context_variables,
set_session_user_context_variable,
)
from cognee.exceptions import CogneeValidationError
from cognee.modules.data.methods import get_authorized_existing_datasets
from cognee.mo... | 82 | 2,926 |
cognee | cognee/memify_pipelines/persist_sessions_in_knowledge_graph.py | .py | from typing import Optional, List
from cognee import memify
from cognee.context_global_variables import (
set_database_global_context_variables,
set_session_user_context_variable,
)
from cognee.exceptions import CogneeValidationError
from cognee.modules.data.methods import get_authorized_existing_datasets
from... | 70 | 2,572 |
cognee | cognee/memory/__init__.py | .py | from .entries import (
MemoryEntry,
QAEntry,
TraceEntry,
FeedbackEntry,
SkillRunEntry,
RecallScope,
normalize_scope,
)
__all__ = [
"MemoryEntry",
"QAEntry",
"TraceEntry",
"FeedbackEntry",
"SkillRunEntry",
"RecallScope",
"normalize_scope",
]
| 20 | 298 |
cognee | cognee/memory/entries.py | .py | """Discriminated-union memory entries for remember()/recall().
Typed payloads let callers pass rich structured data to
``cognee.remember()`` — Q&A turns, agent trace steps, feedback
attachments, and skill-run scores — in addition to the legacy
"blob of text/files" shape.
Each entry carries a literal ``type`` discrimin... | 207 | 6,884 |
cognee | cognee/infrastructure/entities/BaseEntityExtractor.py | .py | from abc import ABC, abstractmethod
from cognee.modules.engine.models import Entity
class BaseEntityExtractor(ABC):
"""
Base class for entity extraction strategies.
This class defines the interface for entity extraction methods that derived classes must
implement. It serves as a blueprint for entity... | 29 | 885 |
cognee | cognee/infrastructure/llm/pipeline_stage.py | .py | from contextlib import contextmanager
from cognee.context_global_variables import (
llm_config as llm_config_ctx,
current_pipeline_stage,
)
from cognee.infrastructure.llm.config import get_llm_context_config
@contextmanager
def pipeline_stage(stage: str):
"""Route every LLM call made within this block to... | 25 | 843 |
cognee | cognee/infrastructure/llm/overload_policy.py | .py | """Overload detection and reaction policy for LLM dispatch.
Everything runs at full speed until there is evidence the provider cannot
keep up; then dispatches are paced by the RPM limiter for a cooldown window
that extends while evidence keeps arriving and lapses back to the configured
state afterwards. The dispatch s... | 117 | 4,787 |
cognee | cognee/infrastructure/llm/utils.py | .py | import asyncio
import os
import litellm
from cognee.infrastructure.llm.LLMGateway import LLMGateway
from cognee.infrastructure.llm.structured_output_framework.litellm_instructor.llm.get_llm_client import (
get_llm_client,
)
from cognee.shared.logging_utils import get_logger
logger = get_logger()
CONNECTION_TEST... | 183 | 7,068 |
cognee | cognee/infrastructure/llm/retry_config.py | .py | """Shared tenacity retry policy for LLM structured-output calls.
Used by every structured-output framework — the litellm/instructor adapters and
the BAML integration alike. Each ``acreate_structured_output`` retries until BOTH
floors are satisfied: at least ``LLM_MIN_RETRY_ATTEMPTS`` attempts AND at least
``LLM_MIN_RE... | 92 | 3,711 |
cognee | cognee/infrastructure/llm/exceptions.py | .py | from cognee.exceptions.exceptions import CogneeValidationError
class ContentPolicyFilterError(CogneeValidationError):
pass
class LLMPaymentRequiredError(CogneeValidationError):
"""Raised when the LLM provider returns HTTP 402 (payment required / budget exhausted)."""
def __init__(
self, message... | 141 | 5,616 |
cognee | cognee/infrastructure/llm/ollama_support.py | .py | import re
from typing import Optional
from cognee.shared.logging_utils import get_logger
logger = get_logger("ollama_support")
# Isolated Ollama model support matrix
OLLAMA_MODEL_CLASSIFICATIONS = {
# Recommended models
"llama3": "recommended",
"llama3.1": "recommended",
"llama3.2": "recommended",
... | 90 | 3,248 |
cognee | cognee/infrastructure/llm/__init__.py | .py | from cognee.infrastructure.llm.config import (
get_llm_config,
)
from cognee.infrastructure.llm.LLMGateway import LLMGateway
from cognee.infrastructure.llm.openai_type_cache import install as _install_openai_type_cache
from cognee.infrastructure.llm.utils import (
determine_embedding_dimensions,
get_max_chu... | 17 | 629 |
cognee | cognee/infrastructure/llm/openai_type_cache.py | .py | """Cache openai-python's per-response type-introspection helpers.
On every HTTP response, the openai SDK rebuilds its ``ChatCompletion`` response
tree, repeatedly calling ``get_origin`` / ``get_args`` / ``is_annotated_type``
/ ``is_literal_type`` against the same static types. At cognify scale this
introspection domin... | 131 | 5,265 |
cognee | cognee/infrastructure/llm/LLMGateway.py | .py | from collections.abc import Coroutine
from typing import Any, TypeVar
from pydantic import BaseModel
from cognee.infrastructure.llm import get_llm_config
from cognee.infrastructure.llm.config import get_llm_context_config
from cognee.infrastructure.llm.retry_config import raise_if_quota_error
from cognee.infrastructu... | 148 | 5,125 |
cognee | cognee/infrastructure/llm/config.py | .py | import json
import os
from functools import lru_cache
from typing import Any, ClassVar
from pydantic import model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
try:
from baml_py import ClientRegistry # ty:ignore[unresolved-import]
except ImportError:
ClientRegistry = None
# Module... | 418 | 16,410 |
cognee | cognee/infrastructure/llm/tokenizer/tokenizer_interface.py | .py | from abc import abstractmethod
from typing import Any, Protocol
class TokenizerInterface(Protocol):
"""
Defines an interface for tokenizers that provides methods for token extraction,
counting, and decoding.
"""
@abstractmethod
def extract_tokens(self, text: str) -> list[Any]:
"""
... | 56 | 1,353 |
cognee | cognee/infrastructure/llm/tokenizer/resolver.py | .py | """Resolve the tokenizer that best matches a configured embedding model.
Chunk sizing counts tokens with a tokenizer. When that tokenizer does not match
the embedding model, the counts are wrong: a BERT wordpiece model (BGE, MiniLM,
E5, ...) counted with the OpenAI BPE tokenizer, for example, mis-sizes every
chunk and... | 220 | 9,526 |
cognee | cognee/infrastructure/llm/tokenizer/Mistral/adapter.py | .py | from typing import Any
from ..tokenizer_interface import TokenizerInterface
class MistralTokenizer(TokenizerInterface):
"""
Tokenizes input text based on a specified model while adhering to a maximum token limit.
The class implements the TokenizerInterface and provides methods to extract tokens,
coun... | 96 | 2,885 |
cognee | cognee/infrastructure/llm/tokenizer/Gemini/adapter.py | .py | from typing import Any
from ..tokenizer_interface import TokenizerInterface
# NOTE: DEPRECATED as to count tokens you need to send an API request to Google it is too slow to use with Cognee
class GeminiTokenizer(TokenizerInterface):
"""
Implements a tokenizer interface for the Gemini model, managing token ex... | 84 | 2,357 |
cognee | cognee/infrastructure/llm/tokenizer/HuggingFace/adapter.py | .py | from typing import Any
from ..tokenizer_interface import TokenizerInterface
class HuggingFaceTokenizer(TokenizerInterface):
"""
Implements a tokenizer using the Hugging Face Transformers library.
Public methods include:
- extract_tokens
- count_tokens
- decode_single_token
Instance vari... | 79 | 2,041 |
cognee | cognee/infrastructure/llm/tokenizer/TikToken/adapter.py | .py | from typing import Any
import tiktoken
from ..tokenizer_interface import TokenizerInterface
class TikTokenTokenizer(TokenizerInterface):
"""
Tokenizer adapter for OpenAI. Intended to be used as part of LLM Embedding and LLM
Adapters classes.
"""
def __init__(
self,
model: str | ... | 125 | 3,650 |
cognee | cognee/infrastructure/llm/prompts/llm_judge_prompts.py | .py | # LLM-as-a-judge metrics as described here: https://arxiv.org/abs/2404.16130
llm_judge_prompts = {
"correctness": "Determine whether the actual output is factually correct based on the expected output.",
"comprehensiveness": "Determine how much detail the answer provides to cover all the aspects and details of... | 10 | 690 |
cognee | cognee/infrastructure/llm/prompts/render_prompt.py | .py | from jinja2 import Environment, FileSystemLoader, select_autoescape
from cognee.root_dir import get_absolute_path
def render_prompt(filename: str, context: dict, base_directory: str | None = None) -> str:
"""
Render a Jinja2 template asynchronously.
Set the base directory if not provided, initialize the... | 47 | 1,626 |
cognee | cognee/infrastructure/llm/prompts/show_prompt.py | .py | from cognee.infrastructure.llm.exceptions import MissingSystemPromptPathError
from cognee.infrastructure.llm.prompts import read_query_prompt
def show_prompt(text_input: str, system_prompt: str) -> str | None:
"""
Format and display the prompt for a user query.
This method formats the prompt using the pr... | 36 | 1,159 |
cognee | cognee/infrastructure/llm/prompts/read_query_prompt.py | .py | from os import path
from cognee.root_dir import get_absolute_path
from cognee.shared.logging_utils import ERROR, get_logger
def read_query_prompt(prompt_file_name: str, base_directory: str | None = None) -> str | None:
"""
Read a query prompt from a file.
Retrieve the contents of a specified prompt file... | 45 | 1,499 |
cognee | cognee/infrastructure/llm/extraction/extract_summary.py | .py | import os
from instructor.core import InstructorRetryException
from pydantic import BaseModel
from cognee.infrastructure.llm.LLMGateway import LLMGateway
from cognee.infrastructure.llm.prompts import read_query_prompt
from cognee.shared.data_models import SummarizedCode
from cognee.shared.logging_utils import get_log... | 52 | 1,729 |
cognee | cognee/infrastructure/llm/extraction/extract_categories.py | .py | from pydantic import BaseModel
from cognee.infrastructure.llm.LLMGateway import LLMGateway
from cognee.infrastructure.llm.prompts import read_query_prompt
async def extract_categories(content: str, response_model: type[BaseModel]):
system_prompt = read_query_prompt("classify_content.txt") or ""
llm_output =... | 13 | 427 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.