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
onyx
backend/onyx/connectors/salesforce/shelve_stuff/shelve_utils.py
.py
import os from onyx.connectors.salesforce.utils import BASE_DATA_PATH, get_object_type_path def get_object_shelf_path(object_type: str) -> str: """Get the path to the shelf file for a specific object type.""" base_path = get_object_type_path(object_type) os.makedirs(base_path, exist_ok=True) return o...
29
1,029
onyx
backend/onyx/connectors/salesforce/shelve_stuff/shelve_functions.py
.py
import csv import shelve from onyx.connectors.salesforce.shelve_stuff.shelve_utils import ( get_child_to_parent_shelf_path, get_id_type_shelf_path, get_object_shelf_path, get_parent_to_child_shelf_path, ) from onyx.connectors.salesforce.utils import SalesforceObject, validate_salesforce_id from onyx.ut...
207
7,668
onyx
backend/onyx/connectors/freshdesk/connector.py
.py
import json from collections.abc import Iterator from datetime import datetime, timezone from typing import List import requests from onyx.configs.app_configs import INDEX_BATCH_SIZE from onyx.configs.constants import DocumentSource from onyx.connectors.cross_connector_utils.rate_limit_wrapper import rl_requests from...
337
11,784
onyx
backend/onyx/connectors/zulip/utils.py
.py
import time from collections.abc import Callable from typing import Any, Dict, Optional from urllib.parse import quote from onyx.utils.logger import setup_logger logger = setup_logger() class ZulipAPIError(Exception): def __init__(self, code: Any = None, msg: str | None = None) -> None: self.code = code...
101
3,068
onyx
backend/onyx/connectors/zulip/connector.py
.py
import os import tempfile import urllib.parse from collections.abc import Generator from datetime import datetime, timezone from typing import Any, Dict, List, Tuple, Union from zulip import Client from onyx.configs.app_configs import INDEX_BATCH_SIZE from onyx.configs.constants import DocumentSource from onyx.connec...
221
8,169
onyx
backend/onyx/connectors/zulip/schemas.py
.py
from typing import Any, List, Optional, Union from pydantic import BaseModel, Field class Message(BaseModel): id: int sender_id: int content: str recipient_id: int timestamp: int client: str is_me_message: bool sender_full_name: str sender_email: str sender_realm_str: str ...
41
1,089
onyx
backend/onyx/connectors/productboard/connector.py
.py
from collections.abc import Generator from itertools import chain from typing import Any, cast import requests from bs4 import BeautifulSoup from onyx.configs.app_configs import INDEX_BATCH_SIZE, REQUEST_TIMEOUT_SECONDS from onyx.configs.constants import DocumentSource from onyx.connectors.cross_connector_utils.misce...
274
10,133
onyx
backend/onyx/connectors/linear/connector.py
.py
import os import re import time from datetime import datetime, timezone from typing import Any, cast from urllib.parse import urlparse import requests from typing_extensions import override from onyx.configs.app_configs import ( INDEX_BATCH_SIZE, LINEAR_CLIENT_ID, LINEAR_CLIENT_SECRET, ) from onyx.configs...
430
15,267
onyx
backend/onyx/connectors/github/utils.py
.py
from collections.abc import Callable from typing import cast from github import Github from github.Repository import Repository from onyx.access.models import ExternalAccess from onyx.connectors.github.models import SerializedRepository from onyx.utils.logger import setup_logger from onyx.utils.variable_functionality...
66
2,276
onyx
backend/onyx/connectors/github/models.py
.py
from typing import Any from github import Repository from github.Requester import Requester from pydantic import BaseModel class SerializedRepository(BaseModel): # id is part of the raw_data as well, just pulled out for convenience id: int headers: dict[str, str | int] raw_data: dict[str, Any] d...
18
506
onyx
backend/onyx/connectors/github/connector.py
.py
import copy import os from collections.abc import Callable, Generator from datetime import datetime, timedelta, timezone from enum import Enum from io import BytesIO from typing import Any, cast from github import Github, RateLimitExceededException, Repository from github.GithubException import GithubException, Unknow...
1,503
59,530
onyx
backend/onyx/connectors/github/rate_limit_utils.py
.py
import time from datetime import datetime, timedelta, timezone from github import Github from onyx.utils.logger import setup_logger logger = setup_logger() def sleep_after_rate_limit_exception(github_client: Github) -> None: """ Sleep until the GitHub rate limit resets. Args: github_client: Th...
26
727
onyx
backend/onyx/connectors/axero/connector.py
.py
import time from datetime import datetime, timezone from typing import Any import requests from pydantic import BaseModel from onyx.configs.app_configs import INDEX_BATCH_SIZE, REQUEST_TIMEOUT_SECONDS from onyx.configs.constants import DocumentSource from onyx.connectors.cross_connector_utils.miscellaneous_utils impo...
377
11,983
onyx
backend/onyx/connectors/blob/connector.py
.py
import mimetypes import os import time from collections.abc import Mapping from datetime import datetime, timezone from io import BytesIO from numbers import Integral from typing import TYPE_CHECKING, Any, Optional from urllib.parse import quote import boto3 from botocore.client import Config from botocore.credentials...
731
31,258
onyx
backend/onyx/connectors/braintrust/connector.py
.py
import copy import csv import io import json from collections.abc import Callable, Mapping from datetime import datetime, timedelta, timezone from enum import Enum from typing import Any import requests from pydantic import BaseModel from onyx.configs.constants import DocumentSource from onyx.connectors.cross_connect...
625
23,632
onyx
backend/onyx/connectors/zendesk/connector.py
.py
import copy import time from collections.abc import Callable, Iterator from typing import Any, cast import requests from pydantic import BaseModel from requests.exceptions import HTTPError from typing_extensions import override from onyx.configs.app_configs import ( REQUEST_TIMEOUT_SECONDS, ZENDESK_CONNECTOR_...
693
23,701
onyx
backend/onyx/connectors/file/connector.py
.py
import json import os from datetime import datetime, timezone from io import BytesIO from pathlib import Path from typing import IO, Any from onyx.configs.app_configs import INDEX_BATCH_SIZE from onyx.configs.constants import DocumentSource, FileOrigin from onyx.connectors.cross_connector_utils.miscellaneous_utils imp...
385
14,451
onyx
backend/onyx/connectors/bitbucket/utils.py
.py
from __future__ import annotations import time from collections.abc import Callable, Iterator from datetime import datetime from typing import Any import httpx from onyx.configs.app_configs import REQUEST_TIMEOUT_SECONDS from onyx.configs.constants import DocumentSource from onyx.connectors.cross_connector_utils.rat...
308
10,490
onyx
backend/onyx/connectors/bitbucket/connector.py
.py
from __future__ import annotations import copy from collections.abc import Callable, Iterator from datetime import datetime, timezone from typing import TYPE_CHECKING, Any from typing_extensions import override from onyx.configs.app_configs import INDEX_BATCH_SIZE, REQUEST_TIMEOUT_SECONDS from onyx.configs.constants...
360
13,791
onyx
backend/onyx/connectors/imap/models.py
.py
import email.header import email.utils from datetime import datetime from email.message import Message from enum import Enum from pydantic import BaseModel class Header(str, Enum): SUBJECT_HEADER = "subject" FROM_HEADER = "from" TO_HEADER = "to" DELIVERED_TO_HEADER = ( "Delivered-To" # Used ...
77
2,461
onyx
backend/onyx/connectors/imap/connector.py
.py
import copy import email import imaplib import os import re from datetime import datetime, timezone from email.message import Message from email.utils import parseaddr from enum import Enum from typing import Any, cast import bs4 from pydantic import BaseModel from onyx.access.models import ExternalAccess from onyx.c...
495
16,157
onyx
backend/onyx/connectors/discourse/connector.py
.py
import time import urllib.parse from datetime import datetime, timezone from typing import Any, cast import requests from pydantic import BaseModel from requests import Response from onyx.configs.app_configs import INDEX_BATCH_SIZE, REQUEST_TIMEOUT_SECONDS from onyx.configs.constants import DocumentSource from onyx.c...
251
8,620
onyx
backend/onyx/connectors/xenforo/connector.py
.py
""" This is the XenforoConnector class. It is used to connect to a Xenforo forum and load or update documents from the forum. To use this class, you need to provide the URL of the Xenforo forum board you want to connect to when creating an instance of the class. The URL should be a string that starts with 'http://' or...
250
9,738
onyx
backend/onyx/connectors/web/connector.py
.py
import ipaddress import random import socket import time from enum import Enum from typing import Any, cast from urllib.parse import urljoin, urlparse import requests from bs4 import BeautifulSoup from playwright.sync_api import BrowserContext, Playwright, TimeoutError from pydantic import BaseModel, TypeAdapter from ...
859
34,386
onyx
backend/onyx/connectors/notion/connector.py
.py
import re from collections.abc import Generator from datetime import datetime from typing import Any, Optional, cast from urllib.parse import parse_qs, urlparse import requests from pydantic import BaseModel from typing_extensions import override from onyx.configs.app_configs import ( INDEX_BATCH_SIZE, NOTION...
1,378
57,059
onyx
backend/onyx/connectors/coda/connector.py
.py
import os from collections.abc import Generator from datetime import datetime from typing import Any, Dict, List, Optional, cast from pydantic import BaseModel from onyx.configs.app_configs import INDEX_BATCH_SIZE from onyx.configs.constants import DocumentSource from onyx.connectors.cross_connector_utils.rate_limit_...
716
26,723
onyx
backend/onyx/connectors/capability_checks/models.py
.py
from abc import ABC, abstractmethod from collections.abc import Sequence from datetime import datetime from enum import Enum from typing import Any from pydantic import BaseModel, ConfigDict from onyx.configs.constants import DocumentSource from onyx.connectors.capabilities import CredentialCapability from onyx.conne...
206
7,811
onyx
backend/onyx/connectors/capability_checks/runner.py
.py
import time from collections.abc import Sequence from datetime import datetime, timezone from typing import Any from pydantic import BaseModel from sqlalchemy.orm import Session from onyx.connectors.capability_checks.models import ( CapabilityCheck, CapabilityCheckContext, CapabilityCheckResult, Capab...
344
13,491
onyx
backend/onyx/connectors/capability_checks/registry.py
.py
from onyx.configs.constants import DocumentSource from onyx.connectors.capability_checks.models import ( CapabilityCheck, CapabilityCheckContext, CredentialCapability, ) from onyx.connectors.slack.capability_checks import build_slack_indexing_checks from onyx.connectors.source_operations import get_source_o...
84
3,421
onyx
backend/onyx/key_value_store/store.py
.py
import json from typing import cast from onyx.cache.interface import CacheBackend from onyx.db.engine.sql_engine import get_session_with_current_tenant from onyx.db.models import KVStore from onyx.key_value_store.interface import KeyValueStore, KvKeyNotFoundError from onyx.utils.logger import setup_logger from onyx.ut...
103
3,711
onyx
backend/onyx/key_value_store/factory.py
.py
from onyx.key_value_store.interface import KeyValueStore from onyx.key_value_store.store import PgRedisKVStore from shared_configs.configs import DEFAULT_REDIS_PREFIX from shared_configs.contextvars import CURRENT_TENANT_ID_CONTEXTVAR def get_kv_store() -> KeyValueStore: # In the Multi Tenant case, the tenant con...
19
683
onyx
backend/onyx/key_value_store/interface.py
.py
import abc from typing import cast from onyx.utils.special_types import JSON_ro class KvKeyNotFoundError(Exception): pass def unwrap_str(val: JSON_ro) -> str: """Unwrap a string stored as {"value": str} in the encrypted KV store. Also handles legacy plain-string values cached in Redis.""" if isinst...
38
1,133
onyx
backend/onyx/utils/subclasses.py
.py
from __future__ import annotations import importlib import os import pkgutil import sys from types import ModuleType from typing import List, Type, TypeVar T = TypeVar("T") def import_all_modules_from_dir(dir_path: str) -> List[ModuleType]: """ Imports all modules found in the given directory and its subdir...
117
3,559
onyx
backend/onyx/utils/middleware.py
.py
import base64 import hashlib import logging import re import uuid from collections.abc import Awaitable, Callable from datetime import datetime, timezone from fastapi import FastAPI, Request, Response from fastapi.routing import APIRoute from shared_configs.contextvars import ( CURRENT_ENDPOINT_CONTEXTVAR, CU...
130
4,581
onyx
backend/onyx/utils/search_nlp_models_utils.py
.py
def pass_aws_key(api_key: str) -> tuple[str, str, str]: """Parse AWS API key string into components. Args: api_key: String in format 'aws_ACCESSKEY_SECRETKEY_REGION' Returns: Tuple of (access_key, secret_key, region) Raises: ValueError: If key format is invalid """ if ...
27
951
onyx
backend/onyx/utils/process_isolation.py
.py
"""Run a callable in a throwaway child process so a native crash (SIGSEGV/SIGABRT) or a hang takes down the child, not the caller; the parent gets a typed error and decides how to recover. Uses subprocess, not multiprocessing: the indexing worker is a daemon process, and daemons can't have multiprocessing children. ""...
88
3,105
onyx
backend/onyx/utils/logger.py
.py
import contextvars import logging import os from collections.abc import MutableMapping from logging.handlers import RotatingFileHandler from typing import Any from onyx.utils.platform_utils import is_running_in_container from onyx.utils.tenant import get_tenant_id_short_string from shared_configs.configs import ( ...
503
18,459
onyx
backend/onyx/utils/errors.py
.py
class EERequiredError(Exception): """This error is thrown if an Enterprise Edition feature or API is requested but the Enterprise Edition flag is not set."""
4
166
onyx
backend/onyx/utils/postgres_sanitization.py
.py
import re from typing import Any from onyx.access.models import ExternalAccess from onyx.connectors.models import BasicExpertInfo, Document, HierarchyNode from onyx.utils.logger import setup_logger logger = setup_logger() _SURROGATE_RE = re.compile(r"[\ud800-\udfff]") def sanitize_string(value: str) -> str: ""...
168
5,747
onyx
backend/onyx/utils/audit.py
.py
"""Structured, SIEM-exportable audit-event subsystem (log-only). Emits one JSON line per security-relevant action (auth, admin-config / access-control change, credential access) on the ``onyx.audit`` logger tree. Field names and the action taxonomy are shaped toward OCSF so the stream maps onto OCSF event classes (Aut...
322
12,240
onyx
backend/onyx/utils/telemetry.py
.py
import contextvars import threading import uuid from enum import Enum from typing import Any import requests from onyx.configs.app_configs import DISABLE_TELEMETRY, ENTERPRISE_EDITION_ENABLED from onyx.configs.constants import ( KV_CUSTOMER_UUID_KEY, KV_INSTANCE_DOMAIN_KEY, MilestoneRecordType, ) from ony...
236
8,050
onyx
backend/onyx/utils/object_size_check.py
.py
import sys from typing import TypeVar T = TypeVar("T", dict, list, tuple, set, frozenset) def deep_getsizeof(obj: T, seen: set[int] | None = None) -> int: """Recursively sum size of objects, handling circular references.""" if seen is None: seen = set() obj_id = id(obj) if obj_id in seen: ...
27
721
onyx
backend/onyx/utils/variable_functionality.py
.py
import functools import importlib import inspect import os from typing import Any, TypeVar from onyx.configs.app_configs import ( API_SERVER_HOST, API_SERVER_PROTOCOL, API_SERVER_URL_OVERRIDE_FOR_HTTP_REQUESTS, APP_API_PREFIX, APP_PORT, DEV_MODE, ENTERPRISE_EDITION_ENABLED, ) from onyx.util...
224
7,466
onyx
backend/onyx/utils/threadpool_concurrency.py
.py
import asyncio import collections.abc import concurrent.futures import contextvars import copy import threading import uuid from collections.abc import Callable, Coroutine, Iterator, MutableMapping, Sequence from concurrent.futures import ( FIRST_COMPLETED, Future, ThreadPoolExecutor, as_completed, ...
630
21,785
onyx
backend/onyx/utils/supervisord_watchdog.py
.py
#!/usr/bin/env python3 import argparse import subprocess import time from onyx.redis.redis_pool import get_redis_client from onyx.utils.logger import setup_logger logger = setup_logger() MAX_AGE_SECONDS = 900 # how old the heartbeat can be CHECK_INTERVAL = 60 # how often to check MAX_LOOKUP_FAILURES = 5 def mai...
112
3,901
onyx
backend/onyx/utils/long_term_log.py
.py
import json import os import threading from datetime import datetime from pathlib import Path from typing import Any from onyx.utils.logger import setup_logger from onyx.utils.special_types import JSON_ro logger = setup_logger() _LOG_FILE_NAME_TIMESTAMP_FORMAT = "%Y-%m-%d_%H-%M-%S-%f" # NOTE: This is no longer use...
128
4,473
onyx
backend/onyx/utils/csv_utils.py
.py
import csv import io from collections.abc import Generator, Iterable, Iterator, Mapping from pydantic import BaseModel # Python's csv default field size limit is 131072 bytes (128 KiB), which # real-world data (long descriptions, pasted docs, base64 blobs) routinely # exceeds β€” the parser then raises `Error: field la...
124
4,592
onyx
backend/onyx/utils/text_processing.py
.py
import codecs import json import re import string from urllib.parse import quote from onyx.utils.logger import setup_logger logger = setup_logger(__name__) # Mapping of curly/smart quotes to straight quotes CURLY_TO_STRAIGHT_QUOTES: dict[str, str] = { "\u2019": "'", # Right single quotation mark "\u2018": "...
318
10,192
onyx
backend/onyx/utils/retry_after.py
.py
import math from datetime import datetime, timezone from email.utils import parsedate_to_datetime from onyx.utils.datetime import datetime_to_utc from onyx.utils.logger import setup_logger logger = setup_logger() def parse_retry_after_seconds(value: str | None) -> float | None: """Parse an HTTP ``Retry-After`` ...
54
1,724
onyx
backend/onyx/utils/b64.py
.py
import base64 def get_image_type_from_bytes(raw_b64_bytes: bytes) -> str: magic_number = raw_b64_bytes[:4] if magic_number.startswith(b"\x89PNG"): mime_type = "image/png" elif magic_number.startswith(b"\xff\xd8"): mime_type = "image/jpeg" elif magic_number.startswith(b"GIF8"): ...
26
761
onyx
backend/onyx/utils/timing.py
.py
import time from collections.abc import Callable, Generator, Iterator from functools import wraps from inspect import signature from typing import Any, TypeVar, cast from onyx.utils.logger import setup_logger from onyx.utils.telemetry import RecordType, optional_telemetry logger = setup_logger() F = TypeVar("F", bou...
113
4,523
onyx
backend/onyx/utils/headers.py
.py
from typing import TypedDict from fastapi.datastructures import Headers from onyx.configs.model_configs import ( LITELLM_EXTRA_HEADERS, LITELLM_PASS_THROUGH_HEADERS, ) from onyx.configs.tool_configs import CUSTOM_TOOL_PASS_THROUGH_HEADERS from onyx.utils.logger import setup_logger logger = setup_logger() c...
82
2,456
onyx
backend/onyx/utils/datetime.py
.py
from datetime import datetime, timedelta, timezone def datetime_to_utc(dt: datetime) -> datetime: """Normalize to timezone-aware UTC. Naive values are treated as UTC.""" if dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None: return dt.replace(tzinfo=timezone.utc) return dt.astimezone(timezone.ut...
25
995
onyx
backend/onyx/utils/batching.py
.py
from collections.abc import Callable, Generator, Iterable from itertools import islice from typing import TypeVar T = TypeVar("T") def batch_generator( items: Iterable[T], batch_size: int, pre_batch_yield: Callable[[list[T]], None] | None = None, ) -> Generator[list[T], None, None]: """Yields batches...
26
638
onyx
backend/onyx/utils/playwright_fetch.py
.py
"""Shared Playwright-based fetching helpers. Centralizes the browser-launch tuning and bot-detection-aware navigation logic that was originally embedded in `onyx.connectors.web.connector`. Two consumers: - `WebConnector` (long-lived `BrowserContext` reused across many pages in a single crawl) uses `start_playwright...
335
12,895
onyx
backend/onyx/utils/callbacks.py
.py
from typing import Generic, TypeVar T = TypeVar("T") class MetricsHander(Generic[T]): def __init__(self) -> None: self.metrics: T | None = None def record_metric(self, metrics: T) -> None: self.metrics = metrics
12
240
onyx
backend/onyx/utils/tls.py
.py
"""Shared helper for constructing ``ssl.SSLContext`` objects from the common TLS primitives (CA bundle, verify mode, optional client cert/key for mTLS). Each service maps its own env-var vocabulary (libpq ``sslmode`` for Postgres, ``cert_reqs`` for Redis, etc.) down to these arguments so the context-building and clien...
38
1,363
onyx
backend/onyx/utils/gpu_utils.py
.py
import os from functools import lru_cache import requests from onyx.utils.logger import setup_logger from onyx.utils.retry_wrapper import retry_builder from shared_configs.configs import ( INDEXING_MODEL_SERVER_HOST, INDEXING_MODEL_SERVER_PORT, MODEL_SERVER_HOST, MODEL_SERVER_PORT, ) logger = setup_l...
51
1,695
onyx
backend/onyx/utils/credential_audit.py
.py
"""Structured audit logging for credential access (log-only). Emits a single structured JSON line whenever a stored LLM-provider or connector credential is decrypted (read in plaintext via ``get_value(apply_mask=False)`` / a credentials provider), for observability and audit purposes. Each event carries tenant / reque...
149
5,273
onyx
backend/onyx/utils/special_types.py
.py
from collections.abc import Mapping, Sequence from typing import TypeAlias JSON_ro: TypeAlias = ( Mapping[str, "JSON_ro"] | Sequence["JSON_ro"] | str | int | float | bool | None )
7
185
onyx
backend/onyx/utils/web_content.py
.py
from __future__ import annotations import io from urllib.parse import unquote, urlparse from bs4.dammit import UnicodeDammit from onyx.file_processing.extract_file_text import read_pdf_file PDF_MIME_TYPES = ( "application/pdf", "application/x-pdf", "application/acrobat", "application/vnd.pdf", "...
127
3,651
onyx
backend/onyx/utils/sitemap.py
.py
import re import xml.etree.ElementTree as ET from typing import Set from urllib.parse import urljoin import requests from onyx.utils.logger import setup_logger logger = setup_logger() def _get_sitemap_locations_from_robots(base_url: str) -> Set[str]: """Extract sitemap URLs from robots.txt""" sitemap_urls:...
83
2,816
onyx
backend/onyx/utils/file.py
.py
from typing import cast import puremagic from pydantic import BaseModel from onyx.utils.logger import setup_logger logger = setup_logger() class FileWithMimeType(BaseModel): data: bytes mime_type: str class OnyxStaticFileManager: """Retrieve static resources with this class. Currently, these should a...
37
1,155
onyx
backend/onyx/utils/encryption.py
.py
from typing import Any from urllib.parse import urlparse, urlunparse from onyx.configs.app_configs import ENCRYPTION_KEY_SECRET from onyx.configs.constants import MASK_CREDENTIAL_CHAR, MASK_CREDENTIAL_LONG_RE from onyx.connectors.google_utils.shared_constants import ( DB_CREDENTIALS_AUTHENTICATION_METHOD, ) from o...
266
9,426
onyx
backend/onyx/utils/pydantic_util.py
.py
from typing import Any, TypeVar from pydantic import BaseModel, TypeAdapter, ValidationError from onyx.error_handling.error_codes import OnyxErrorCode from onyx.error_handling.exceptions import OnyxError T = TypeVar("T") def shallow_model_dump(model_instance: BaseModel) -> dict[str, Any]: """Like model_dump(),...
32
1,182
onyx
backend/onyx/utils/url.py
.py
import ipaddress import socket import unicodedata from typing import Any from urllib.parse import parse_qs, urlencode, urlparse, urlunparse import requests from onyx.utils.logger import setup_logger logger = setup_logger() # Hostnames that should always be blocked BLOCKED_HOSTNAMES = { # Localhost variations ...
586
19,535
onyx
backend/onyx/utils/sensitive.py
.py
""" Wrapper class for sensitive values that require explicit masking decisions. This module provides a wrapper for encrypted values that forces developers to make an explicit decision about whether to mask the value when accessing it. This prevents accidental exposure of sensitive data in API responses. """ from __fu...
201
7,484
onyx
backend/onyx/utils/retry_wrapper.py
.py
import functools import logging from collections.abc import Callable from logging import Logger from typing import Any, TypeVar, cast import requests from tenacity import ( before_sleep_log, retry_if_exception_type, stop_after_attempt, stop_never, wait_exponential, wait_random, ) from tenacity ...
123
3,947
onyx
backend/onyx/utils/platform_utils.py
.py
# Named `platform_utils` (not `platform`) so direct execution of a utility from this # directory cannot shadow the stdlib `platform`. See issue #10975. import os import warnings _ONYX_DOCKER_ENV_STR = "ONYX_RUNNING_IN_DOCKER" _DANSWER_DOCKER_ENV_STR = "DANSWER_RUNNING_IN_DOCKER" def _resolve_container_flag() -> bool...
38
1,129
onyx
backend/onyx/utils/client_ip.py
.py
"""Extract the real client IP from a FastAPI request and expose it per-request. nginx-ingress forwards the real client address in ``X-Forwarded-For`` while ``request.client.host`` is the in-cluster proxy address. Callers use this for rate limiting, PostHog ``$ip`` enrichment (drives GeoIP), and abuse attribution. Onl...
80
3,186
onyx
backend/onyx/utils/tenant.py
.py
from shared_configs.configs import TENANT_ID_PREFIX def get_tenant_id_short_string(tenant_id: str) -> str: """Gets a short string representation of a full tenant id. Args: tenant_id: The full tenant id. Returns: str: The first 8 characters of the tenant id after removing the prefix. ...
16
448
onyx
backend/onyx/utils/error_handling.py
.py
""" Standardized error handling utilities. """ from onyx.configs.app_configs import CONTINUE_ON_CONNECTOR_FAILURE from onyx.utils.logger import setup_logger logger = setup_logger() def handle_connector_error(e: Exception, context: str) -> None: """ Standard error handling for connectors. Args: ...
25
622
onyx
backend/onyx/utils/os_reaper.py
.py
"""Reap orphaned child processes in spawned connector workers (Linux). Chromium helpers orphaned by Playwright teardown re-parent to PID 1 (the celery worker, which never wait()s) and accumulate as zombies. Spawned connector children mark themselves as the subreaper and drain them instead. Linux-only by nature, not a...
150
4,751
onyx
backend/onyx/utils/github.py
.py
import re from dataclasses import dataclass from typing import Final from urllib.parse import quote, unquote, urlparse import requests from onyx.error_handling.error_codes import OnyxErrorCode from onyx.error_handling.exceptions import OnyxError from onyx.utils.url import SSRFException, ssrf_safe_get GITHUB_COMMIT_S...
354
13,383
onyx
backend/onyx/utils/isolated_runner.py
.py
"""Child entry for ``run_in_isolated_process``: read a pickled (callable, args, kwargs) from stdin, run it, and write the pickled result back over a private copy of stdout. Run as ``python -m onyx.utils.isolated_runner`` so it works even when the caller is a daemon (the indexing worker), which can't spawn multiprocess...
44
1,314
onyx
backend/onyx/utils/external_endpoint.py
.py
"""Generic client for POSTing JSON payloads to external HTTP endpoints. Used by any feature that delivers data to an operator- or customer-provided endpoint (hooks, config-driven document push, ...). Handles the HTTP call, response processing, and validation of the response body against a Pydantic model. It has no opi...
266
10,014
onyx
backend/onyx/utils/jsonriver/parse.py
.py
""" JSON parser for streaming incremental parsing Copyright (c) 2023 Google LLC (original TypeScript implementation) Copyright (c) 2024 jsonriver-python contributors (Python port) SPDX-License-Identifier: BSD-3-Clause """ from __future__ import annotations import copy from enum import IntEnum from typing import Unio...
417
14,772
onyx
backend/onyx/utils/jsonriver/__init__.py
.py
""" jsonriver - A streaming JSON parser for Python Parse JSON incrementally as it streams in, e.g. from a network request or a language model. Gives you a sequence of increasingly complete values. Copyright (c) 2023 Google LLC (original TypeScript implementation) Copyright (c) 2024 jsonriver-python contributors (Pyth...
17
521
onyx
backend/onyx/utils/jsonriver/tokenize.py
.py
""" JSON tokenizer for streaming incremental parsing Copyright (c) 2023 Google LLC (original TypeScript implementation) Copyright (c) 2024 jsonriver-python contributors (Python port) SPDX-License-Identifier: BSD-3-Clause """ from __future__ import annotations import re from enum import IntEnum from typing import Pro...
515
17,228
onyx
backend/onyx/kg/models.py
.py
from datetime import datetime from enum import Enum from typing import Any from pydantic import BaseModel from onyx.configs.constants import DocumentSource from onyx.configs.kg_configs import KG_DEFAULT_MAX_PARENT_RECURSION_DEPTH # Note: make sure to write a migration if adding a non-nullable field or removing a fi...
191
5,579
onyx
backend/onyx/kg/resets/reset_vespa.py
.py
import time from typing import Any from redis.lock import Lock as RedisLock from onyx.configs.constants import CELERY_GENERIC_BEAT_LOCK_TIMEOUT, DocumentSource from onyx.db.document import get_num_chunks_for_document from onyx.db.engine.sql_engine import get_session_with_current_tenant from onyx.db.models import Conn...
130
4,566
onyx
backend/onyx/kg/resets/reset_source.py
.py
from redis.lock import Lock as RedisLock from sqlalchemy import or_ from onyx.configs.constants import DocumentSource from onyx.db.engine.sql_engine import get_session_with_current_tenant from onyx.db.models import ( Connector, Document, DocumentByConnectorCredentialPair, KGEntity, KGEntityExtracti...
103
3,850
onyx
backend/onyx/kg/resets/reset_index.py
.py
from sqlalchemy.orm import Session from onyx.db.document import reset_all_document_kg_stages from onyx.db.models import ( Connector, KGEntity, KGEntityExtractionStaging, KGEntityType, KGRelationship, KGRelationshipExtractionStaging, KGRelationshipType, KGRelationshipTypeExtractionStagin...
38
1,133
onyx
backend/onyx/kg/vespa/vespa_interactions.py
.py
import json from collections.abc import Generator from onyx.context.search.models import IndexFilters from onyx.document_index.vespa.chunk_retrieval import get_chunks_via_visit_api from onyx.document_index.vespa.internal_types import VespaChunkRequest from onyx.kg.models import KGChunkFormat from onyx.utils.logger imp...
81
2,627
onyx
backend/onyx/kg/extractions/extraction_processing.py
.py
import time from typing import Any from redis.lock import Lock as RedisLock from onyx.configs.constants import CELERY_GENERIC_BEAT_LOCK_TIMEOUT from onyx.db.connector import get_kg_enabled_connectors from onyx.db.document import ( get_document_updated_at, get_skipped_kg_documents, get_unprocessed_kg_docum...
604
25,000
onyx
backend/onyx/kg/utils/embeddings.py
.py
from typing import List import numpy as np from onyx.db.engine.sql_engine import get_session_with_current_tenant from onyx.db.search_settings import get_current_search_settings from onyx.natural_language_processing.search_nlp_models import ( EmbeddingModel, EmbedTextType, ) from shared_configs.configs import ...
25
902
onyx
backend/onyx/kg/utils/formatting_utils.py
.py
import re from onyx.db.kg_config import KGConfigSettings from onyx.kg.models import KGPerson def format_entity_id(entity_id_name: str) -> str: return make_entity_id(*split_entity_id(entity_id_name)) def make_entity_id(entity_type: str, entity_name: str) -> str: return f"{entity_type.upper()}::{entity_name....
133
4,381
onyx
backend/onyx/kg/utils/extraction_utils.py
.py
import json from onyx.configs.constants import DocumentSource, OnyxCallTypes from onyx.configs.kg_configs import KG_METADATA_TRACKING_THRESHOLD from onyx.db.engine.sql_engine import get_session_with_current_tenant from onyx.db.entities import get_kg_entity_by_document from onyx.db.entity_type import get_entity_types f...
719
26,827
onyx
backend/onyx/kg/utils/lock_utils.py
.py
import time from redis.lock import Lock as RedisLock def extend_lock(lock: RedisLock, timeout: int, last_lock_time: float) -> float: current_time = time.monotonic() if current_time - last_lock_time >= (timeout / 4): lock.reacquire() last_lock_time = current_time return last_lock_time
13
317
onyx
backend/onyx/kg/clustering/clustering.py
.py
import time from collections.abc import Generator from typing import cast from rapidfuzz.fuzz import ratio from redis.lock import Lock as RedisLock from sqlalchemy import func, text from onyx.configs.constants import CELERY_GENERIC_BEAT_LOCK_TIMEOUT from onyx.configs.kg_configs import ( KG_CLUSTERING_RETRIEVE_THR...
471
17,172
onyx
backend/onyx/kg/clustering/normalizations.py
.py
import re from collections import defaultdict from typing import cast import numpy as np from rapidfuzz.distance.DamerauLevenshtein import normalized_similarity from sqlalchemy import Float, MetaData, String, Table, desc, func, select from sqlalchemy.dialects.postgresql import ARRAY from onyx.configs.kg_configs impor...
350
12,865
onyx
backend/onyx/kg/setup/kg_default_entity_definitions.py
.py
from typing import cast from sqlalchemy.orm import Session from onyx.configs.constants import DocumentSource from onyx.db.entity_type import KGEntityType from onyx.db.kg_config import get_kg_config_settings, validate_kg_settings from onyx.kg.models import ( KGAttributeEntityOption, KGAttributeImplicationPrope...
292
14,483
onyx
backend/onyx/coding_agent/mock_tools.py
.py
from onyx.deep_research.dr_mock_tools import THINK_TOOL_NAME CODING_AGENT_IN_CODE_ID = "CodingAgent" CODING_AGENT_TOOL_NAME = "coding_agent" CODING_AGENT_QUERY_KEY = "query" CODING_AGENT_REPO_KEY = "github_repo" BASH_TOOL_NAME = "bash" BASH_TOOL_CMD_KEY = "cmd" GENERATE_ANSWER_TOOL_NAME = "generate_answer" CODING...
123
3,797
onyx
backend/onyx/coding_agent/models.py
.py
from pydantic import BaseModel from onyx.tools.models import ToolCallKickoff class CodingAgentSpecialToolCalls(BaseModel): think_tool_call: ToolCallKickoff | None = None generate_answer_tool_call: ToolCallKickoff | None = None class CodingAgentCallResult(BaseModel): answer: str
13
296
onyx
backend/onyx/skills/metadata.py
.py
"""Agent Skills metadata parsing, validation, and serialization.""" from __future__ import annotations import re from collections.abc import Mapping from typing import Any, Final import yaml from pydantic import ValidationError from yaml.constructor import ConstructorError from yaml.nodes import MappingNode from on...
142
4,752
onyx
backend/onyx/skills/models.py
.py
import re from typing import Final from pydantic import BaseModel, ConfigDict, Field, field_validator SKILL_NAME_PATTERN: Final[re.Pattern[str]] = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$") GITHUB_SKILL_MAX_COUNT: Final[int] = 500 class SkillMetadata(BaseModel): """Typed representation of Agent Skills frontmatte...
97
2,534
onyx
backend/onyx/skills/ingest.py
.py
import io import zipfile from collections.abc import Iterator from contextlib import contextmanager from typing import NamedTuple from onyx.configs.constants import FileOrigin from onyx.error_handling.error_codes import OnyxErrorCode from onyx.error_handling.exceptions import OnyxError from onyx.file_store.file_store ...
130
3,986
onyx
backend/onyx/skills/push.py
.py
"""Push skill bundles to running sandboxes.""" import hashlib import io import zipfile from collections.abc import Iterable from pathlib import Path from uuid import UUID from sqlalchemy.orm import Session from onyx.db.enums import GatedAppKind from onyx.db.external_app import ( get_connectable_apps_for_user, ...
321
11,652
onyx
backend/onyx/skills/rendering.py
.py
"""Render dynamic skill templates for the per-user skills fileset.""" import re from pathlib import Path from sqlalchemy.orm import Session from onyx.configs.constants import DocumentSource, DocumentSourceDescription from onyx.db.connector import _INTERNAL_ONLY_SOURCES from onyx.db.connector_credential_pair import g...
159
5,855
onyx
backend/onyx/skills/content.py
.py
"""Helpers for reading skill source content.""" from onyx.db.models import Skill from onyx.error_handling.error_codes import OnyxErrorCode from onyx.error_handling.exceptions import OnyxError from onyx.file_store.file_store import FileStore, get_default_file_store from onyx.skills.built_in import BuiltInSkillDefinitio...
60
2,057