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/server/metrics/metrics_auth.py
.py
"""Bearer-token auth for the API server's /metrics endpoint. Auth is required by default. Scrapers must present ``METRICS_AUTH_TOKEN`` as ``Authorization: Bearer <token>`` — the standard Prometheus scrape format (``authorization: { credentials: <token> }`` in a scrape config). Set ``DISABLE_METRICS_AUTH=true`` to del...
62
2,394
onyx
backend/onyx/server/metrics/postgres_connection_pool.py
.py
"""SQLAlchemy connection pool Prometheus metrics. Provides production-grade visibility into database connection pool state: - Pool state gauges (checked-out, idle, overflow, configured size) - Pool lifecycle counters (checkouts, checkins, creates, invalidations, timeouts) - Per-endpoint connection attribution (which ...
251
8,851
onyx
backend/onyx/server/metrics/prometheus_setup.py
.py
"""Prometheus metrics setup for the Onyx API server. Orchestrates HTTP request instrumentation via ``prometheus-fastapi-instrumentator``: - Request count, latency histograms, in-progress gauges - Pool checkout timeout exception handler - Custom metric callbacks (e.g. slow request counting) SQLAlchemy connection pool ...
86
2,769
onyx
backend/onyx/server/kg/models.py
.py
from datetime import datetime from pydantic import ConfigDict from pydantic.main import BaseModel from onyx.db.models import KGEntityType from onyx.kg.models import KGConfigSettings class KGConfig(BaseModel): enabled: bool vendor: str | None vendor_domains: list[str] | None ignore_domains: list[str]...
76
1,834
onyx
backend/onyx/server/kg/api.py
.py
from fastapi import APIRouter, Depends from sqlalchemy.orm import Session from onyx.auth.permissions import require_permission from onyx.configs.constants import TMP_DRALPHA_PERSONA_NAME from onyx.configs.kg_configs import KG_BETA_ASSISTANT_DESCRIPTION from onyx.db.engine.sql_engine import get_session from onyx.db.ent...
215
6,825
onyx
backend/onyx/server/gateway/models.py
.py
from collections.abc import Sequence from typing import Any, Literal, TypeAlias from pydantic import BaseModel, ConfigDict, Field from onyx.llm.model_response import ModelResponse, ModelResponseStream, Usage GatewayModality: TypeAlias = Literal["text", "audio", "image", "video", "pdf"] class GatewayModelCapabiliti...
854
26,089
onyx
backend/onyx/server/gateway/configs.py
.py
import os GATEWAY_PATH_PREFIX = "/gateway" # Kill switch, default ON: set to "false" to send Anthropic-backed providers # back through the translation path (losing server tools / thinking fidelity). ANTHROPIC_GATEWAY_PASSTHROUGH_ENABLED = ( os.environ.get("ANTHROPIC_GATEWAY_PASSTHROUGH_ENABLED", "").lower() != "f...
20
794
onyx
backend/onyx/server/gateway/model_catalog.py
.py
from collections import Counter from collections.abc import Sequence from typing import Any from onyx.llm.model_capabilities import ( find_model_obj, get_llm_max_output_tokens, get_model_map, llm_max_input_tokens, ) from onyx.llm.well_known_providers.llm_provider_options import ( get_provider_displ...
133
4,280
onyx
backend/onyx/server/pat/models.py
.py
"""Pydantic models for Personal Access Token API.""" from datetime import datetime from pydantic import BaseModel, ConfigDict, Field, computed_field, field_validator from onyx.auth.permissions import resolve_effective_permissions from onyx.db.enums import Permission from onyx.db.permissions import parse_permission_v...
101
3,187
onyx
backend/onyx/server/pat/api.py
.py
"""API endpoints for Personal Access Tokens.""" 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 PatType, Permission from onyx.db.models import User from onyx.db.pa...
108
3,681
onyx
backend/onyx/server/middleware/latency_logging.py
.py
import logging import time from collections.abc import Awaitable, Callable from fastapi import FastAPI, Request, Response def add_latency_logging_middleware(app: FastAPI, logger: logging.LoggerAdapter) -> None: @app.middleware("http") async def log_latency( request: Request, call_next: Callable[[Requ...
24
761
onyx
backend/onyx/server/middleware/api_prefix.py
.py
"""Helpers for normalizing ingress paths to application route paths.""" from onyx.configs.app_configs import APP_API_PREFIX def strip_api_prefix(path: str) -> str: """Remove the configured API prefix from an incoming request path. When no API prefix is configured, retain the legacy ``/api`` fallback for ...
21
703
onyx
backend/onyx/server/middleware/rate_limiting.py
.py
from fastapi import Depends, Request, Response, params from fastapi_limiter import FastAPILimiter from fastapi_limiter.depends import RateLimiter from onyx.auth.users import current_chat_accessible_user from onyx.configs.app_configs import ( AUTH_RATE_LIMITING_ENABLED, FEEDBACK_RATE_LIMIT_MAX_REQUESTS, FEE...
109
4,057
onyx
backend/onyx/server/features/document_set/models.py
.py
from typing import Any from uuid import UUID from pydantic import BaseModel, Field from onyx.db.models import DocumentSet as DocumentSetDBModel from onyx.db.models import FederatedConnector__DocumentSet from onyx.server.documents.models import ( CCPairSummary, ConnectorCredentialPairDescriptor, ConnectorS...
191
6,542
onyx
backend/onyx/server/features/document_set/api.py
.py
from fastapi import APIRouter, Depends, HTTPException, Query 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.client import app as client_app from onyx.configs.app_configs import ...
184
6,453
onyx
backend/onyx/server/features/skill/models.py
.py
"""Pydantic request and response models for the skills API.""" import datetime from typing import Any, Literal from uuid import UUID from pydantic import BaseModel, ConfigDict, Field, model_validator from sqlalchemy.orm import Session from onyx.db.enums import SkillAccessLevel, SkillSharePermission from onyx.db.mode...
334
10,014
onyx
backend/onyx/server/features/skill/response_helpers.py
.py
from sqlalchemy.orm import Session from onyx.auth.schemas import UserRole from onyx.db.enums import SkillAccessLevel, SkillSharePermission from onyx.db.external_app import ( SkillExternalAppDependencyState, get_skill_external_app_dependencies, ) from onyx.db.models import Skill, User from onyx.db.persona_shari...
211
6,874
onyx
backend/onyx/server/features/skill/api.py
.py
import io import zipfile from contextlib import ExitStack from typing import Annotated from uuid import UUID from fastapi import APIRouter, Depends, File, Form, UploadFile from pydantic import ValidationError from sqlalchemy.orm import Session from onyx.auth.permissions import get_effective_permissions, require_permi...
932
31,158
onyx
backend/onyx/server/features/usage/models.py
.py
from datetime import datetime from pydantic import BaseModel, Field from onyx.db.models import ModelCostOverride from onyx.db.user_usage import UserUsageByDay as UsageDayModel from onyx.llm.cost import ModelPrice class CostOverrideUpsertRequest(BaseModel): # USD/Mtok; null cache → input rate. Negative rates wou...
104
2,825
onyx
backend/onyx/server/features/usage/api.py
.py
"""Admin cost overrides + user/usage endpoints.""" from collections import defaultdict from collections.abc import Sequence from datetime import date, datetime, time, timedelta, timezone from typing import Annotated from uuid import UUID from fastapi import APIRouter, Depends, Query from sqlalchemy.orm import Session...
412
15,311
onyx
backend/onyx/server/features/password/models.py
.py
from pydantic import BaseModel class UserResetRequest(BaseModel): user_email: str class UserResetResponse(BaseModel): user_id: str new_password: str class ChangePasswordRequest(BaseModel): old_password: str new_password: str
16
251
onyx
backend/onyx/server/features/password/api.py
.py
from fastapi import APIRouter, Depends, HTTPException from fastapi_users.exceptions import InvalidPasswordException from sqlalchemy.orm import Session from onyx.auth.permissions import require_permission from onyx.auth.users import User, UserManager, get_user_manager from onyx.db.engine.sql_engine import get_session f...
60
2,057
onyx
backend/onyx/server/features/search/models.py
.py
from datetime import datetime from pydantic import BaseModel, Field, model_validator from onyx.configs.constants import DocumentSource from onyx.context.search.models import Tag from onyx.tools.models import ChatMinimalTextMessage class SearchRequest(BaseModel): query: str = Field(..., min_length=1, max_length=...
52
1,623
onyx
backend/onyx/server/features/search/api.py
.py
"""Search API endpoint (POST /api/search). Runs the full SearchTool.run() pipeline — the same multi-stage search that powers chat mode. Returns ranked results without generating an LLM answer. Intended for programmatic consumers (onyx-cli, Craft sandbox, integrations). Not the same as the Onyx Search UI backend at /...
206
7,358
onyx
backend/onyx/server/features/tool/models.py
.py
from typing import Any from pydantic import BaseModel from onyx.db.models import Tool from onyx.server.features.tool.tool_visibility import get_tool_visibility_config class ToolSnapshot(BaseModel): id: int name: str description: str definition: dict[str, Any] | None display_name: str in_code...
78
2,480
onyx
backend/onyx/server/features/tool/api.py
.py
from typing import Any from fastapi import APIRouter, Depends, HTTPException from pydantic import BaseModel from sqlalchemy.orm import Session from onyx.auth.permissions import require_permission from onyx.auth.schemas import UserRole from onyx.auth.users import current_curator_or_admin_user from onyx.configs.constan...
286
9,096
onyx
backend/onyx/server/features/tool/tool_visibility.py
.py
"""Tool visibility configuration and utility functions.""" from pydantic import BaseModel from onyx.db.models import Tool from onyx.tools.constants import MEMORY_TOOL_ID, OPEN_URL_TOOL_ID # Tool class name constant for OktaProfileTool (not in main constants.py as it's hidden) OKTA_PROFILE_TOOL_ID = "OktaProfileTool"...
91
3,261
onyx
backend/onyx/server/features/persona/models.py
.py
from datetime import datetime from uuid import UUID from pydantic import BaseModel, Field from onyx.configs.constants import DocumentSource from onyx.db.enums import ( HierarchyNodeType, PersonaAccessLevel, PersonaSharePermission, PersonaSharingStatus, ) from onyx.db.models import ( Document, ...
517
18,225
onyx
backend/onyx/server/features/persona/constants.py
.py
# NOTE: Users know this functionality as "agents", so we want to start moving # nomenclature of these REST resources to match that. ADMIN_AGENTS_RESOURCE = "/admin/agents" AGENTS_RESOURCE = "/agents"
5
200
onyx
backend/onyx/server/features/persona/api.py
.py
from uuid import UUID from fastapi import ( APIRouter, Depends, HTTPException, Query, Request, Response, UploadFile, ) from fastapi.responses import StreamingResponse from pydantic import BaseModel, model_validator from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session...
727
24,817
onyx
backend/onyx/server/features/oauth_config/models.py
.py
from datetime import datetime from typing import Any from pydantic import BaseModel class OAuthConfigCreate(BaseModel): name: str authorization_url: str token_url: str client_id: str client_secret: str scopes: list[str] | None = None additional_params: dict[str, Any] | None = None class...
62
1,573
onyx
backend/onyx/server/features/oauth_config/__init__.py
.py
"""OAuth configuration feature module.""" from onyx.server.features.oauth_config.api import admin_router, router __all__ = ["admin_router", "router"]
6
152
onyx
backend/onyx/server/features/oauth_config/api.py
.py
"""API endpoints for OAuth configuration management.""" from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from onyx.auth.oauth_token_manager import OAuthTokenManager from onyx.auth.permissions import require_permission from onyx.auth.users import current_curator_or_admin_user fr...
270
9,338
onyx
backend/onyx/server/features/input_prompt/models.py
.py
from uuid import UUID from pydantic import BaseModel from onyx.db.models import InputPrompt from onyx.utils.logger import setup_logger logger = setup_logger() class CreateInputPromptRequest(BaseModel): prompt: str content: str is_public: bool class UpdateInputPromptRequest(BaseModel): prompt: str...
48
987
onyx
backend/onyx/server/features/input_prompt/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.input_prompt import ( disable_input_prompt_for_user, fetch_input_prom...
150
4,950
onyx
backend/onyx/server/features/default_assistant/models.py
.py
"""Models for default assistant configuration API.""" from pydantic import BaseModel, Field class DefaultAssistantConfiguration(BaseModel): """Simplified view of default assistant configuration for admin UI.""" tool_ids: list[int] = Field( default_factory=list, description="List of enabled tool IDs"...
32
1,050
onyx
backend/onyx/server/features/default_assistant/api.py
.py
"""API endpoints for default assistant configuration.""" 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.models import User ...
94
3,230
onyx
backend/onyx/server/features/web_search/models.py
.py
from pydantic import BaseModel, Field, field_validator from onyx.tools.models import LlmOpenUrlResult, LlmWebSearchResult from shared_configs.enums import WebContentProviderType, WebSearchProviderType class WebSearchToolRequest(BaseModel): queries: list[str] = Field( ..., min_length=1, de...
69
2,305
onyx
backend/onyx/server/features/web_search/api.py
.py
from fastapi import APIRouter, Depends from sqlalchemy.orm import Session from onyx.auth.permissions import require_permission from onyx.configs.constants import PUBLIC_API_TAGS from onyx.db.engine.sql_engine import get_session from onyx.db.enums import Permission from onyx.db.models import User from onyx.db.web_searc...
302
10,801
onyx
backend/onyx/server/features/notifications/utils.py
.py
from sqlalchemy.orm import Session from onyx.configs.constants import NotificationType from onyx.db.admin_banner import get_admin_banner from onyx.db.enums import NotificationSeverity from onyx.db.models import User from onyx.db.notification import create_notification def ensure_permissions_migration_notification(us...
47
1,913
onyx
backend/onyx/server/features/notifications/models.py
.py
from datetime import datetime from pydantic import BaseModel, ConfigDict from onyx.configs.constants import NotificationType from onyx.db.enums import NotificationSeverity class NotificationResponse(BaseModel): model_config = ConfigDict(from_attributes=True) id: int notif_type: NotificationType sev...
35
818
onyx
backend/onyx/server/features/notifications/api.py
.py
from threading import Lock from uuid import UUID from cachetools import TTLCache from fastapi import APIRouter, Depends, Query from sqlalchemy.orm import Session from onyx.auth.permissions import require_permission from onyx.configs.constants import NotificationType from onyx.db.engine.sql_engine import get_session f...
242
8,848
onyx
backend/onyx/server/features/mcp/models.py
.py
import datetime import re from enum import Enum from typing import Any, List, Literal, NotRequired, Optional, TypedDict from uuid import UUID from mcp.types import Tool as MCPLibTool from pydantic import AnyUrl, BaseModel, Field, model_validator from onyx.db.enums import ( EndpointPolicy, MCPAuthenticationPer...
692
27,081
onyx
backend/onyx/server/features/mcp/client.py
.py
""" MCP (Model Context Protocol) Client Implementation This module provides a proper MCP client that follows the JSON-RPC 2.0 specification and handles connection initialization, session management, and protocol communication. """ from collections.abc import Callable, Coroutine from enum import Enum from typing impor...
342
11,158
onyx
backend/onyx/server/features/mcp/oauth.py
.py
"""Shared MCP OAuth machinery: the SDK token storage/provider and their helpers. Used by chat tool calls (`MCPTool.run`), the admin/user MCP API routes, and the Craft sandbox proxy's token refresh — anything that authenticates against an MCP server with the credentials persisted on `mcp_connection_config` rows. Routes...
1,003
42,105
onyx
backend/onyx/server/features/mcp/api.py
.py
import asyncio import base64 import datetime import hashlib import ipaddress import json import time from collections.abc import Mapping from enum import Enum from secrets import token_urlsafe from typing import Literal from urllib.parse import urlparse from uuid import UUID import requests from fastapi import APIRout...
2,670
101,012
onyx
backend/onyx/server/features/mcp/credentials.py
.py
"""Central home for MCP credential/authentication questions. Several distinct business questions used to share the name ``is_authenticated``. Each function here answers exactly one, with the consumer noted: - ``ResolvedMCPCredentials.can_authenticate`` — are the effective credentials usable for a call right now (la...
276
11,074
onyx
backend/onyx/server/features/mcp/client_metadata.py
.py
from fastapi import APIRouter, Response from mcp.client.auth.utils import is_valid_client_metadata_url from pydantic import AnyUrl from onyx.configs.app_configs import WEB_DOMAIN from onyx.configs.constants import ONYX_DEFAULT_APPLICATION_NAME, PUBLIC_API_TAGS from onyx.server.features.mcp.models import MCPOAuthClient...
52
1,934
onyx
backend/onyx/server/features/mcp/ssrf.py
.py
"""SSRF protection for outbound MCP traffic. The MCP SDK builds its own URLs from server responses (WWW-Authenticate, OAuth metadata, redirects, dynamic client registration), so validating the stored ``server_url`` alone is insufficient. The guard is injected at the httpx transport so every request the SDK makes — eac...
109
4,329
onyx
backend/onyx/server/features/user_oauth_token/api.py
.py
"""API endpoints for user OAuth token management.""" from fastapi import APIRouter, Depends from pydantic import BaseModel from sqlalchemy.orm import Session from onyx.auth.oauth_token_manager import OAuthTokenManager from onyx.auth.permissions import require_permission from onyx.db.engine.sql_engine import get_sessi...
48
1,586
onyx
backend/onyx/server/features/admin_banner/api.py
.py
from fastapi import APIRouter, Depends from pydantic import BaseModel, Field from sqlalchemy.orm import Session from onyx.auth.permissions import require_permission from onyx.configs.constants import NotificationType from onyx.db.admin_banner import ( AdminBanner, clear_admin_banner, get_admin_banner, ...
71
2,430
onyx
backend/onyx/server/features/projects/projects_file_utils.py
.py
from math import ceil from fastapi import UploadFile from PIL import Image, ImageOps, UnidentifiedImageError from pydantic import BaseModel, ConfigDict, Field from sqlalchemy.orm import Session from onyx.configs.app_configs import ( MAX_EMBEDDED_IMAGES_PER_FILE, MAX_EMBEDDED_IMAGES_PER_UPLOAD, ) from onyx.con...
393
16,286
onyx
backend/onyx/server/features/projects/models.py
.py
from datetime import datetime from uuid import UUID from pydantic import BaseModel from onyx.db.enums import UserFileStatus from onyx.db.models import UserFile, UserProject from onyx.db.projects import CategorizedFilesResult from onyx.file_store.models import ChatFileType from onyx.server.query_and_chat.chat_utils im...
112
3,420
onyx
backend/onyx/server/features/projects/api.py
.py
import json from uuid import UUID from fastapi import ( APIRouter, BackgroundTasks, Depends, File, Form, HTTPException, Response, UploadFile, ) from pydantic import BaseModel from sqlalchemy.orm import Session from onyx.auth.permissions import require_permission from onyx.chat.incognit...
756
25,662
onyx
backend/onyx/server/features/hierarchy/models.py
.py
from datetime import datetime from enum import Enum from pydantic import BaseModel from onyx.configs.constants import DocumentSource from onyx.server.features.hierarchy.constants import DOCUMENT_PAGE_SIZE class DocumentSortField(str, Enum): NAME = "name" LAST_UPDATED = "last_updated" class DocumentSortDir...
104
2,659
onyx
backend/onyx/server/features/hierarchy/constants.py
.py
HIERARCHY_NODES_PREFIX = "/hierarchy-nodes" HIERARCHY_NODES_LIST_PATH = "" HIERARCHY_NODE_DOCUMENTS_PATH = "/documents" HIERARCHY_NODES_SEARCH_PATH = "/search" DOCUMENT_PAGE_SIZE = 50 HIERARCHY_NODE_SEARCH_LIMIT = 30
8
218
onyx
backend/onyx/server/features/hierarchy/api.py
.py
from fastapi import APIRouter, Depends, HTTPException, Query from sqlalchemy.orm import Session from onyx.access.hierarchy_access import get_user_external_group_ids from onyx.auth.permissions import require_permission from onyx.configs.app_configs import ENABLE_OPENSEARCH_INDEXING_FOR_ONYX from onyx.configs.constants ...
182
6,727
onyx
backend/onyx/server/features/image_generation/api.py
.py
import base64 import binascii import contextvars import json import threading import time from collections.abc import Iterator from concurrent.futures import ThreadPoolExecutor from fastapi import APIRouter, Depends from fastapi.responses import StreamingResponse from pydantic import BaseModel from onyx.auth.permissi...
253
8,720
onyx
backend/onyx/server/features/release_notes/utils.py
.py
"""Utility functions for release notes parsing and caching.""" import re from datetime import datetime, timezone import httpx from sqlalchemy.orm import Session from onyx import __version__ from onyx.cache.factory import get_shared_cache_backend from onyx.configs.app_configs import INSTANCE_TYPE from onyx.configs.co...
238
7,868
onyx
backend/onyx/server/features/release_notes/models.py
.py
"""Pydantic models for release notes.""" from pydantic import BaseModel class ReleaseNoteEntry(BaseModel): """A single version's release note entry.""" version: str # e.g., "v2.7.0" date: str # e.g., "January 7th, 2026" title: str # Display title for notifications: "Onyx v2.7.0 is available!"
12
317
onyx
backend/onyx/server/features/release_notes/constants.py
.py
"""Constants for release notes functionality.""" # GitHub source GITHUB_RAW_BASE_URL = ( "https://raw.githubusercontent.com/onyx-dot-app/documentation/main" ) GITHUB_CHANGELOG_RAW_URL = f"{GITHUB_RAW_BASE_URL}/changelog.mdx" # Base URL for changelog documentation (used for notification links) DOCS_CHANGELOG_BASE_...
24
681
onyx
backend/onyx/server/token_rate_limits/models.py
.py
from typing import Self from pydantic import BaseModel, Field, model_validator from onyx.db.models import TokenRateLimit from onyx.db.user_usage import ( COST_BUDGET_PERIOD_HOURS, TOKEN_BUDGET_PERIOD_ERROR, normalize_token_period_hours, ) # 1T tokens; stored in thousands so the ceiling stays inside the i...
68
2,282
onyx
backend/onyx/server/api_key/models.py
.py
from pydantic import BaseModel from onyx.auth.schemas import UserRole class APIKeyArgs(BaseModel): name: str | None = None role: UserRole = UserRole.BASIC
9
166
onyx
backend/onyx/server/api_key/api.py
.py
from fastapi import APIRouter, Depends from sqlalchemy.orm import Session from onyx.auth.permissions import require_permission from onyx.db.api_key import ( ApiKeyDescriptor, fetch_api_keys, insert_api_key, regenerate_api_key, remove_api_key, update_api_key, ) from onyx.db.engine.sql_engine imp...
93
2,659
onyx
backend/onyx/server/federated/models.py
.py
from datetime import datetime from typing import Any from pydantic import BaseModel, Field from onyx.configs.constants import FederatedConnectorSource class FederatedConnectorCredentials(BaseModel): """Credentials for federated connector""" client_id: str | None = None client_secret: str | None = None ...
110
2,818
onyx
backend/onyx/server/federated/api.py
.py
import json from typing import Any from uuid import UUID from fastapi import APIRouter, Depends, HTTPException, Request, Response 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 Federat...
648
23,243
onyx
backend/onyx/server/onyx_api/models.py
.py
from pydantic import BaseModel from onyx.connectors.models import DocumentBase class IngestionDocument(BaseModel): document: DocumentBase cc_pair_id: int | None = None class IngestionResult(BaseModel): document_id: str already_existed: bool class DocMinimalInfo(BaseModel): document_id: str ...
20
367
onyx
backend/onyx/server/onyx_api/ingestion.py
.py
from datetime import datetime, timezone from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from onyx.auth.users import current_curator_or_admin_user from onyx.configs.constants import DEFAULT_CC_PAIR_ID, PUBLIC_API_TAGS from onyx.connectors.models import Document, IndexAttemptMet...
233
8,001
onyx
backend/onyx/server/runtime/onyx_runtime.py
.py
import io from PIL import Image from onyx.background.celery.tasks.beat_schedule import ( CLOUD_BEAT_MULTIPLIER_DEFAULT, CLOUD_DOC_PERMISSION_SYNC_MULTIPLIER_DEFAULT, ) from onyx.configs.app_configs import ( ENABLE_TENANT_WORK_GATING, TENANT_WORK_GATING_FULL_FANOUT_INTERVAL_SECONDS, TENANT_WORK_GAT...
249
9,295
onyx
backend/onyx/server/evals/models.py
.py
from pydantic import BaseModel class EvalRunAck(BaseModel): """Response model for evaluation runs""" success: bool
8
126
onyx
backend/onyx/hooks/models.py
.py
from datetime import datetime from enum import Enum from typing import Annotated, Any from pydantic import BaseModel, Field, SecretStr, field_validator, model_validator from onyx.db.enums import HookFailStrategy, HookPoint NonEmptySecretStr = Annotated[SecretStr, Field(min_length=1)] # ----------------------------...
118
4,157
onyx
backend/onyx/hooks/api_dependencies.py
.py
from onyx.error_handling.error_codes import OnyxErrorCode from onyx.error_handling.exceptions import OnyxError from shared_configs.configs import MULTI_TENANT def require_hook_enabled() -> None: """FastAPI dependency that gates all hook management endpoints. Hooks are only available in single-tenant / self-h...
18
562
onyx
backend/onyx/hooks/executor.py
.py
"""CE hook executor. HookSkipped and HookSoftFailed are real classes kept here because process_message.py (CE code) uses isinstance checks against them. execute_hook is the public entry point. It dispatches to _execute_hook_impl via fetch_versioned_implementation so that: - CE: onyx.hooks.executor._execute_hook_imp...
62
1,800
onyx
backend/onyx/hooks/registry.py
.py
from onyx.db.enums import HookPoint from onyx.hooks.points.base import HookPointSpec from onyx.hooks.points.document_ingestion import DocumentIngestionSpec from onyx.hooks.points.document_push import DocumentPushSpec from onyx.hooks.points.query_processing import QueryProcessingSpec # Internal: use `monkeypatch.setatt...
48
1,741
onyx
backend/onyx/hooks/points/document_push.py
.py
from onyx.db.enums import HookFailStrategy, HookPoint from onyx.hooks.points.base import HookPointSpec from onyx.indexing.document_push import DocumentPushPayload, DocumentPushResponse __all__ = ["DocumentPushPayload", "DocumentPushResponse", "DocumentPushSpec"] class DocumentPushSpec(HookPointSpec): """Hook poi...
40
1,637
onyx
backend/onyx/hooks/points/document_ingestion.py
.py
from pydantic import BaseModel, Field from onyx.db.enums import HookFailStrategy, HookPoint from onyx.hooks.points.base import HookPointSpec class DocumentIngestionSection(BaseModel): """Represents a single section of a document — either text or image, not both. Text section: set `text`, leave `image_file_i...
113
4,682
onyx
backend/onyx/hooks/points/query_processing.py
.py
from pydantic import BaseModel, ConfigDict, Field from onyx.db.enums import HookFailStrategy, HookPoint from onyx.hooks.points.base import HookPointSpec class QueryProcessingPayload(BaseModel): model_config = ConfigDict(extra="forbid") query: str = Field(description="The raw query string exactly as the user...
71
2,886
onyx
backend/onyx/hooks/points/base.py
.py
from typing import Any, ClassVar from pydantic import BaseModel from onyx.db.enums import HookFailStrategy, HookPoint _REQUIRED_ATTRS = ( "hook_point", "display_name", "description", "default_timeout_seconds", "fail_hard_description", "default_fail_strategy", "payload_model", "respons...
72
2,711
onyx
backend/onyx/deep_research/utils.py
.py
from collections.abc import Callable from typing import Any from pydantic import BaseModel from onyx.deep_research.dr_mock_tools import GENERATE_REPORT_TOOL_NAME, THINK_TOOL_NAME from onyx.deep_research.models import SpecialToolCalls from onyx.llm.model_response import ChatCompletionDeltaToolCall, Delta, FunctionCall...
213
8,557
onyx
backend/onyx/deep_research/models.py
.py
from pydantic import BaseModel from onyx.chat.citation_processor import CitationMapping from onyx.tools.models import ToolCallKickoff class SpecialToolCalls(BaseModel): think_tool_call: ToolCallKickoff | None = None generate_report_tool_call: ToolCallKickoff | None = None class ResearchAgentCallResult(Base...
23
682
onyx
backend/onyx/deep_research/dr_loop.py
.py
# TODO: Notes for potential extensions and future improvements: # 1. Allow tools that aren't search specific tools # 2. Use user provided custom prompts # 3. Save the plan for replay import time from collections.abc import Callable from typing import cast from onyx.chat.chat_state import ChatStateContainer from onyx....
807
37,944
onyx
backend/onyx/deep_research/dr_mock_tools.py
.py
GENERATE_PLAN_TOOL_NAME = "generate_plan" RESEARCH_AGENT_IN_CODE_ID = "ResearchAgent" RESEARCH_AGENT_TOOL_NAME = "research_agent" RESEARCH_AGENT_TASK_KEY = "task" GENERATE_REPORT_TOOL_NAME = "generate_report" THINK_TOOL_NAME = "think_tool" # ruff: noqa: E501, W605 start GENERATE_PLAN_TOOL_DESCRIPTION = { "type...
140
4,075
onyx
backend/onyx/image_gen/exceptions.py
.py
class ImageProviderError(Exception): pass class ImageProviderCredentialsError(ImageProviderError): pass class ImageGenerationNotConfiguredError(ImageProviderError): pass
11
186
onyx
backend/onyx/image_gen/generation.py
.py
from pydantic import BaseModel from sqlalchemy.orm import Session from onyx.db.engine.sql_engine import get_session_with_current_tenant from onyx.db.image_generation import get_default_image_generation_config from onyx.image_gen.exceptions import ImageGenerationNotConfiguredError from onyx.image_gen.factory import get...
164
5,299
onyx
backend/onyx/image_gen/factory.py
.py
from enum import Enum from onyx.image_gen.interfaces import ( ImageGenerationProvider, ImageGenerationProviderCredentials, ) from onyx.image_gen.providers.azure_img_gen import AzureImageGenerationProvider from onyx.image_gen.providers.openai_img_gen import OpenAIImageGenerationProvider from onyx.image_gen.prov...
47
1,534
onyx
backend/onyx/image_gen/interfaces.py
.py
from __future__ import annotations import abc from enum import Enum from typing import TYPE_CHECKING, Any from pydantic import BaseModel from onyx.image_gen.exceptions import ImageProviderCredentialsError if TYPE_CHECKING: from litellm.types.utils import ImageResponse as ImageGenerationResponse class ImageSha...
88
2,476
onyx
backend/onyx/image_gen/providers/vertex_img_gen.py
.py
from __future__ import annotations import base64 import json from datetime import datetime from typing import TYPE_CHECKING, Any from pydantic import BaseModel from onyx.image_gen.exceptions import ImageProviderCredentialsError from onyx.image_gen.interfaces import ( ImageGenerationProvider, ImageGenerationP...
290
9,619
onyx
backend/onyx/image_gen/providers/openai_img_gen.py
.py
from __future__ import annotations from typing import TYPE_CHECKING, Any from onyx.image_gen.interfaces import ( ImageGenerationProvider, ImageGenerationProviderCredentials, ReferenceImage, ) from onyx.tracing.flows import LLMFlow from onyx.tracing.llm_utils import traced_llm_call if TYPE_CHECKING: f...
136
4,164
onyx
backend/onyx/image_gen/providers/azure_img_gen.py
.py
from __future__ import annotations from typing import TYPE_CHECKING, Any from onyx.image_gen.interfaces import ( ImageGenerationProvider, ImageGenerationProviderCredentials, ReferenceImage, ) from onyx.tracing.flows import LLMFlow from onyx.tracing.llm_utils import traced_llm_call if TYPE_CHECKING: f...
151
4,587
onyx
backend/onyx/llm/cost_overrides.py
.py
"""Admin per-model cost overrides — negotiated enterprise rates that win over litellm.""" import threading import time from cachetools import LRUCache, TTLCache from pydantic import BaseModel, ConfigDict from sqlalchemy import select from sqlalchemy.orm import Session from onyx.db.models import ModelCostOverride fro...
171
5,691
onyx
backend/onyx/llm/tracing_wrap.py
.py
"""Auto-tracing wrapper applied to every concrete `LLM` subclass. Every concrete subclass of `onyx.llm.interfaces.LLM` has its `invoke` and `stream` methods auto-wrapped via `LLM.__init_subclass__` so that every LLM call lands in Braintrust without per-callsite instrumentation. The wrap is a no-op when an outer `gener...
332
13,499
onyx
backend/onyx/llm/utils.py
.py
import copy import re from collections.abc import Callable, Iterable from typing import TYPE_CHECKING, Any from sqlalchemy import select from onyx.configs.app_configs import ( LITELLM_CUSTOM_ERROR_MESSAGE_MAPPINGS, MAX_TOKENS_FOR_FULL_INCLUSION, SEND_USER_METADATA_TO_LLM_PROVIDER, USE_CHUNK_SUMMARY, ...
621
23,432
onyx
backend/onyx/llm/multi_llm.py
.py
import copy import os import re import time from collections.abc import Iterator from contextlib import AbstractContextManager, contextmanager, nullcontext from functools import lru_cache from typing import TYPE_CHECKING, Any, Union, cast from readerwriterlock import rwlock from onyx.configs.app_configs import ( ...
1,373
60,320
onyx
backend/onyx/llm/exceptions.py
.py
class ClassifiedLLMError(RuntimeError): def __init__( self, *, client_error_msg: str, error_code: str, is_retryable: bool, ) -> None: super().__init__(client_error_msg) self.client_error_msg = client_error_msg self.error_code = error_code s...
13
352
onyx
backend/onyx/llm/model_name_parser.py
.py
""" LiteLLM Model Name Parser Parses LiteLLM model strings and returns structured metadata for UI display. All metadata comes from litellm's model_cost dictionary. Until this upstream patch to LiteLLM is merged (https://github.com/BerriAI/litellm/pull/17330), we use the model_metadata_enrichments.json to add these fie...
272
9,835
onyx
backend/onyx/llm/models.py
.py
from enum import Enum from typing import Literal from pydantic import BaseModel, ConfigDict class LLMErrorInfo(BaseModel): message: str error_code: str is_retryable: bool class ToolChoiceOptions(str, Enum): REQUIRED = "required" AUTO = "auto" NONE = "none" class NamedToolChoice(BaseModel)...
188
5,585
onyx
backend/onyx/llm/model_capabilities.py
.py
"""Capability and token-limit lookups backed by the LiteLLM model map. This module is deliberately lightweight to import: no DB / SQLAlchemy dependencies, and `litellm` itself is only imported lazily at call time. Keep it that way — API schema modules (e.g. `onyx.server.manage.llm.models`) import from here at module s...
478
17,195
onyx
backend/onyx/llm/override_models.py
.py
"""Overrides sent over the wire / stored in the DB NOTE: these models are used in many places, so have to be kepy in a separate file to avoid circular imports. """ from pydantic import BaseModel class LLMOverride(BaseModel): """Per-request LLM settings that override persona defaults. All fields are optiona...
45
1,741
onyx
backend/onyx/llm/constants.py
.py
""" LLM Constants Centralized constants for LLM providers, vendors, and display names. """ from enum import Enum # Provider names class LlmProviderNames(str, Enum): """ Canonical string identifiers for LLM providers. """ OPENAI = "openai" ANTHROPIC = "anthropic" GOOGLE = "google" BEDROC...
385
10,811
onyx
backend/onyx/llm/custom_config_mapping.py
.py
"""Maps LLM provider custom_config keys to LiteLLM completion kwargs. Recognized keys become explicit kwargs and never touch os.environ. Unrecognized keys are env-only: injected into os.environ for the duration of the call when the llm_custom_config_env_injection security setting allows it (self-hosted only, default o...
176
6,889