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/context/search/federated/models.py | .py | from dataclasses import dataclass
from datetime import datetime
from typing import TypedDict
from pydantic import BaseModel
from onyx.onyxbot.slack.models import ChannelType
@dataclass(frozen=True)
class DirectThreadFetch:
"""Request to fetch a Slack thread directly by channel and timestamp."""
channel_id:... | 40 | 834 |
onyx | backend/onyx/context/search/federated/slack_search.py | .py | import json
import re
import time
from datetime import datetime
from typing import Any, cast
from pydantic import BaseModel, ConfigDict, ValidationError
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
from sqlalchemy.orm import Session
from onyx.configs.app_configs import (
ENABLE_CONTE... | 1,357 | 51,320 |
onyx | backend/onyx/context/search/retrieval/search_runner.py | .py | from collections.abc import Callable
from uuid import UUID
from sqlalchemy.orm import Session
from onyx.configs.chat_configs import HYBRID_ALPHA, NUM_RETURNED_HITS
from onyx.context.search.enums import QueryType
from onyx.context.search.models import (
ChunkIndexRequest,
IndexFilters,
InferenceChunk,
... | 212 | 7,155 |
onyx | backend/onyx/feature_flags/feature_flags_keys.py | .py | """
Feature flag keys used throughout the application.
Centralizes feature flag key definitions to avoid magic strings.
"""
| 5 | 124 |
onyx | backend/onyx/feature_flags/factory.py | .py | from onyx.configs.app_configs import DEV_MODE
from onyx.feature_flags.interface import FeatureFlagProvider, NoOpFeatureFlagProvider
from onyx.utils.variable_functionality import (
fetch_versioned_implementation_with_fallback,
)
from shared_configs.configs import MULTI_TENANT
def get_default_feature_flag_provider(... | 29 | 1,100 |
onyx | backend/onyx/feature_flags/interface.py | .py | import abc
from typing import Any
from uuid import UUID
from onyx.db.models import User
class FeatureFlagProvider(abc.ABC):
"""
Abstract base class for feature flag providers.
Implementations should provide vendor-specific logic for checking
whether a feature flag is enabled for a given user.
""... | 69 | 2,038 |
onyx | backend/onyx/federated_connectors/models.py | .py | from datetime import datetime
from typing import Any, Dict, Optional
from pydantic import BaseModel, Field
class FieldSpec(BaseModel):
"""Model for describing a field specification."""
type: str = Field(
..., description="The type of the field (e.g., 'str', 'bool', 'list[str]')"
)
descriptio... | 67 | 2,345 |
onyx | backend/onyx/federated_connectors/federated_retrieval.py | .py | from collections import defaultdict
from collections.abc import Callable
from typing import Any
from uuid import UUID
from pydantic import BaseModel, ConfigDict
from sqlalchemy.orm import Session
from onyx.configs.constants import DocumentSource, FederatedConnectorSource
from onyx.context.search.models import ChunkIn... | 288 | 11,631 |
onyx | backend/onyx/federated_connectors/registry.py | .py | """Registry mapping for federated connector classes."""
from pydantic import BaseModel
from onyx.configs.constants import FederatedConnectorSource
class FederatedConnectorMapping(BaseModel):
module_path: str
class_name: str
# Mapping of FederatedConnectorSource to connector details for lazy loading
FEDERA... | 20 | 551 |
onyx | backend/onyx/federated_connectors/factory.py | .py | """Factory for creating federated connector instances."""
import importlib
from typing import Any, Type
from onyx.configs.constants import FederatedConnectorSource
from onyx.federated_connectors.interfaces import FederatedConnector
from onyx.federated_connectors.registry import FEDERATED_CONNECTOR_CLASS_MAP
from onyx... | 63 | 2,022 |
onyx | backend/onyx/federated_connectors/interfaces.py | .py | from abc import ABC, abstractmethod
from typing import Any, Dict
from onyx.context.search.models import ChunkIndexRequest, InferenceChunk
from onyx.federated_connectors.models import CredentialField, EntityField, OAuthResult
from onyx.onyxbot.slack.models import SlackContext
class FederatedConnector(ABC):
"""Bas... | 121 | 4,127 |
onyx | backend/onyx/federated_connectors/oauth_utils.py | .py | """Generic OAuth utilities for federated connectors API layer."""
import base64
import json
import uuid
from typing import Any
from onyx.cache.factory import get_cache_backend
from onyx.configs.app_configs import WEB_DOMAIN
from onyx.utils.logger import setup_logger
logger = setup_logger()
OAUTH_STATE_PREFIX = "fed... | 152 | 4,471 |
onyx | backend/onyx/federated_connectors/slack/models.py | .py | from typing import Optional
from pydantic import BaseModel, Field, field_validator, model_validator
class SlackEntities(BaseModel):
"""Pydantic model for Slack federated search entities."""
# Channel filtering
search_all_channels: bool = Field(
default=True,
description="Search all acces... | 188 | 6,733 |
onyx | backend/onyx/federated_connectors/slack/federated_connector.py | .py | from datetime import datetime, timedelta, timezone
from typing import Any
from urllib.parse import urlencode
import requests
from pydantic import ValidationError
from slack_sdk import WebClient
from typing_extensions import override
from onyx.context.search.federated.slack_search import slack_retrieval
from onyx.cont... | 316 | 11,482 |
onyx | backend/onyx/external_apps/token_refresh.py | .py | """Lazy, single-flighted OAuth token refresh, called by the egress gate.
The caller passes a tenant-scoped session *factory* (not a session) and ids;
everything else — staleness, the Redis lock, the token POST, persistence — lives
behind :func:`ensure_fresh_credentials`. Each step takes its own short session, so
no co... | 193 | 7,299 |
onyx | backend/onyx/external_apps/models.py | .py | from pydantic import BaseModel
from onyx.db.enums import EndpointPolicy, ExternalAppType
class ActionPolicyView(BaseModel):
"""One action of a built-in app, with its effective policy — the admin's
stored override if set, otherwise the action's ``default_policy``."""
action_id: str
normalised_name: s... | 52 | 1,643 |
onyx | backend/onyx/external_apps/token_utils.py | .py | """Pure, clockless helpers for OAuth token expiry. A leaf module (imports nothing
from providers/orchestrator) so callers can use it without an import cycle.
"""
from datetime import datetime, timedelta
from typing import Any
from onyx.utils.datetime import datetime_to_utc
# Refresh slightly early so no in-flight re... | 63 | 2,575 |
onyx | backend/onyx/external_apps/credentials.py | .py | from typing import Any
from uuid import UUID
from sqlalchemy.orm import Session
from onyx.db.external_app import (
get_external_app_by_id,
get_external_app_user_credential,
)
from onyx.db.models import ExternalApp
def build_auth_headers(
auth_template: dict[str, Any],
credentials: dict[str, Any],
) ... | 82 | 3,080 |
onyx | backend/onyx/external_apps/url_glob.py | .py | import re
from functools import lru_cache
from pydantic import BaseModel, ConfigDict
from onyx.error_handling.error_codes import OnyxErrorCode
from onyx.error_handling.exceptions import OnyxError
_SCHEME_RE = re.compile(r"^https?://", re.IGNORECASE)
@lru_cache(maxsize=1024)
def _to_regex(glob: str) -> str:
ret... | 61 | 1,826 |
onyx | backend/onyx/external_apps/matching/rules.py | .py | """Rule matching as a Strategy: each ``MatchRule`` kind has a matcher object
that knows how to test that kind against a request, looked up through a
registry. Adding a new rule kind is "write a ``RuleMatcher`` + register it" —
the dispatch in ``rule_matches`` never changes (open/closed).
"""
from abc import ABC, abstr... | 87 | 2,913 |
onyx | backend/onyx/external_apps/matching/request.py | .py | """The normalised request the matcher consumes, plus a per-request context that
lazily derives and caches the views rule matchers need."""
from functools import cached_property
from pydantic import BaseModel
from onyx.external_apps.matching.graphql_parsing import parse_invocations
class ProxiedRequest(BaseModel):
... | 41 | 1,549 |
onyx | backend/onyx/external_apps/matching/graphql_parsing.py | .py | """Turns a GraphQL HTTP body into the ``(operation_type, root_field)`` pairs the
matcher reasons about.
Isolated behind one function so the GraphQL library is the only thing this
module knows about — swapping parsers (or hardening the traversal) never touches
the rule-matching layer.
"""
import json
from graphql imp... | 97 | 3,455 |
onyx | backend/onyx/external_apps/matching/engine.py | .py | """Composes recognition + policy resolution into a single verdict for an
outbound request."""
from collections.abc import Iterable, Mapping
from typing import Any
from pydantic import BaseModel, ConfigDict, Field, field_validator
from sqlalchemy.orm import Session
from onyx.db.enums import POLICY_SEVERITY, EndpointP... | 214 | 7,686 |
onyx | backend/onyx/external_apps/presentation/payload_decoders.py | .py | from __future__ import annotations
import base64
import binascii
from email import message_from_bytes, policy
from email.message import EmailMessage
from email.utils import formataddr, getaddresses
from typing import Any, Protocol
class PayloadDecoder(Protocol):
"""A single (provider, action) body-decoding strat... | 128 | 4,767 |
onyx | backend/onyx/external_apps/presentation/decode.py | .py | from typing import Any
from onyx.external_apps.presentation.payload_decoders import PayloadDecoder
from onyx.external_apps.providers.registry import PROVIDERS
from onyx.utils.logger import setup_logger
logger = setup_logger()
# action_type namespaces its provider, so entries can't collide.
_DECODERS: dict[str, Paylo... | 31 | 1,000 |
onyx | backend/onyx/external_apps/providers/google_base.py | .py | from typing import Any
from onyx.db.enums import ExternalAppType
from onyx.error_handling.error_codes import OnyxErrorCode
from onyx.error_handling.exceptions import OnyxError
from onyx.external_apps.providers.actions import EndpointSpec
from onyx.external_apps.providers.base import (
AdminDescriptorSpec,
OAut... | 123 | 4,921 |
onyx | backend/onyx/external_apps/providers/google_calendar.py | .py | from onyx.configs.app_configs import (
EXT_APP_GOOGLE_CALENDAR_CLIENT_ID,
EXT_APP_GOOGLE_CALENDAR_CLIENT_SECRET,
)
from onyx.db.enums import EndpointPolicy, ExternalAppType
from onyx.external_apps.providers.actions import (
EndpointSpec,
ExternalAppAction,
RestRoute,
)
from onyx.external_apps.provid... | 107 | 4,022 |
onyx | backend/onyx/external_apps/providers/slack.py | .py | from typing import Any
from onyx.configs.app_configs import (
EXT_APP_SLACK_CLIENT_ID,
EXT_APP_SLACK_CLIENT_SECRET,
)
from onyx.db.enums import EndpointPolicy, ExternalAppType
from onyx.error_handling.error_codes import OnyxErrorCode
from onyx.error_handling.exceptions import OnyxError
from onyx.external_apps.... | 216 | 8,472 |
onyx | backend/onyx/external_apps/providers/linear.py | .py | from typing import Any
from onyx.configs.app_configs import (
EXT_APP_LINEAR_CLIENT_ID,
EXT_APP_LINEAR_CLIENT_SECRET,
)
from onyx.db.enums import EndpointPolicy, ExternalAppType
from onyx.error_handling.error_codes import OnyxErrorCode
from onyx.error_handling.exceptions import OnyxError
from onyx.external_app... | 171 | 6,438 |
onyx | backend/onyx/external_apps/providers/hubspot.py | .py | from typing import Any
from urllib.parse import quote
import requests
from onyx.configs.app_configs import (
EXT_APP_HUBSPOT_CLIENT_ID,
EXT_APP_HUBSPOT_CLIENT_SECRET,
)
from onyx.db.enums import EndpointPolicy, ExternalAppType
from onyx.error_handling.error_codes import OnyxErrorCode
from onyx.error_handling.... | 275 | 10,848 |
onyx | backend/onyx/external_apps/providers/registry.py | .py | from onyx.db.enums import EndpointPolicy, ExternalAppType
from onyx.db.models import ExternalApp
from onyx.error_handling.error_codes import OnyxErrorCode
from onyx.error_handling.exceptions import OnyxError
from onyx.external_apps.models import (
ActionPolicyView,
BuiltInExternalAppDescriptor,
EndpointDesc... | 232 | 9,351 |
onyx | backend/onyx/external_apps/providers/notion.py | .py | import base64
from typing import Any
from onyx.configs.app_configs import (
EXT_APP_NOTION_CLIENT_ID,
EXT_APP_NOTION_CLIENT_SECRET,
)
from onyx.db.enums import EndpointPolicy, ExternalAppType
from onyx.error_handling.error_codes import OnyxErrorCode
from onyx.error_handling.exceptions import OnyxError
from ony... | 303 | 12,196 |
onyx | backend/onyx/external_apps/providers/google_drive.py | .py | from onyx.configs.app_configs import (
EXT_APP_GOOGLE_DRIVE_CLIENT_ID,
EXT_APP_GOOGLE_DRIVE_CLIENT_SECRET,
)
from onyx.db.enums import EndpointPolicy, ExternalAppType
from onyx.external_apps.providers.actions import (
EndpointSpec,
ExternalAppAction,
RestRoute,
)
from onyx.external_apps.providers.ba... | 242 | 9,431 |
onyx | backend/onyx/external_apps/providers/base.py | .py | from abc import ABC, abstractmethod
from collections.abc import Mapping
from typing import Any, ClassVar
import requests
from pydantic import BaseModel, ConfigDict
from onyx.db.enums import ExternalAppType
from onyx.external_apps.presentation.payload_decoders import PayloadDecoder
from onyx.external_apps.providers.ac... | 400 | 17,026 |
onyx | backend/onyx/external_apps/providers/github.py | .py | from typing import Any
import requests
from onyx.configs.app_configs import (
EXT_APP_GITHUB_CLIENT_ID,
EXT_APP_GITHUB_CLIENT_SECRET,
)
from onyx.db.enums import EndpointPolicy, ExternalAppType
from onyx.error_handling.error_codes import OnyxErrorCode
from onyx.error_handling.exceptions import OnyxError
from ... | 310 | 12,831 |
onyx | backend/onyx/external_apps/providers/gmail.py | .py | from collections.abc import Mapping
from onyx.configs.app_configs import (
EXT_APP_GMAIL_CLIENT_ID,
EXT_APP_GMAIL_CLIENT_SECRET,
)
from onyx.db.enums import EndpointPolicy, ExternalAppType
from onyx.external_apps.presentation.payload_decoders import (
GmailRawMimeDecoder,
PayloadDecoder,
)
from onyx.ex... | 206 | 7,919 |
onyx | backend/onyx/external_apps/providers/actions.py | .py | from enum import Enum
from typing import Annotated, Literal
from pydantic import BaseModel, ConfigDict, Field, InstanceOf, field_validator
from onyx.db.enums import EndpointPolicy
class ExternalAppAction(str, Enum):
"""Marker base for every built-in provider's action-id enum.
Deliberately member-less so ea... | 126 | 5,222 |
onyx | backend/onyx/prompts/prompt_template.py | .py | import re
from onyx.prompts.prompt_utils import replace_current_datetime_tag
class PromptTemplate:
"""
A class for building prompt templates with placeholders.
Useful when building templates with json schemas, as {} will not work with f-strings.
Unlike string.replace, this class will raise an error i... | 58 | 2,081 |
onyx | backend/onyx/prompts/prompt_utils.py | .py | import re
from datetime import datetime
from typing import cast
from langchain_core.messages import BaseMessage
from onyx.auth.login_claims_capture import IDP_PLACEHOLDER_KEYS
from onyx.configs.constants import DocumentSource
from onyx.prompts.chat_prompts import (
ADDITIONAL_INFO,
CITATION_GUIDANCE_REPLACEME... | 335 | 11,132 |
onyx | backend/onyx/prompts/compression_prompts.py | .py | # Prompts for chat history compression via summarization.
# ruff: noqa: E501, W605 start
# Cutoff marker helps the LLM focus on summarizing only messages before this point.
# This improves "needle in haystack" accuracy by explicitly marking where to stop with an exact pattern which is also placed in locations easily a... | 40 | 2,585 |
onyx | backend/onyx/prompts/chat_tools.py | .py | # These prompts are to support tool calling. Currently not used in the main flow or via any configs
# The current generation of LLM is too unreliable for this task.
# Onyx retrieval call as a tool option
DANSWER_TOOL_NAME = "Current Search"
DANSWER_TOOL_DESCRIPTION = "A search tool that can find information on any topi... | 98 | 2,867 |
onyx | backend/onyx/prompts/user_info.py | .py | # ruff: noqa: E501, W605 start
USER_INFORMATION_HEADER = "\n# User Information\n\n"
BASIC_INFORMATION_PROMPT = """
## Basic Information
User name: {user_name}
User email: {user_email}{user_role}
""".lstrip()
# This line only shows up if the user has configured their role.
USER_ROLE_PROMPT = """
User role: {user_role}... | 44 | 1,222 |
onyx | backend/onyx/prompts/image_analysis.py | .py | # Used for creating embeddings of images for vector search
DEFAULT_IMAGE_SUMMARIZATION_SYSTEM_PROMPT = """
You are an assistant for summarizing images for retrieval.
Summarize the content of the following image and be as precise as possible.
The summary will be embedded and used to retrieve the original image.
Therefor... | 22 | 1,012 |
onyx | backend/onyx/prompts/tool_prompts.py | .py | # ruff: noqa: E501, W605 start
# If there are any tools, this section is included, the sections below are for the available tools
TOOL_SECTION_HEADER = "\n# Tools\n\n"
# This section is included if there are search type tools, currently internal_search and web_search
TOOL_DESCRIPTION_SEARCH_GUIDANCE = """
For questio... | 86 | 5,523 |
onyx | backend/onyx/prompts/contextual_retrieval.py | .py | # NOTE: the prompt separation is partially done for efficiency; previously I tried
# to do it all in one prompt with sequential format() calls but this will cause a backend
# error when the document contains any {} as python will expect the {} to be filled by
# format() arguments
# ruff: noqa: E501, W605 start
CONTEXT... | 28 | 1,020 |
onyx | backend/onyx/prompts/search_prompts.py | .py | # How it works and rationale:
# First - this works best empirically across multiple LLMs, some of this is back-explaining reasons based on results.
#
# The system prompt is kept simple and as similar to typical system prompts as possible to stay within training distribution.
# The history is passed through as a list of... | 202 | 9,563 |
onyx | backend/onyx/prompts/constants.py | .py | # ruff: noqa: E501, W605 start
CODE_BLOCK_PAT = "```\n{}\n```"
TRIPLE_BACKTICK = "```"
SYSTEM_REMINDER_TAG_OPEN = "<system-reminder>"
SYSTEM_REMINDER_TAG_CLOSE = "</system-reminder>"
# Tags format inspired by Anthropic and OpenCode
REMINDER_TAG_NO_HEADER = f"""
User messages may include {SYSTEM_REMINDER_TAG_OPEN} and ... | 18 | 736 |
onyx | backend/onyx/prompts/federated_search.py | .py | from onyx.configs.app_configs import MAX_SLACK_QUERY_EXPANSIONS
SLACK_QUERY_EXPANSION_PROMPT = f"""
Rewrite the user's query into at most {MAX_SLACK_QUERY_EXPANSIONS} keyword-only queries for Slack's keyword search.
Slack search behavior:
- Pure keyword AND search (no semantics)
- More words = fewer matches, so keep ... | 86 | 2,340 |
onyx | backend/onyx/prompts/kg_prompts.py | .py | # Standards
SEPARATOR_LINE = "-------"
SEPARATOR_LINE_LONG = "---------------"
NO_EXTRACTION = "No extraction of knowledge graph objects was feasible."
YES = "yes"
NO = "no"
# Framing/Support/Template Prompts
ENTITY_TYPE_SETTING_PROMPT = f"""
{SEPARATOR_LINE}
{{entity_types}}
{SEPARATOR_LINE}
""".strip()
RELATIONSHIP... | 1,459 | 74,038 |
onyx | backend/onyx/prompts/basic_memory.py | .py | # ruff: noqa: E501, W605 start
# Note that the user_basic_information is only included if we have at least 1 of the following: user_name, user_email, user_role
# This is included because sometimes we need to know the user's name or basic info to best generate the memory.
FULL_MEMORY_UPDATE_PROMPT = """
You are a memor... | 39 | 1,704 |
onyx | backend/onyx/prompts/filter_extration.py | .py | # The following prompts are used for extracting filters to apply along with the query in the
# document index. For example, a filter for dates or a filter by source type such as GitHub
# or Slack
SOURCES_KEY = "sources"
# Used in source_filter.py: decide which connected source(s) an internal search
# cycle should cove... | 175 | 7,924 |
onyx | backend/onyx/prompts/chat_prompts.py | .py | # ruff: noqa: E501, W605 start
from onyx.prompts.constants import REMINDER_TAG_NO_HEADER
DATETIME_REPLACEMENT_PAT = "{{CURRENT_DATETIME}}"
CITATION_GUIDANCE_REPLACEMENT_PAT = "{{CITATION_GUIDANCE}}"
REMINDER_TAG_REPLACEMENT_PAT = "{{REMINDER_TAG_DESCRIPTION}}"
# Note this uses a string pattern replacement so the us... | 127 | 5,761 |
onyx | backend/onyx/prompts/deep_research/research_agent.py | .py | from onyx.prompts.deep_research.dr_tool_prompts import (
GENERATE_REPORT_TOOL_NAME,
THINK_TOOL_NAME,
)
MAX_RESEARCH_CYCLES = 8
# ruff: noqa: E501, W605 start
RESEARCH_AGENT_PROMPT = f"""
You are a highly capable, thoughtful, and precise research agent that conducts research on a specific topic. Prefer being t... | 102 | 6,131 |
onyx | backend/onyx/prompts/deep_research/dr_tool_prompts.py | .py | GENERATE_PLAN_TOOL_NAME = "generate_plan"
GENERATE_REPORT_TOOL_NAME = "generate_report"
RESEARCH_AGENT_TOOL_NAME = "research_agent"
# This is to ensure that even the non-reasoning models can have an ok time with this more complex flow.
THINK_TOOL_NAME = "think_tool"
# ruff: noqa: E501, W605 start
# Hard for th... | 45 | 2,182 |
onyx | backend/onyx/prompts/deep_research/orchestration_layer.py | .py | from onyx.prompts.deep_research.dr_tool_prompts import (
GENERATE_PLAN_TOOL_NAME,
GENERATE_REPORT_TOOL_NAME,
RESEARCH_AGENT_TOOL_NAME,
THINK_TOOL_NAME,
)
# ruff: noqa: E501, W605 start
CLARIFICATION_PROMPT = f"""
You are a clarification agent that runs prior to deep research. Assess whether you need to... | 209 | 13,446 |
onyx | backend/onyx/prompts/coding_agent/coding_agent.py | .py | from onyx.coding_agent.mock_tools import BASH_TOOL_NAME, GENERATE_ANSWER_TOOL_NAME
from onyx.deep_research.dr_mock_tools import THINK_TOOL_NAME
MAX_CODING_AGENT_CYCLES = 20
# ruff: noqa: E501, W605 start
CODING_AGENT_PROMPT = f"""
You are a careful, precise code investigator. Your job is to answer questions about a s... | 171 | 14,615 |
onyx | backend/onyx/auth/oidc_client.py | .py | """Hardened OIDC client for multi-IdP SSO. Two guarantees on top of the
stock client: the email claim is trusted only when the IdP marks it
verified, and the discovery document's issuer must own the configured
discovery URL, so one provider's tokens cannot be replayed against another
provider's callback (OIDC mix-up de... | 157 | 6,599 |
onyx | backend/onyx/auth/anonymous_user.py | .py | from collections.abc import Mapping
from typing import Any, cast
from onyx.auth.schemas import UserRole
from onyx.configs.constants import (
ANONYMOUS_USER_EMAIL,
ANONYMOUS_USER_INFO_ID,
KV_ANONYMOUS_USER_PERSONALIZATION_KEY,
KV_ANONYMOUS_USER_PREFERENCES_KEY,
)
from onyx.key_value_store.store import K... | 62 | 2,044 |
onyx | backend/onyx/auth/pkce.py | .py | """PKCE (RFC 7636) S256 transform for the mobile SSO bridge.
Used by the mobile SSO code store to verify the app's ``code_verifier``. The web
OAuth flow computes the same transform independently in
``users.generate_pkce_pair``; a test pins that the two agree so they can't drift.
"""
import base64
import hashlib
def... | 20 | 757 |
onyx | backend/onyx/auth/utils.py | .py | """Shared authentication utilities for bearer token extraction and validation."""
from collections.abc import Callable
from urllib.parse import unquote
from fastapi import Request
from onyx.auth.constants import (
API_KEY_HEADER_ALTERNATIVE_NAME,
API_KEY_HEADER_NAME,
API_KEY_PREFIX,
BEARER_PREFIX,
... | 111 | 3,213 |
onyx | backend/onyx/auth/jwt.py | .py | import json
from enum import Enum
from functools import lru_cache
from typing import Any, cast
import jwt
import requests
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
from jwt import InvalidTokenError, PyJWTError
from jwt import decode as jwt_decode
from jwt.algorithms import RSAAlgorithm # ... | 161 | 4,950 |
onyx | backend/onyx/auth/sso_tenant_token.py | .py | """Signed workspace pin for an in-flight cloud SSO login.
Cloud serves every workspace from one domain, so the SSO login routes have no
tenant until the user identifies themselves. Discovery resolves the workspace
from the catalog and returns this token. The authorize call presents it to
select the schema holding the ... | 54 | 2,008 |
onyx | backend/onyx/auth/invited_users.py | .py | from typing import cast
from onyx.configs.constants import KV_PENDING_USERS_KEY, KV_USER_STORE_KEY
from onyx.key_value_store.factory import get_kv_store
from onyx.key_value_store.interface import KvKeyNotFoundError
from onyx.utils.special_types import JSON_ro
def remove_user_from_invited_users(email: str) -> int:
... | 46 | 1,359 |
onyx | backend/onyx/auth/captcha.py | .py | """Captcha verification for user registration.
Two flows share this module:
1. Email/password signup — ``UserManager.create`` verifies the token
posted with the signup body.
2. Google OAuth signup — the frontend pre-verifies a token, the backend
sets a signed cookie, and ``CaptchaCookieMiddleware`` checks the
... | 296 | 9,829 |
onyx | backend/onyx/auth/email_utils.py | .py | import base64
import smtplib
from datetime import datetime
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formatdate, make_msgid
import sendgrid
from sendgrid.helpers.mail import (
Attachment,
Content,
Conte... | 516 | 15,358 |
onyx | backend/onyx/auth/users.py | .py | import base64
import hashlib
import os
import random
import secrets
import string
import uuid
from collections.abc import AsyncGenerator, Sequence
from contextlib import asynccontextmanager
from datetime import datetime, timedelta, timezone
from functools import partial
from typing import Any, Dict, List, Literal, Opti... | 2,994 | 113,650 |
onyx | backend/onyx/auth/api_key.py | .py | import hashlib
import secrets
import uuid
from urllib.parse import quote
from fastapi import Request
from passlib.hash import sha256_crypt
from pydantic import BaseModel
from onyx.auth.constants import (
API_KEY_LENGTH,
API_KEY_PREFIX,
DEPRECATED_API_KEY_PREFIX,
)
from onyx.auth.schemas import UserRole
fr... | 73 | 2,254 |
onyx | backend/onyx/auth/session_tokens.py | .py | """Redis session-token value format and rejection classification.
Token values embed their logical expiry; the physical TTL adds a grace window
and logout writes a tombstone instead of deleting, so a rejected token can be
classified: EXPIRED (embedded expiry passed), TERMINATED (tombstone), NOT_FOUND
(no entry: cookie... | 227 | 7,884 |
onyx | backend/onyx/auth/sso_web_error.py | .py | """Render SSO callback failures for browsers and drop the flow's PKCE cookie.
Non-legacy OIDC provider rows and all SAML callbacks terminate directly in
FastAPI (no Next.js wrapper), so an ``OnyxError`` from those handlers would
reach the browser as raw JSON. This decorator converts it into a redirect to
the ``/auth/e... | 83 | 2,923 |
onyx | backend/onyx/auth/constants.py | .py | """Authentication constants shared across auth modules."""
# API Key constants
API_KEY_PREFIX = "on_"
DEPRECATED_API_KEY_PREFIX = "dn_"
API_KEY_LENGTH = 192
# PAT constants
PAT_PREFIX = "onyx_pat_"
PAT_LENGTH = 192
# Shared header constants
API_KEY_HEADER_NAME = "Authorization"
API_KEY_HEADER_ALTERNATIVE_NAME = "X-O... | 16 | 365 |
onyx | backend/onyx/auth/sso_url_guard.py | .py | """Stop a tenant admin from aiming the OIDC discovery URL, or the endpoints it
names, at an address the server should not fetch."""
from urllib.parse import urlsplit
from onyx.server.security.models import outbound_ssrf_params
from onyx.server.security.store import get_security_settings
from onyx.utils.url import SSR... | 54 | 1,927 |
onyx | backend/onyx/auth/pat.py | .py | """Personal Access Token generation and validation."""
import hashlib
import secrets
from datetime import datetime, timedelta, timezone
from urllib.parse import quote
from fastapi import Request
from onyx.auth.constants import PAT_LENGTH, PAT_PREFIX
from onyx.auth.utils import get_hashed_bearer_token_from_request
fr... | 58 | 1,970 |
onyx | backend/onyx/auth/oauth_refresher.py | .py | import asyncio
import os
import time
import uuid
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional, cast
import httpx
from fastapi.concurrency import run_in_threadpool
from fastapi_users.manager import BaseUserManager
from sqlalchemy.ext.async... | 476 | 18,258 |
onyx | backend/onyx/auth/permissions.py | .py | """
Permission resolution for group-based authorization.
Granted permissions are stored as a JSONB column on the User table and
loaded for free with every auth query. Implied permissions are expanded
at read time — only directly granted permissions are persisted.
"""
from collections.abc import Callable, Coroutine
fr... | 138 | 5,310 |
onyx | backend/onyx/auth/schemas.py | .py | import uuid
from enum import Enum
from typing import Any
from fastapi_users import schemas
from typing_extensions import override
from onyx.db.enums import AccountType
class UserRole(str, Enum):
"""
User roles
- Basic can't perform any admin actions
- Admin can perform all admin actions
- Curato... | 80 | 2,439 |
onyx | backend/onyx/auth/signup_rate_limit.py | .py | """Per-IP rate limit on email/password signup."""
import time
from fastapi import Request
from onyx.configs.app_configs import SIGNUP_RATE_LIMIT_ENABLED
from onyx.error_handling.error_codes import OnyxErrorCode
from onyx.error_handling.exceptions import OnyxError
from onyx.redis.redis_pool import get_async_redis_con... | 73 | 2,203 |
onyx | backend/onyx/auth/oauth_token_manager.py | .py | import time
from typing import Any
from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse
from uuid import UUID
import requests
from pydantic import BaseModel
from sqlalchemy.orm import Session
from onyx.db.models import OAuthConfig, OAuthUserToken
from onyx.db.oauth_config import get_user_oauth_token, u... | 316 | 11,894 |
onyx | backend/onyx/auth/login_claims_capture.py | .py | """Capture the identity attributes an IdP sends at login and derive a
directory profile from them, independent of login protocol.
Both protocols feed this module: OAuth/OIDC logins contribute id_token and
userinfo claims (plus the Microsoft Graph profile for Entra ID), and SAML
logins contribute assertion attributes. ... | 606 | 25,451 |
onyx | backend/onyx/auth/disposable_email_validator.py | .py | """
Utility to validate and block disposable/temporary email addresses.
This module fetches a list of known disposable email domains from a remote source
and caches them for performance. It's used during user registration to prevent
abuse from temporary email services.
"""
import threading
import time
from typing imp... | 196 | 6,177 |
onyx | backend/onyx/auth/mobile_sso/__init__.py | .py | """Mobile SSO bridge.
Backend support for native-mobile (Expo / React Native) OAuth/SSO login. The
app runs the OAuth dance in the system browser (reusing the existing, already
registered IdP callback) and the backend returns a single-use, PKCE-bound
one-time code over a custom-scheme deep link — never a token. The ap... | 14 | 629 |
onyx | backend/onyx/auth/mobile_sso/tokens.py | .py | """Token-issuance seam for mobile auth.
A single indirection point for minting the credential a native client receives.
Today it mints the SAME session token the web cookie flow uses (via the active
strategy's ``write_token``) — server-revocable under the redis/postgres backends,
a self-contained non-revocable JWT und... | 21 | 818 |
onyx | backend/onyx/auth/mobile_sso/sso_completion.py | .py | """Shared SSO completion for native mobile clients.
Every OAuth/SSO provider callback (Google today; OIDC / SAML / Apple later)
funnels through ``complete_mobile_sso`` once the signed state carries the mobile
marker. It mints the session token, stashes it behind a single-use PKCE-bound
code, and 302-redirects to the a... | 122 | 5,229 |
onyx | backend/onyx/auth/mobile_sso/code_store.py | .py | """One-time, PKCE-bound SSO code store (Redis).
The mobile SSO bridge never puts a session token on the (interceptable)
custom-scheme deep link. Instead the backend stores the freshly minted token in
Redis under a short-lived, single-use code bound to an app-supplied PKCE
challenge, and hands the deep link only that o... | 91 | 3,963 |
onyx | backend/onyx/mcp_server/utils.py | .py | """Utility helpers for the Onyx MCP server."""
from __future__ import annotations
import httpx
from fastmcp.server.auth.auth import AccessToken
from fastmcp.server.dependencies import get_access_token
from pydantic import BaseModel, TypeAdapter
from onyx.utils.logger import setup_logger
from onyx.utils.variable_func... | 129 | 4,156 |
onyx | backend/onyx/mcp_server/auth.py | .py | """Authentication helpers for the Onyx MCP server."""
from typing import Optional
from fastmcp.server.auth.auth import AccessToken, TokenVerifier
from onyx.mcp_server.utils import get_http_client
from onyx.server.metrics.mcp_server import MCPAuthResult, record_mcp_auth_result
from onyx.utils.logger import setup_logg... | 51 | 1,753 |
onyx | backend/onyx/mcp_server/api.py | .py | """MCP server with FastAPI wrapper."""
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, Response
from fastmcp import FastMCP
from starlette.datastruc... | 120 | 4,232 |
onyx | backend/onyx/mcp_server/tools/__init__.py | .py | """Tool registrations for the Onyx MCP server."""
# Import tool modules so decorators execute when the package is imported.
from onyx.mcp_server.tools import search # noqa: F401
| 5 | 180 |
onyx | backend/onyx/mcp_server/tools/search.py | .py | """Search tools for MCP server - document and web search."""
import time
from datetime import datetime
from typing import Any
import httpx
from fastmcp.server.auth.auth import AccessToken
from pydantic import BaseModel, TypeAdapter, ValidationError
from onyx.configs.constants import DocumentSource
from onyx.mcp_serv... | 352 | 12,766 |
onyx | backend/onyx/mcp_server/resources/indexed_sources.py | .py | """Resources that expose metadata for the Onyx MCP server."""
from __future__ import annotations
import json
from onyx.mcp_server.api import mcp_server
from onyx.mcp_server.utils import get_indexed_sources, require_access_token
from onyx.utils.logger import setup_logger
logger = setup_logger()
@mcp_server.resourc... | 38 | 1,122 |
onyx | backend/onyx/mcp_server/resources/__init__.py | .py | """Resource registrations for the Onyx MCP server."""
# Import resource modules so decorators execute when the package loads.
from onyx.mcp_server.resources import (
document_sets, # noqa: F401
indexed_sources, # noqa: F401
)
| 8 | 237 |
onyx | backend/onyx/mcp_server/resources/document_sets.py | .py | """Resource exposing document sets available to the current user."""
from __future__ import annotations
import json
from onyx.mcp_server.api import mcp_server
from onyx.mcp_server.utils import get_accessible_document_sets, require_access_token
from onyx.utils.logger import setup_logger
logger = setup_logger()
@mc... | 41 | 1,314 |
onyx | backend/onyx/natural_language_processing/search_nlp_models.py | .py | import asyncio
import json
import os
import threading
import time
from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor, as_completed
from functools import wraps
from types import TracebackType
from typing import Any, cast
import aioboto3
import httpx
import requests
import voyageai
fr... | 1,466 | 54,017 |
onyx | backend/onyx/natural_language_processing/query_embedding_cache.py | .py | """Tenant-scoped Redis/Postgres cache for query embeddings.
Sits in front of ``EmbeddingModel.encode`` for ``EmbedTextType.QUERY`` calls. A
cache hit avoids a network round-trip to the embedding provider.
Tenancy is handled by ``TenantRedis`` automatically prefixing every key with the
current tenant id, so two tenant... | 265 | 8,647 |
onyx | backend/onyx/natural_language_processing/utils.py | .py | import os
from abc import ABC, abstractmethod
from copy import copy
from tokenizers import Encoding, Tokenizer
from onyx.configs.model_configs import DOCUMENT_ENCODER_MODEL
from onyx.context.search.models import InferenceChunk
from onyx.utils.logger import setup_logger
from shared_configs.configs import DOC_EMBEDDING... | 277 | 9,105 |
onyx | backend/onyx/natural_language_processing/english_stopwords.py | .py | import re
ENGLISH_STOPWORDS = [
"a",
"about",
"above",
"after",
"again",
"against",
"ain",
"all",
"am",
"an",
"and",
"any",
"are",
"aren",
"aren't",
"as",
"at",
"be",
"because",
"been",
"before",
"being",
"below",
"between"... | 226 | 3,238 |
onyx | backend/onyx/natural_language_processing/exceptions.py | .py | class ModelServerRateLimitError(Exception):
"""
Exception raised for rate limiting errors from the model server.
"""
class CohereBillingLimitError(Exception):
"""
Raised when Cohere rejects requests because the billing cap is reached.
"""
| 11 | 265 |
onyx | backend/onyx/natural_language_processing/constants.py | .py | """
Constants for natural language processing, including embedding and reranking models.
This file contains constants moved from model_server to support the gradual migration
of API-based calls to bypass the model server.
"""
from shared_configs.enums import EmbeddingProvider, EmbedTextType
# Default model names for... | 39 | 1,349 |
onyx | backend/onyx/voice/factory.py | .py | from onyx.db.models import VoiceProvider
from onyx.voice.interface import VoiceProviderInterface
def get_voice_provider(provider: VoiceProvider) -> VoiceProviderInterface:
"""
Factory function to get the appropriate voice provider implementation.
Args:
provider: VoiceProvider model instance (can ... | 71 | 2,212 |
onyx | backend/onyx/voice/interface.py | .py | from abc import ABC, abstractmethod
from collections.abc import AsyncIterator
from typing import Protocol
from pydantic import BaseModel
class TranscriptResult(BaseModel):
"""Result from streaming transcription."""
text: str
"""The accumulated transcript text."""
is_vad_end: bool = False
"""Tru... | 182 | 5,215 |
onyx | backend/onyx/voice/providers/openai.py | .py | """OpenAI voice provider for STT and TTS.
- STT chunked: `/v1/audio/transcriptions` with the provider's `stt_model`.
- STT streaming: GA Realtime WS, always `gpt-realtime-whisper`. No server-side
VAD on this model, so `close()` sends an explicit `input_audio_buffer.commit`.
- TTS: HTTP streaming, tts-1 / tts-1-hd.
"... | 659 | 25,977 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.