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/background/celery/versioned_apps/primary.py
.py
"""Factory stub for running celery worker / celery beat.""" from celery import Celery from onyx.utils.variable_functionality import ( fetch_versioned_implementation, set_is_ee_based_on_env_variable, ) set_is_ee_based_on_env_variable() app: Celery = fetch_versioned_implementation( "onyx.background.celery....
15
355
onyx
backend/onyx/background/celery/versioned_apps/heavy.py
.py
"""Factory stub for running celery worker / celery beat. This code is different from the primary/beat stubs because there is no EE version to fetch. Port over the code in those files if we add an EE version of this worker.""" from celery import Celery from onyx.utils.variable_functionality import ( fetch_versione...
17
519
onyx
backend/onyx/background/celery/versioned_apps/beat.py
.py
"""Factory stub for running celery worker / celery beat.""" from celery import Celery from onyx.background.celery.apps.beat import celery_app from onyx.utils.variable_functionality import set_is_ee_based_on_env_variable set_is_ee_based_on_env_variable() app: Celery = celery_app
10
282
onyx
backend/onyx/background/celery/versioned_apps/light.py
.py
"""Factory stub for running celery worker / celery beat. This code is different from the primary/beat stubs because there is no EE version to fetch. Port over the code in those files if we add an EE version of this worker.""" from celery import Celery from onyx.utils.variable_functionality import ( fetch_versione...
17
519
onyx
backend/onyx/access/utils.py
.py
from onyx.configs.constants import DocumentSource def prefix_user_email(user_email: str) -> str: """Prefixes a user email to eliminate collision with group names. This applies to both a Onyx user and an External user, this is to make the query time more efficient""" return f"user_email:{user_email}" ...
35
1,391
onyx
backend/onyx/access/models.py
.py
from dataclasses import dataclass from onyx.access.utils import ( prefix_external_group, prefix_user_email, prefix_user_group, ) from onyx.configs.constants import PUBLIC_DOC_PAT @dataclass(frozen=True) class ExternalAccess: # arbitrary limit to prevent excessively large permissions sets # not in...
239
7,761
onyx
backend/onyx/access/hierarchy_access.py
.py
from sqlalchemy.orm import Session from onyx.db.models import User from onyx.utils.variable_functionality import fetch_versioned_implementation def _get_user_external_group_ids( db_session: Session, # noqa: ARG001 user: User, # noqa: ARG001 ) -> list[str]: return [] def get_user_external_group_ids(db...
19
585
onyx
backend/onyx/access/access.py
.py
from collections.abc import Callable from typing import cast from sqlalchemy import cast as sa_cast from sqlalchemy import or_, select from sqlalchemy.dialects import postgresql from sqlalchemy.orm import Session from onyx.access.models import DocumentAccess from onyx.access.utils import prefix_user_email from onyx.c...
399
14,229
onyx
backend/onyx/server/saml_multi.py
.py
import base64 import uuid from typing import Any, NoReturn, TypedDict from fastapi import APIRouter, Depends, Request, Response from fastapi_users.authentication import Strategy from onelogin.saml2.auth import OneLogin_Saml2_Auth from onelogin.saml2.xml_utils import OneLogin_Saml2_XML from pydantic import ValidationEr...
373
12,735
onyx
backend/onyx/server/utils.py
.py
import base64 import json import os from datetime import datetime from typing import Any from uuid import UUID from fastapi import HTTPException, status class BasicAuthenticationError(HTTPException): def __init__(self, detail: str): super().__init__(status_code=status.HTTP_403_FORBIDDEN, detail=detail) ...
48
1,530
onyx
backend/onyx/server/models.py
.py
import datetime from typing import Generic, Optional, TypeVar from uuid import UUID from pydantic import BaseModel from onyx.auth.schemas import UserRole from onyx.db.enums import AccountType from onyx.db.models import User DataT = TypeVar("DataT") class StatusResponse(BaseModel, Generic[DataT]): success: bool...
82
1,852
onyx
backend/onyx/server/auth_check.py
.py
from typing import cast from fastapi import FastAPI from fastapi.dependencies.models import Dependant from starlette.routing import BaseRoute from onyx.auth.users import ( current_chat_accessible_user, current_curator_or_admin_user, current_limited_user, current_user, current_user_from_websocket, ...
190
7,822
onyx
backend/onyx/server/usage_limits.py
.py
"""Usage limits enforcement for cloud deployments.""" from collections.abc import Callable from sqlalchemy.orm import Session from onyx.configs.app_configs import ( ANTHROPIC_DEFAULT_API_KEY, COHERE_DEFAULT_API_KEY, OPENAI_DEFAULT_API_KEY, OPENROUTER_DEFAULT_API_KEY, ) from onyx.db.usage import Usage...
279
9,338
onyx
backend/onyx/server/saml.py
.py
import contextlib import secrets import string from typing import Any from urllib.parse import urlparse from fastapi import Request from fastapi_users import exceptions from pydantic import BaseModel from onyx.auth.schemas import UserCreate, UserRole from onyx.auth.users import get_user_manager from onyx.configs.app_...
174
6,796
onyx
backend/onyx/server/utils_vector_db.py
.py
"""Utilities for gating endpoints that require a vector database.""" from fastapi import HTTPException from starlette.status import HTTP_501_NOT_IMPLEMENTED from onyx.configs.app_configs import DISABLE_VECTOR_DB def require_vector_db() -> None: """FastAPI dependency — raises 501 when the vector DB is disabled."...
16
530
onyx
backend/onyx/server/sso_discovery.py
.py
"""Workspace discovery for the cloud login page. Cloud serves every workspace from one domain, so the login page cannot know which IdP to offer until the visitor names themselves. This endpoint takes an address, resolves the workspace from the shared catalog, and returns that workspace's sign-in buttons with a signed ...
140
5,112
onyx
backend/onyx/server/api_key_usage.py
.py
"""API key and PAT usage tracking for cloud usage limits.""" from fastapi import Depends, Request from sqlalchemy.orm import Session from onyx.auth.api_key import get_hashed_api_key_from_request from onyx.auth.pat import get_hashed_pat_from_request from onyx.db.engine.sql_engine import get_session from onyx.db.usage ...
54
1,620
onyx
backend/onyx/server/tenant_usage_limits.py
.py
""" Non-EE version of tenant usage limit overrides. In non-EE deployments, there are no tenant-specific overrides - all tenants use the default limits from environment variables. The EE version (ee.onyx.server.tenant_usage_limits) fetches per-tenant overrides from the control plane. """ from enum import Enum from p...
74
2,206
onyx
backend/onyx/server/oidc_multi.py
.py
"""Per-request-resolved multi-provider OAuth2/OIDC login. Resolves the enabled provider row from the database on each request so one deployment can serve multiple Google and generic OIDC IdPs. Ships dark when no matching provider rows exist. Provider rows are per-workspace, and on cloud a login request carries no ses...
503
18,400
onyx
backend/onyx/server/manage/oauth_test.py
.py
"""Admin "OAuth Test" API. Exposes the claims snapshot captured at OAuth/OIDC login time (see onyx/auth/login_claims_capture.py) so admins can inspect which user fields the IdP actually releases about a user, and debug the directory-profile enrichment. To refresh the snapshot the admin simply goes through the login fl...
81
3,169
onyx
backend/onyx/server/manage/search_settings.py
.py
from uuid import UUID from fastapi import APIRouter, Depends, HTTPException, status from pydantic import BaseModel from sqlalchemy.orm import Session from onyx.auth.permissions import require_permission from onyx.background.celery.tasks.port.tasks import ( PortResumeResult, resume_paused_port_unit, ) from ony...
578
21,995
onyx
backend/onyx/server/manage/models.py
.py
import re from datetime import datetime from enum import Enum from typing import TYPE_CHECKING, Any from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator from onyx.auth.schemas import UserRole from onyx.context.search.models import SavedSearchSettings from onyx.db.enums import ( Defa...
565
17,495
onyx
backend/onyx/server/manage/users.py
.py
import csv import io from datetime import datetime, timedelta, timezone from typing import cast from uuid import UUID import jwt from email_validator import EmailNotValidError, EmailUndeliverableError, validate_email from fastapi import APIRouter, Body, Depends, HTTPException, Query, Request from fastapi.responses imp...
1,351
48,081
onyx
backend/onyx/server/manage/administrative.py
.py
from datetime import datetime, timedelta, timezone from typing import cast from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from onyx.auth.permissions import require_permission from onyx.auth.users import current_curator_or_admin_user from onyx.background.celery.versioned_apps....
251
8,505
onyx
backend/onyx/server/manage/get_state.py
.py
import concurrent.futures import re import threading import requests from cachetools import TTLCache from fastapi import APIRouter, HTTPException, Response from fastapi.concurrency import run_in_threadpool from onyx import __version__ from onyx.auth.users import anonymous_user_enabled, user_needs_to_be_verified from ...
230
9,037
onyx
backend/onyx/server/manage/invite_rate_limit.py
.py
"""Redis-backed rate limits for admin invite + remove-invited-user endpoints. Defends against compromised-admin invite-spam and email-bomb abuse that nginx IP-keyed `limit_req` cannot stop (per-pod counters in multi-replica deployments, trivial IP rotation). Counters live in tenant-prefixed Redis so multi-pod api-serv...
233
8,704
onyx
backend/onyx/server/manage/slack_bot.py
.py
from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from onyx.auth.permissions import require_permission from onyx.configs.constants import MilestoneRecordType from onyx.db.constants import SLACK_BOT_PERSONA_PREFIX from onyx.db.engine.sql_engine import get_session from onyx.db.enum...
356
13,026
onyx
backend/onyx/server/manage/validate_tokens.py
.py
import requests from fastapi import HTTPException from onyx.configs.constants import SLACK_USER_TOKEN_PREFIX SLACK_API_URL = "https://slack.com/api/auth.test" SLACK_CONNECTIONS_OPEN_URL = "https://slack.com/api/apps.connections.open" def validate_bot_token(bot_token: str) -> bool: headers = {"Authorization": f"...
84
2,610
onyx
backend/onyx/server/manage/tracing/models.py
.py
from typing import Literal from pydantic import BaseModel, Field from shared_configs.enums import TracingProviderType class TracingProviderView(BaseModel): provider_type: TracingProviderType connected: bool # "db" (configured in the UI), "env" (legacy env vars), or "none". source: Literal["db", "env...
37
1,078
onyx
backend/onyx/server/manage/tracing/api.py
.py
from __future__ import annotations from fastapi import APIRouter, Depends from sqlalchemy.orm import Session from onyx.auth.permissions import require_permission from onyx.db.engine.sql_engine import get_session from onyx.db.enums import Permission from onyx.db.models import TracingProviderConfig, User from onyx.db.t...
230
7,896
onyx
backend/onyx/server/manage/llm/utils.py
.py
""" LLM Provider Utilities Utilities for dynamic LLM providers (Bedrock, Ollama, OpenRouter): - Display name generation from model identifiers - Model validation and filtering - Reasoning capability inference """ import re from typing import TypedDict from onyx.llm.constants import ( BEDROCK_MODEL_NAME_MAPPINGS,...
399
14,465
onyx
backend/onyx/server/manage/llm/models.py
.py
from __future__ import annotations from functools import cached_property from typing import TYPE_CHECKING, Any, Generic, TypeVar from pydantic import BaseModel, Field, field_validator from onyx.db.enums import LLMModelFlowType from onyx.llm.constants import DYNAMIC_LLM_PROVIDERS from onyx.llm.model_capabilities impo...
687
24,643
onyx
backend/onyx/server/manage/llm/api.py
.py
from collections import defaultdict from datetime import datetime, timezone from typing import Any import boto3 import botocore.session import httpx from botocore.config import Config from botocore.exceptions import BotoCoreError, ClientError, NoCredentialsError from botocore.tokens import FrozenAuthToken, TokenProvid...
2,313
87,164
onyx
backend/onyx/server/manage/llm/provider_cache.py
.py
"""Per-tenant cache for the non-admin LLM provider listing endpoints. GET /llm/provider and GET /llm/persona/{persona_id}/providers are hit on every chat page load and rebuild an identical payload from Postgres each time. The descriptor construction (ORM hydration + pydantic models over every provider x model configur...
153
5,465
onyx
backend/onyx/server/manage/opensearch_migration/models.py
.py
from datetime import datetime from pydantic import BaseModel class OpenSearchMigrationStatusResponse(BaseModel): model_config = {"frozen": True} total_chunks_migrated: int created_at: datetime | None migration_completed_at: datetime | None approx_chunk_count_in_vespa: int | None class OpenSearc...
23
607
onyx
backend/onyx/server/manage/opensearch_migration/api.py
.py
from fastapi import APIRouter, Depends from sqlalchemy.orm import Session from onyx.auth.permissions import require_permission from onyx.configs.app_configs import ONYX_DISABLE_VESPA from onyx.db.engine.sql_engine import get_session from onyx.db.enums import Permission from onyx.db.models import User from onyx.db.open...
67
2,451
onyx
backend/onyx/server/manage/code_interpreter/models.py
.py
from pydantic import BaseModel class CodeInterpreterServer(BaseModel): enabled: bool class CodeInterpreterServerHealth(BaseModel): connected: bool error: str = ""
11
179
onyx
backend/onyx/server/manage/code_interpreter/api.py
.py
from fastapi import APIRouter, Depends from sqlalchemy.orm import Session from onyx.auth.permissions import require_permission from onyx.db.code_interpreter import ( fetch_code_interpreter_server, update_code_interpreter_server_enabled, ) from onyx.db.engine.sql_engine import get_session from onyx.db.enums imp...
57
1,809
onyx
backend/onyx/server/manage/web_search/models.py
.py
from typing import Any from pydantic import BaseModel, Field from onyx.tools.tool_implementations.web_search.models import WebContentProviderConfig from shared_configs.enums import WebContentProviderType, WebSearchProviderType class WebSearchProviderView(BaseModel): id: int name: str provider_type: WebS...
83
2,624
onyx
backend/onyx/server/manage/web_search/api.py
.py
from __future__ import annotations from fastapi import APIRouter, Depends, HTTPException, Response from sqlalchemy.dialects.postgresql import insert from sqlalchemy.orm import Session from onyx.auth.permissions import require_permission from onyx.db.engine.sql_engine import get_session from onyx.db.enums import Permi...
479
17,235
onyx
backend/onyx/server/manage/voice/text_utils.py
.py
from markdown_it import MarkdownIt from markdown_it.token import Token _md = MarkdownIt("commonmark") def _render(tokens: list[Token]) -> str: out: list[str] = [] for tok in tokens: if tok.type == "inline": out.append(_render(tok.children or [])) elif tok.type in ("text", "code_in...
32
1,148
onyx
backend/onyx/server/manage/voice/models.py
.py
from typing import Any from pydantic import BaseModel, Field class VoiceProviderView(BaseModel): """Response model for voice provider listing.""" id: int name: str provider_type: str # "openai", "azure", "elevenlabs" is_default_stt: bool is_default_tts: bool stt_model: str | None tt...
103
3,242
onyx
backend/onyx/server/manage/voice/websocket_api.py
.py
"""WebSocket API for streaming speech-to-text and text-to-speech.""" import asyncio import io import json import os from collections.abc import MutableMapping from typing import Any import numpy as np from fastapi import APIRouter, Depends, WebSocket, WebSocketDisconnect from sqlalchemy.orm import Session from onyx....
1,024
40,064
onyx
backend/onyx/server/manage/voice/api.py
.py
from fastapi import APIRouter, Depends, Response from sqlalchemy.orm import Session from onyx.auth.permissions import require_permission from onyx.db.engine.sql_engine import get_session from onyx.db.enums import Permission from onyx.db.models import LLMProvider as LLMProviderModel from onyx.db.models import User, Voi...
331
11,926
onyx
backend/onyx/server/manage/voice/user_api.py
.py
import json import secrets from collections.abc import AsyncIterator from fastapi import APIRouter, Depends, File, UploadFile from fastapi.responses import StreamingResponse from pydantic import BaseModel, Field from sqlalchemy.orm import Session from onyx.auth.permissions import require_permission from onyx.db.engin...
280
9,772
onyx
backend/onyx/server/manage/discord_bot/utils.py
.py
"""Discord registration key generation and parsing.""" import secrets from urllib.parse import quote, unquote from onyx.utils.logger import setup_logger logger = setup_logger() REGISTRATION_KEY_PREFIX: str = "discord_" def generate_discord_registration_key(tenant_id: str) -> str: """Generate a one-time regist...
46
1,269
onyx
backend/onyx/server/manage/discord_bot/models.py
.py
"""Pydantic models for Discord bot API.""" from datetime import datetime from pydantic import BaseModel # === Bot Config === class DiscordBotConfigResponse(BaseModel): configured: bool created_at: datetime | None = None class Config: from_attributes = True class DiscordBotConfigCreateRequest...
71
1,367
onyx
backend/onyx/server/manage/discord_bot/api.py
.py
"""Discord bot admin API endpoints.""" from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.orm import Session from onyx.auth.permissions import require_permission from onyx.configs.app_configs import DISCORD_BOT_TOKEN from onyx.db.discord_bot import ( create_discord_bot_config, creat...
294
10,189
onyx
backend/onyx/server/manage/sso/models.py
.py
from __future__ import annotations from typing import Any from pydantic import BaseModel from onyx.db.enums import SSOProviderType from onyx.db.models import SSOProvider from onyx.db.sso_provider import mask_secret_config_values, sso_login_callback_uri class SSOProviderCreateRequest(BaseModel): name: str d...
63
1,758
onyx
backend/onyx/server/manage/sso/api.py
.py
from typing import Any from fastapi import APIRouter, Depends from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session from onyx.auth.permissions import require_permission from onyx.auth.sso_url_guard import UnsafeSSOUrl, validate_idp_url from onyx.configs.app_configs import WEB_DOMAIN from onyx.d...
248
9,836
onyx
backend/onyx/server/manage/embedding/models.py
.py
from typing import TYPE_CHECKING from pydantic import BaseModel from shared_configs.enums import EmbeddingProvider if TYPE_CHECKING: from onyx.db.models import CloudEmbeddingProvider as CloudEmbeddingProviderModel class SearchSettingsDeleteRequest(BaseModel): search_settings_id: int class TestEmbeddingRe...
57
1,696
onyx
backend/onyx/server/manage/embedding/api.py
.py
from fastapi import APIRouter, Depends from sqlalchemy.orm import Session from onyx.auth.permissions import require_permission from onyx.db.engine.sql_engine import get_session from onyx.db.enums import Permission from onyx.db.llm import ( fetch_existing_embedding_providers, remove_embedding_provider, upse...
115
4,317
onyx
backend/onyx/server/manage/image_generation/models.py
.py
from typing import TYPE_CHECKING from pydantic import BaseModel if TYPE_CHECKING: from onyx.db.models import ImageGenerationConfig as ImageGenerationConfigModel def _mask_api_key(api_key: str | None) -> str | None: """Mask API key, showing first 4 and last 4 characters.""" if not api_key: return...
184
6,293
onyx
backend/onyx/server/manage/image_generation/api.py
.py
from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from onyx.auth.permissions import require_permission from onyx.db.engine.sql_engine import get_session from onyx.db.enums import Permission from onyx.db.image_generation import ( create_image_generation_config__no_commit, ...
554
20,592
onyx
backend/onyx/server/settings/models.py
.py
from enum import Enum from pydantic import BaseModel, Field from onyx.configs.app_configs import ( DEFAULT_PRUNING_FREQ, DEFAULT_USER_FILE_MAX_UPLOAD_SIZE_MB, DISABLE_VECTOR_DB, MAX_ALLOWED_UPLOAD_SIZE_MB, ) from onyx.configs.constants import QueryHistoryType from onyx.server.features.notifications.mo...
151
5,777
onyx
backend/onyx/server/settings/store.py
.py
from collections.abc import Iterator from contextlib import contextmanager from onyx.cache.factory import get_cache_backend from onyx.cache.locks import cache_shared_lock from onyx.configs.app_configs import ( DEFAULT_USER_FILE_MAX_UPLOAD_SIZE_MB, DISABLE_USER_KNOWLEDGE, DISABLE_VECTOR_DB, ENABLE_OPENS...
135
5,124
onyx
backend/onyx/server/settings/tier_order.py
.py
"""Total ordering over the `Tier` enum. Lives in CE so any module can compare tiers without depending on EE code. """ from onyx.server.settings.models import Tier TIER_RANK: dict[Tier, int] = { Tier.COMMUNITY: 0, Tier.BUSINESS: 1, Tier.ENTERPRISE: 2, } def tier_at_least(current: Tier, required: Tier) -...
17
381
onyx
backend/onyx/server/settings/api.py
.py
from typing import cast from fastapi import APIRouter, Depends from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.orm import Session from onyx import __version__ as onyx_version from onyx.auth.permissions import require_permission from onyx.auth.users import is_user_admin from onyx.configs.app_configs import ...
273
9,996
onyx
backend/onyx/server/security/models.py
.py
from enum import Enum from typing import NamedTuple from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator from typing_extensions import Self from onyx.db.enums import IncognitoRecordMode class SSRFProtectionLevel(str, Enum): """How aggressively outbound HTTP requests are validated ...
236
9,429
onyx
backend/onyx/server/security/store.py
.py
import threading import time from collections.abc import Callable, Iterator from contextlib import contextmanager from typing import Any from cachetools import TTLCache from pydantic import ValidationError from onyx.cache.factory import get_cache_backend from onyx.configs import app_configs as _cfg from onyx.configs....
310
13,068
onyx
backend/onyx/server/security/api.py
.py
import json from typing import Any from fastapi import APIRouter, Depends, Request from fastapi.concurrency import run_in_threadpool from pydantic import ValidationError from onyx.auth.permissions import require_permission from onyx.db.enums import Permission from onyx.db.models import User from onyx.error_handling.e...
90
3,338
onyx
backend/onyx/server/documents/cc_pair.py
.py
from datetime import datetime from http import HTTPStatus from fastapi import APIRouter, Depends, HTTPException, Query from fastapi.responses import JSONResponse from sqlalchemy import select from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session from onyx.auth.permissions import require_permiss...
868
30,789
onyx
backend/onyx/server/documents/models.py
.py
from collections.abc import Sequence from datetime import UTC, datetime, timezone from enum import Enum from typing import Any, Generic, TypeVar from uuid import UUID from pydantic import BaseModel, ConfigDict, Field from onyx.configs.constants import DocumentSource from onyx.connectors.models import InputType from o...
826
26,880
onyx
backend/onyx/server/documents/standard_oauth.py
.py
import json import uuid from typing import Annotated, cast from fastapi import APIRouter, Depends, HTTPException, Query, Request from pydantic import BaseModel, ValidationError from sqlalchemy.orm import Session from onyx.auth.permissions import require_permission from onyx.configs.app_configs import WEB_DOMAIN from ...
227
7,350
onyx
backend/onyx/server/documents/private_key_types.py
.py
import base64 from enum import Enum from typing import Protocol from fastapi import HTTPException, UploadFile from onyx.server.documents.document_utils import validate_pkcs12_content class ProcessPrivateKeyFileProtocol(Protocol): def __call__(self, file: UploadFile) -> str: """ Accepts a file-li...
57
1,877
onyx
backend/onyx/server/documents/connector.py
.py
import json import math import mimetypes import os import zipfile from datetime import datetime from io import BytesIO from typing import Any, cast from fastapi import ( APIRouter, Depends, File, Form, HTTPException, Query, Request, Response, UploadFile, ) from google.oauth2.credent...
2,029
71,720
onyx
backend/onyx/server/documents/credential.py
.py
import json from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, UploadFile from sqlalchemy.orm import Session from onyx.auth.permissions import require_permission from onyx.auth.users import current_curator_or_admin_user from onyx.configs.constants import PUBLIC_API_TAGS from onyx.connectors.fac...
465
14,991
onyx
backend/onyx/server/documents/document_utils.py
.py
from cryptography.hazmat.primitives.serialization import pkcs12 from onyx.utils.logger import setup_logger logger = setup_logger() def _is_password_related_error(error: Exception) -> bool: """ Check if the exception indicates a password-related issue rather than a format issue. """ error_msg = str(e...
77
3,064
onyx
backend/onyx/server/documents/targeted_reindex.py
.py
"""Admin endpoints for the targeted-reindex flow. Two endpoints: * `POST /manage/admin/indexing/targeted-reindex` — submit error IDs and/or doc refs, returns a job id the FE polls. * `GET /manage/admin/indexing/targeted-reindex/{job_id}` — current status. The POST handler validates input, persists the job + per-d...
180
5,951
onyx
backend/onyx/server/documents/document.py
.py
from fastapi import APIRouter, Depends, HTTPException, Query from sqlalchemy.orm import Session from onyx.auth.permissions import require_permission from onyx.context.search.models import IndexFilters from onyx.context.search.preprocessing.access_filters import ( build_access_filters_for_user, ) from onyx.db.engin...
106
3,984
onyx
backend/onyx/server/query_and_chat/session_loading.py
.py
from __future__ import annotations import json from typing import Any, Literal, cast from pydantic import ValidationError from sqlalchemy.orm import Session from onyx.chat.citation_utils import extract_citation_order_from_text from onyx.coding_agent.mock_tools import CODING_AGENT_QUERY_KEY, CODING_AGENT_REPO_KEY fro...
903
31,741
onyx
backend/onyx/server/query_and_chat/models.py
.py
from datetime import datetime from enum import Enum from typing import Any from uuid import UUID from pydantic import BaseModel, model_validator from onyx.configs.constants import DocumentSource, MessageType, SessionType from onyx.context.search.models import BaseFilters, SavedSearchDoc, SearchDoc, Tag from onyx.db.e...
317
10,436
onyx
backend/onyx/server/query_and_chat/placement.py
.py
from pydantic import BaseModel class Placement(BaseModel): """Coordinates that identify where a streaming packet belongs in the UI. The frontend uses these fields to route each packet to the correct turn, tool tab, agent sub-turn, and (in multi-model mode) response column. Attributes: turn_i...
27
1,181
onyx
backend/onyx/server/query_and_chat/token_limit.py
.py
from collections.abc import Sequence from datetime import datetime, timezone from math import ceil from threading import RLock from cachetools import TTLCache from fastapi import Depends from sqlalchemy import select from sqlalchemy.orm import Session from onyx.auth.users import current_chat_accessible_user from onyx...
267
9,988
onyx
backend/onyx/server/query_and_chat/streaming_models.py
.py
from datetime import datetime from enum import Enum from typing import Annotated, Any, Literal, Union from pydantic import BaseModel, Field from onyx.context.search.models import SearchDoc from onyx.server.query_and_chat.placement import Placement class StreamingType(Enum): """Enum defining all streaming packet...
499
14,815
onyx
backend/onyx/server/query_and_chat/chat_utils.py
.py
from typing import IO, Any from pydantic import BaseModel from onyx.file_processing.extract_file_text import xlsx_sheet_extraction from onyx.file_processing.file_types import SPREADSHEET_MIME_TYPES, OnyxMimeTypes from onyx.file_store.models import ChatFileType # Per-sheet cap on CSV text returned for in-chat spreads...
88
3,004
onyx
backend/onyx/server/query_and_chat/chat_backend.py
.py
import datetime import json import time from collections.abc import Generator from datetime import timedelta from uuid import UUID from fastapi import ( APIRouter, BackgroundTasks, Depends, HTTPException, Query, Request, Response, ) from fastapi.responses import JSONResponse, StreamingRespo...
1,385
51,882
onyx
backend/onyx/server/query_and_chat/query_backend.py
.py
from fastapi import APIRouter, Depends from sqlalchemy.orm import Session from onyx.auth.permissions import require_permission from onyx.auth.users import current_curator_or_admin_user from onyx.configs.chat_configs import NUM_RETURNED_HITS from onyx.configs.constants import DocumentSource from onyx.context.search.mod...
123
4,470
onyx
backend/onyx/server/auth/captcha_api.py
.py
"""API + middleware for the reCAPTCHA cookie and header flows. Three entry points are gated: 1. ``/auth/oauth/callback`` — the frontend pre-verifies a token and gets a signed HttpOnly cookie (``/auth/captcha/oauth-verify``) that rides along on the Google redirect, where ``CaptchaCookieMiddleware`` checks it....
190
6,810
onyx
backend/onyx/server/auth/mobile.py
.py
"""Mobile auth gateway. Native mobile clients (Expo / React Native) authenticate against the SAME backend as web, but receive the existing stateful session token as a Bearer value instead of an HttpOnly cookie. This module owns the mobile-facing auth surface. Endpoints: - POST /auth/mobile/login email/passw...
61
2,687
onyx
backend/onyx/server/metrics/opensearch_search.py
.py
"""Prometheus metrics for OpenSearch search latency, throughput, and errors. Tracks client-side round-trip latency, server-side execution time (from OpenSearch's ``took`` field), total search attempts, in-flight concurrency, and per-error-type failure counts. ``onyx_opensearch_search_total`` counts attempts (incremen...
189
6,140
onyx
backend/onyx/server/metrics/perm_sync_metrics.py
.py
"""Permission-sync-specific Prometheus metrics. Tracks doc permission sync and external group sync phases: Doc permission sync (connector_permission_sync_generator_task): 1. Overall sync duration (source enumeration + DB updates) 2. Cumulative per-element DB update duration within update_db 3. Documents success...
186
5,934
onyx
backend/onyx/server/metrics/indexing_pipeline_setup.py
.py
"""Setup function for indexing pipeline Prometheus collectors. Called once by the monitoring celery worker after Redis and DB are ready. """ from celery import Celery from prometheus_client.registry import REGISTRY from onyx.server.metrics.indexing_pipeline import ( QueueDepthCollector, RedisHealthCollector,...
60
2,190
onyx
backend/onyx/server/metrics/per_tenant.py
.py
"""Per-tenant request counter metric. Increments a counter on every request, labelled by tenant, so Grafana can answer "which tenant is generating the most traffic?" """ from prometheus_client import Counter from prometheus_fastapi_instrumentator.metrics import Info from shared_configs.contextvars import CURRENT_TEN...
28
861
onyx
backend/onyx/server/metrics/deletion_metrics.py
.py
"""Connector-deletion-specific Prometheus metrics. Tracks the deletion lifecycle: 1. Deletions started (taskset generated) 2. Deletions completed (success or failure) 3. Taskset duration (from taskset generation to completion or failure). Note: this measures the most recent taskset execution, NOT wall-clock...
104
3,383
onyx
backend/onyx/server/metrics/mcp_common.py
.py
from enum import Enum class MCPToolCallStatus(str, Enum): SUCCESS = "success" AUTH_ERROR = "auth_error" ERROR = "error"
8
134
onyx
backend/onyx/server/metrics/connector_state_metrics.py
.py
"""Restart-proof connector state metrics for single-tenant deployments.""" import concurrent.futures import threading from collections.abc import Iterator from datetime import datetime from typing import NamedTuple from prometheus_client.core import REGISTRY, GaugeMetricFamily, InfoMetricFamily, Metric from prometheu...
305
11,841
onyx
backend/onyx/server/metrics/craft_sandbox.py
.py
"""Prometheus metrics for Craft sandbox provisioning latency. Tracks how long a caller waits for a ready sandbox, and where that time went. The ``outcome`` label is load-bearing rather than descriptive: obtaining a sandbox takes milliseconds when the pod is already running and seconds when it has to be provisioned, s...
155
4,618
onyx
backend/onyx/server/metrics/indexing_pipeline.py
.py
"""Prometheus collectors for Celery queue depths and infrastructure health. These collectors query Redis at scrape time (the Collector pattern), so metrics are always fresh when Prometheus scrapes /metrics. They run inside the monitoring celery worker which already has Redis access. To avoid hammering Redis on every ...
457
18,394
onyx
backend/onyx/server/metrics/connector_health_metrics.py
.py
"""Prometheus metrics for connector health and index attempts. Emitted by docfetching and docprocessing workers when connector or index attempt state changes. All functions silently catch exceptions to avoid disrupting the caller's business logic. Gauge metrics (error state, last success timestamp) are per-process. W...
123
3,773
onyx
backend/onyx/server/metrics/mcp_client.py
.py
import time from prometheus_client import Counter, Histogram from onyx.server.metrics.mcp_common import MCPToolCallStatus from onyx.utils.logger import setup_logger logger = setup_logger() MCP_CLIENT_TOOL_TOTAL = Counter( "onyx_mcp_client_tool_calls_total", "External MCP tool calls made by Onyx", ["serv...
41
1,140
onyx
backend/onyx/server/metrics/embedding.py
.py
"""Prometheus metrics for embedding generation latency and throughput. Tracks client-side round-trip latency (as seen by callers of ``EmbeddingModel.encode``). """ import logging from collections.abc import Generator from contextlib import contextmanager from enum import Enum from prometheus_client import Counter, G...
210
6,157
onyx
backend/onyx/server/metrics/metrics_server.py
.py
"""Standalone Prometheus metrics HTTP server for non-API processes. The FastAPI API server already exposes /metrics via prometheus-fastapi-instrumentator. Celery workers and other background processes use this module to expose their own /metrics endpoint on a configurable port. The listener binds the IPv6 wildcard wi...
225
8,819
onyx
backend/onyx/server/metrics/celery_task_metrics.py
.py
"""Generic Celery task lifecycle Prometheus metrics. Provides signal handlers that track task started/completed/failed counts, active task gauge, task duration histograms, queue wait time histograms, and retry/reject/revoke counts. These fire for ALL tasks on the worker — no per-connector enrichment (see indexing_task...
240
7,097
onyx
backend/onyx/server/metrics/pruning_metrics.py
.py
"""Pruning-specific Prometheus metrics. Tracks three pruning pipeline phases for connector_pruning_generator_task: 1. Document ID enumeration duration (extract_ids_from_runnable_connector) 2. Diff + dispatch duration (DB lookup, set diff, generate_tasks) 3. Rate limit errors during enumeration All metrics are l...
72
2,382
onyx
backend/onyx/server/metrics/mcp_server.py
.py
import time from enum import Enum from prometheus_client import Counter, Histogram from onyx.server.metrics.mcp_common import MCPToolCallStatus from onyx.utils.logger import setup_logger logger = setup_logger() class MCPAuthResult(str, Enum): SUCCESS = "success" REJECTED = "rejected" ERROR = "error" ...
95
2,614
onyx
backend/onyx/server/metrics/shard_capacity.py
.py
"""How many tenant schemas each physical database is holding. Schema-per-tenant is bounded by catalog size rather than disk: every tenant adds ~110 tables, so the table count — and with it migration wall-clock and autovacuum pressure — scales with tenants, not bytes. This is the signal for when to move new signups ont...
77
3,107
onyx
backend/onyx/server/metrics/image_processing.py
.py
import bisect import functools import inspect import io import logging import time from collections.abc import Callable from typing import ParamSpec, TypeVar from prometheus_client import Counter, Histogram logger = logging.getLogger(__name__) P = ParamSpec("P") R = TypeVar("R") _SIZE_TIERS = (10_000, 100_000, 1_00...
117
3,434
onyx
backend/onyx/server/metrics/indexing_task_metrics.py
.py
"""Per-connector Prometheus metrics for indexing tasks. Enriches the two primary indexing tasks (docfetching_proxy_task and docprocessing_task) with connector-level labels: source, tenant_id, and cc_pair_id. Note: connector_name is intentionally excluded from push-based per-task counters because it is a user-defined ...
254
8,034
onyx
backend/onyx/server/metrics/slow_requests.py
.py
"""Slow request counter metric. Increments a counter whenever a request exceeds a configurable duration threshold. Useful for identifying endpoints that regularly take too long. """ import os from prometheus_client import Counter from prometheus_fastapi_instrumentator.metrics import Info SLOW_REQUEST_THRESHOLD_SECO...
32
928