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/skills/ingest_from_github.py | .py | """Fetch and discover skill bundles in GitHub repository archives."""
from __future__ import annotations
import io
import tarfile
import zipfile
from pathlib import PurePosixPath
from typing import Final
from onyx.error_handling.error_codes import OnyxErrorCode
from onyx.error_handling.exceptions import OnyxError
fr... | 280 | 10,337 |
onyx | backend/onyx/skills/bundle.py | .py | """Custom skill bundle validation and helpers."""
from __future__ import annotations
import hashlib
import io
import os
import stat
import sys
import zipfile
from contextlib import ExitStack
from copy import copy
from dataclasses import dataclass
from typing import IO, Final
from onyx.error_handling.error_codes impo... | 670 | 24,149 |
onyx | backend/onyx/skills/validation.py | .py | """Validation for custom skill bundles already stored in FileStore."""
from __future__ import annotations
import io
import zipfile
from dataclasses import dataclass
from onyx.db.file_record import FileRecordNotFoundError
from onyx.db.models import Skill
from onyx.error_handling.exceptions import OnyxError
from onyx.... | 133 | 4,132 |
onyx | backend/onyx/skills/built_in.py | .py | """Codified built-in skill definitions.
``_REGISTRY`` is the single source of truth: one provider per built-in skill,
one of two kinds —
- ``SeededBuiltInProvider``: a plain built-in skill whose ``skill`` rows are
owned by Alembic migrations.
- ``ExternalAppBuiltInProvider``: a built-in skill backed by a connectabl... | 222 | 9,178 |
onyx | backend/onyx/skills/builtin/google-drive/gdrive_api.py | .py | #!/usr/bin/env python3
"""Google Drive wrapper for the Onyx Craft sandbox.
Common operations exposed as subcommands. Output is JSON on stdout. No auth is
handled here: the sandbox egress proxy injects the connected user's bearer token.
Writes (create/upload/edit/delete) may pause for user approval at the proxy.
"""
i... | 662 | 24,235 |
onyx | backend/onyx/skills/builtin/google-drive/gslides_api.py | .py | #!/usr/bin/env python3
"""Google Slides wrapper for the Onyx Craft sandbox.
Common operations exposed as subcommands. Output is JSON on stdout. No auth is
handled here: the sandbox egress proxy injects the connected user's bearer token.
Writes (create / add-slide / text edits / batch-update) may pause for user
approva... | 301 | 10,839 |
onyx | backend/onyx/skills/builtin/google-drive/gsheets_api.py | .py | #!/usr/bin/env python3
"""Google Sheets wrapper for the Onyx Craft sandbox.
Common operations exposed as subcommands. Output is JSON on stdout. No auth is
handled here: the sandbox egress proxy injects the connected user's bearer token.
Writes (create / update / append / clear / batch-update) may pause for user
approv... | 260 | 9,277 |
onyx | backend/onyx/skills/builtin/pptx/scripts/thumbnail.py | .py | """Create thumbnail grids from PowerPoint presentation slides.
Creates a grid layout of slide thumbnails for quick visual analysis.
Labels each thumbnail with its XML filename (e.g., slide1.xml).
Hidden slides are shown with a placeholder pattern.
Usage:
python thumbnail.py input.pptx [output_prefix] [--cols N]
... | 290 | 8,785 |
onyx | backend/onyx/skills/builtin/pptx/scripts/clean.py | .py | """Remove unreferenced files from an unpacked PPTX directory.
Usage: python clean.py <unpacked_dir>
Example:
python clean.py unpacked/
This script removes:
- Orphaned slides (not in sldIdLst) and their relationships
- [trash] directory (unreferenced files)
- Orphaned .rels files for deleted resources
- Unreferen... | 295 | 9,682 |
onyx | backend/onyx/skills/builtin/pptx/scripts/preview.py | .py | """Generate slide preview images from a PowerPoint file.
Converts PPTX -> PDF -> JPEG slides with caching. If cached slides
already exist and are up-to-date, returns them without reconverting.
Output protocol (stdout):
Line 1: status — one of CACHED, GENERATED, ERROR_NOT_FOUND, ERROR_NO_PDF
Lines 2+: sorted a... | 115 | 2,995 |
onyx | backend/onyx/skills/builtin/pptx/scripts/lint.py | .py | """Deterministic layout linter for PowerPoint files.
Statically checks a .pptx for mechanical layout defects that vision QA is
slow and unreliable at catching:
BOUNDS shape partially or fully off the slide canvas
MARGIN text content closer than the profile margin (0.5" standard /
0.25" den... | 892 | 31,560 |
onyx | backend/onyx/skills/builtin/pptx/scripts/add_slide.py | .py | """Add a new slide to an unpacked PPTX directory.
Usage: python add_slide.py <unpacked_dir> <source>
The source can be:
- A slide file (e.g., slide2.xml) - duplicates the slide
- A layout file (e.g., slideLayout2.xml) - creates from layout
Examples:
python add_slide.py unpacked/ slide2.xml
# Duplicates s... | 220 | 7,099 |
onyx | backend/onyx/skills/builtin/pptx/scripts/chart.py | .py | """Deck-styled matplotlib baseline for slide charts.
Usage (from the session workspace):
import sys
sys.path.insert(0, ".opencode/skills/pptx/scripts")
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from chart import deck_style, save_for_slide
with deck_style(pale... | 96 | 2,965 |
onyx | backend/onyx/skills/builtin/pptx/scripts/office/unpack.py | .py | """Unpack Office files (DOCX, PPTX, XLSX) for editing.
Extracts the ZIP archive, pretty-prints XML files, and optionally:
- Merges adjacent runs with identical formatting (DOCX only)
- Simplifies adjacent tracked changes from same author (DOCX only)
Usage:
python unpack.py <office_file> <output_dir> [options]
Ex... | 132 | 4,041 |
onyx | backend/onyx/skills/builtin/pptx/scripts/office/validate.py | .py | """
Command line tool to validate Office document XML files against XSD schemas and tracked changes.
Usage:
python validate.py <path> [--original <original_file>] [--auto-repair] [--author NAME]
The first argument can be either:
- An unpacked directory containing the Office document XML files
- A packed Office fi... | 126 | 3,878 |
onyx | backend/onyx/skills/builtin/pptx/scripts/office/soffice.py | .py | """
Helper for running LibreOffice (soffice) in environments where AF_UNIX
sockets may be blocked (e.g., sandboxed VMs). Detects the restriction
at runtime and applies an LD_PRELOAD shim if needed.
Usage:
from office.soffice import run_soffice, get_soffice_env
# Option 1 – run soffice directly
result = r... | 182 | 5,299 |
onyx | backend/onyx/skills/builtin/pptx/scripts/office/pack.py | .py | """Pack a directory into a DOCX, PPTX, or XLSX file.
Validates with auto-repair, condenses XML formatting, and creates the Office file.
Usage:
python pack.py <input_directory> <output_file> [--original <file>] [--validate true|false]
Examples:
python pack.py unpacked/ output.docx --original input.docx
py... | 160 | 4,991 |
onyx | backend/onyx/skills/builtin/pptx/scripts/office/validators/redlining.py | .py | """
Validator for tracked changes in Word documents.
"""
import subprocess
import tempfile
import zipfile
from pathlib import Path
class RedliningValidator:
def __init__(self, unpacked_dir, original_docx, verbose=False, author="Claude"):
self.unpacked_dir = Path(unpacked_dir)
self.original_docx =... | 251 | 9,249 |
onyx | backend/onyx/skills/builtin/pptx/scripts/office/validators/pptx.py | .py | """
Validator for PowerPoint presentation XML files against XSD schemas.
"""
import re
from .base import BaseSchemaValidator
class PPTXSchemaValidator(BaseSchemaValidator):
PRESENTATIONML_NAMESPACE = (
"http://schemas.openxmlformats.org/presentationml/2006/main"
)
ELEMENT_RELATIONSHIP_TYPES = {... | 274 | 9,801 |
onyx | backend/onyx/skills/builtin/pptx/scripts/office/validators/docx.py | .py | """
Validator for Word document XML files against XSD schemas.
"""
import random
import re
import tempfile
import zipfile
import defusedxml.minidom
import lxml.etree
from .base import BaseSchemaValidator
class DOCXSchemaValidator(BaseSchemaValidator):
WORD_2006_NAMESPACE = "http://schemas.openxmlformats.org/wo... | 444 | 16,285 |
onyx | backend/onyx/skills/builtin/pptx/scripts/office/validators/base.py | .py | """
Base validator with common validation logic for document files.
"""
import re
from pathlib import Path
import defusedxml.minidom
import lxml.etree
class BaseSchemaValidator:
IGNORED_VALIDATION_ERRORS = [
"hyphenationZone",
"purl.org/dc/terms",
]
UNIQUE_ID_REQUIREMENTS = {
"c... | 856 | 32,896 |
onyx | backend/onyx/skills/builtin/pptx/scripts/office/helpers/merge_runs.py | .py | """Merge adjacent runs with identical formatting in DOCX.
Merges adjacent <w:r> elements that have identical <w:rPr> properties.
Works on runs in paragraphs and inside tracked changes (<w:ins>, <w:del>).
Also:
- Removes rsid attributes from runs (revision metadata that doesn't affect rendering)
- Removes proofErr ele... | 194 | 5,559 |
onyx | backend/onyx/skills/builtin/pptx/scripts/office/helpers/simplify_redlines.py | .py | """Simplify tracked changes by merging adjacent w:ins or w:del elements.
Merges adjacent <w:ins> elements from the same author into a single element.
Same for <w:del> elements. This makes heavily-redlined documents easier to
work with by reducing the number of tracked change wrappers.
Rules:
- Only merges w:ins with ... | 203 | 6,069 |
onyx | backend/onyx/skills/builtin/gmail/gmail_api.py | .py | #!/usr/bin/env python3
"""Gmail wrapper for the Onyx Craft sandbox.
Common operations exposed as subcommands. Output is JSON on stdout. The
Authorization header is injected by the Onyx egress gateway from the connected
user's credentials, so no token handling happens here.
"""
import argparse
import base64
import jso... | 416 | 14,720 |
onyx | backend/onyx/skills/builtin/hubspot/hubspot_api.py | .py | #!/usr/bin/env python3
"""HubSpot CRM (REST v3) wrapper for the Onyx Craft sandbox.
Common CRM operations exposed as subcommands. Authentication is handled by
the egress proxy, which injects the connected user's bearer token on the
wire — this script sends no credentials itself. User input is passed as
JSON request bo... | 275 | 10,193 |
onyx | backend/onyx/skills/builtin/slack/slack_api.py | .py | #!/usr/bin/env python3
"""Slack Web API wrapper for the Onyx Craft sandbox.
Common Slack operations exposed as subcommands. Output is JSON on stdout.
Slack signals failure with {"ok": false, "error": "..."} (still HTTP 200).
"""
import argparse
import json
import os
import re
import sys
import urllib.error
import url... | 279 | 9,805 |
onyx | backend/onyx/skills/builtin/linear/linear_api.py | .py | #!/usr/bin/env python3
"""Linear (GraphQL) wrapper for the Onyx Craft sandbox.
Common operations exposed as subcommands. User input is passed as
GraphQL *variables* (never string-formatted into the query), so there
is no injection risk. Output is JSON on stdout.
"""
import argparse
import json
import re
import sys
im... | 323 | 12,027 |
onyx | backend/onyx/skills/builtin/notion/notion_api.py | .py | #!/usr/bin/env python3
"""Notion REST API wrapper for the Onyx Craft sandbox.
Common Notion operations exposed as subcommands. The connected user's token is
injected by the egress gateway, so this script sends no credentials itself.
Output is JSON on stdout; Notion signals failure with a non-2xx status and a
``{"code"... | 345 | 12,451 |
onyx | backend/onyx/skills/builtin/google-calendar/gcal_api.py | .py | #!/usr/bin/env python3
"""Google Calendar wrapper for the Onyx Craft sandbox.
Common operations exposed as subcommands. Output is JSON on stdout.
"""
import argparse
import json
import sys
import urllib.error
import urllib.parse
import urllib.request
from typing import Any
_BASE = "https://www.googleapis.com/calenda... | 220 | 7,417 |
onyx | backend/onyx/file_store/utils.py | .py | import base64
from collections.abc import Callable
from io import BytesIO
from typing import cast
from uuid import UUID
import requests
from sqlalchemy.orm import Session
from onyx.configs.app_configs import WEB_DOMAIN
from onyx.configs.constants import FileOrigin
from onyx.db.models import UserFile
from onyx.db.user... | 396 | 13,925 |
onyx | backend/onyx/file_store/staging.py | .py | from collections.abc import Callable
from typing import IO, Any
from sqlalchemy.orm import Session
from onyx.configs.constants import FileOrigin
from onyx.db.file_record import (
get_staged_file_ids_by_index_attempt_id,
get_staged_file_ids_for_cc_pair_excluding_attempt,
update_filerecord_origin,
)
from on... | 180 | 5,955 |
onyx | backend/onyx/file_store/gcs_file_store.py | .py | from __future__ import annotations
import json
import tempfile
import uuid
from io import BytesIO
from typing import IO, TYPE_CHECKING, Any, cast
import puremagic
from sqlalchemy.orm import Session
if TYPE_CHECKING:
from google.cloud.storage import Client as GCSClient
from onyx.configs.constants import FileOrig... | 419 | 16,274 |
onyx | backend/onyx/file_store/models.py | .py | import base64
import threading
from enum import Enum
from typing import Callable, NotRequired
from pydantic import BaseModel
from typing_extensions import TypedDict # noreorder
# Sidecar attribute names used by the lazy-content materialization shim. They
# live on the instance via object.__setattr__ rather than as P... | 150 | 5,286 |
onyx | backend/onyx/file_store/azure_blob_file_store.py | .py | from __future__ import annotations
import tempfile
import uuid
from io import BytesIO
from typing import IO, TYPE_CHECKING, Any, cast
import puremagic
from sqlalchemy.orm import Session
if TYPE_CHECKING:
from azure.storage.blob import BlobServiceClient
from onyx.configs.constants import FileOrigin
from onyx.db.... | 478 | 18,969 |
onyx | backend/onyx/file_store/constants.py | .py | MAX_IN_MEMORY_SIZE = 30 * 1024 * 1024 # 30MB
STANDARD_CHUNK_SIZE = 10 * 1024 * 1024 # 10MB chunks
# Marks a blob a content-free chat turn produced, so cleanup can find it by the
# record itself rather than by anything that can expire.
INCOGNITO_SESSION_METADATA_KEY = "incognito_session_id"
| 7 | 294 |
onyx | backend/onyx/file_store/postgres_file_store.py | .py | """PostgreSQL-backed file store using Large Objects.
Stores file content directly in PostgreSQL via the Large Object facility,
eliminating the need for an external S3/MinIO service.
"""
import tempfile
import uuid
from io import BytesIO
from typing import IO, Any, cast
import puremagic
from psycopg2.extensions impor... | 349 | 12,311 |
onyx | backend/onyx/file_store/file_store.py | .py | import hashlib
import tempfile
import uuid
from abc import ABC, abstractmethod
from io import BytesIO
from typing import IO, TYPE_CHECKING, Any, NotRequired, TypedDict, cast
import boto3
import puremagic
from botocore.config import Config
from botocore.exceptions import ClientError
from sqlalchemy.orm import Session
... | 737 | 26,743 |
onyx | backend/onyx/file_store/document_batch_storage.py | .py | import json
from abc import ABC, abstractmethod
from enum import Enum
from io import StringIO
from typing import List, Optional, TypeAlias
from pydantic import BaseModel
from onyx.configs.constants import FileOrigin
from onyx.connectors.models import DocExtractionContext, DocIndexingContext, Document
from onyx.file_s... | 294 | 11,427 |
onyx | backend/onyx/file_store/s3_key_utils.py | .py | """
S3 key sanitization utilities for ensuring AWS S3 compatibility.
This module provides utilities for sanitizing file names to be compatible with
AWS S3 object key naming guidelines while ensuring uniqueness when significant
sanitization occurs.
Reference: https://docs.aws.amazon.com/AmazonS3/latest/userguide/objec... | 167 | 6,157 |
onyx | backend/onyx/chat/prompt_utils.py | .py | from collections.abc import Callable, Sequence
from uuid import UUID
from sqlalchemy.orm import Session
from onyx.db.memory import UserMemoryContext
from onyx.db.persona import get_default_behavior_persona
from onyx.db.user_file import calculate_user_files_token_count
from onyx.file_store.models import FileDescriptor... | 319 | 11,333 |
onyx | backend/onyx/chat/save_chat.py | .py | import json
import mimetypes
from sqlalchemy.orm import Session
from onyx.chat.chat_state import ChatStateContainer, SearchDocKey
from onyx.configs.constants import DocumentSource
from onyx.context.search.models import SearchDoc
from onyx.db.chat import (
add_search_docs_to_chat_message,
add_search_docs_to_to... | 363 | 15,956 |
onyx | backend/onyx/chat/incognito.py | .py | """Recording policy for incognito chat turns.
An incognito chat is an ordinary chat carrying a mode. ``IncognitoRecordMode``
is the only policy object: behavior is exposed as derived properties on it, so
the legal states are the only representable ones and no caller can assemble an
illegal combination out of loose boo... | 260 | 10,659 |
onyx | backend/onyx/chat/chat_processing_checker.py | .py | from uuid import UUID
from onyx.cache.interface import CacheBackend
from onyx.utils.logger import setup_logger
logger = setup_logger()
PREFIX = "chatprocessing"
FENCE_PREFIX = f"{PREFIX}_fence"
FENCE_TTL = 30 * 60 # 30 minutes
def _get_fence_key(chat_session_id: UUID) -> str:
"""Generate the cache key for a c... | 80 | 2,548 |
onyx | backend/onyx/chat/models.py | .py | from collections.abc import Iterator
from typing import Any, Callable
from uuid import UUID
from pydantic import BaseModel
from onyx.configs.constants import MessageType
from onyx.context.search.models import SearchDoc
from onyx.file_store.models import ChatFileType, InMemoryChatFile
from onyx.server.query_and_chat.m... | 252 | 8,431 |
onyx | backend/onyx/chat/tool_call_args_streaming.py | .py | from collections.abc import Generator, Mapping
from typing import Any, Type
from onyx.llm.model_response import ChatCompletionDeltaToolCall
from onyx.server.query_and_chat.placement import Placement
from onyx.server.query_and_chat.streaming_models import Packet, ToolCallArgumentDelta
from onyx.tools.built_in_tools imp... | 75 | 2,600 |
onyx | backend/onyx/chat/citation_processor.py | .py | """
Dynamic Citation Processor for LLM Responses
This module provides a citation processor that can:
- Accept citation number to SearchDoc mappings dynamically
- Process token streams from LLMs to extract citations
- Handle citations in three modes: REMOVE, KEEP_MARKERS, or HYPERLINK
- Emit CitationInfo objects for de... | 641 | 28,659 |
onyx | backend/onyx/chat/stop_signal_checker.py | .py | from uuid import UUID
from onyx.cache.interface import CacheBackend
PREFIX = "chatsessionstop"
FENCE_PREFIX = f"{PREFIX}_fence"
FENCE_TTL = 10 * 60 # 10 minutes
def _get_fence_key(chat_session_id: UUID) -> str:
"""Generate the cache key for a chat session stop signal fence.
Args:
chat_session_id: ... | 59 | 1,750 |
onyx | backend/onyx/chat/stream_buffer.py | .py | """Transient cross-pod buffer of a chat run's outbound stream.
The run's writer appends the exact NDJSON lines the SSE endpoint sends, stored in
the shared cache as zlib-compressed, sequence-numbered chunks so any api-server
pod can replay and tail an in-flight run. The cache is the only coordination
channel available... | 251 | 9,052 |
onyx | backend/onyx/chat/emitter.py | .py | import threading
from queue import Queue
from onyx.server.query_and_chat.placement import Placement
from onyx.server.query_and_chat.streaming_models import Packet
class Emitter:
"""Routes packets from LLM/tool execution to the ``_run_models`` drain loop.
Tags every packet with ``model_index`` and places it ... | 57 | 1,874 |
onyx | backend/onyx/chat/compression.py | .py | """
Chat history compression via summarization.
This module handles compressing long chat histories by summarizing older messages
while keeping recent messages verbatim.
Summaries are branch-aware: each summary's parent_message_id points to the last
message when compression triggered, making it part of the tree struc... | 510 | 18,483 |
onyx | backend/onyx/chat/chat_utils.py | .py | import json
import re
from collections.abc import Callable
from typing import cast
from uuid import UUID
from fastapi.datastructures import Headers
from pydantic import BaseModel
from sqlalchemy.orm import Session
from onyx.chat.incognito import (
incognito_allowed_for_user,
resolve_incognito_record_mode,
)
f... | 1,076 | 42,334 |
onyx | backend/onyx/chat/chat_state.py | .py | import threading
from collections.abc import Callable
from dataclasses import dataclass
from uuid import UUID
from pydantic import BaseModel
from onyx.cache.interface import CacheBackend
from onyx.chat.citation_processor import CitationMapping
from onyx.chat.models import (
ChatLoadedFile,
ChatMessageSimple,
... | 233 | 9,826 |
onyx | backend/onyx/chat/incognito_context.py | .py | """Ephemeral conversation context for incognito chat turns.
USAGE_ONLY must carry the live conversation outside Postgres, so it lives in
Redis: one value per session, a sliding TTL that starts over on every save,
and explicit teardown when the chat closes. Keys are tenant-prefixed by the
Redis client. Redis may evict ... | 237 | 8,996 |
onyx | backend/onyx/chat/process_message.py | .py | """
IMPORTANT: familiarize yourself with the design concepts prior to contributing to this file.
An overview can be found in the README.md file in this directory.
"""
import contextvars
import io
import os
import queue
import re
import threading
import time
import traceback
from collections.abc import Callable, Genera... | 2,265 | 93,255 |
onyx | backend/onyx/chat/llm_step.py | .py | import json
import re
import time
import uuid
from collections.abc import Callable, Generator, Mapping, Sequence
from html import unescape
from typing import Any, cast
from onyx.chat.chat_state import ChatStateContainer
from onyx.chat.citation_processor import DynamicCitationProcessor
from onyx.chat.emitter import Emi... | 1,618 | 64,645 |
onyx | backend/onyx/chat/llm_loop.py | .py | import json
import time
from collections.abc import Callable
from typing import Any, Literal
from onyx.chat.chat_state import ChatStateContainer
from onyx.chat.chat_utils import (
build_python_chat_files_from_search_docs,
create_tool_call_failure_messages,
)
from onyx.chat.citation_processor import (
Citat... | 1,411 | 61,120 |
onyx | backend/onyx/chat/citation_utils.py | .py | import re
from onyx.chat.citation_processor import CitationMapping, DynamicCitationProcessor
from onyx.context.search.models import SearchDocsResponse
from onyx.tools.built_in_tools import CITEABLE_TOOLS_NAMES
from onyx.tools.models import ToolResponse
def update_citation_processor_from_tool_response(
tool_respo... | 221 | 8,737 |
onyx | backend/onyx/indexing/port_reembed.py | .py | """Re-embed stored PRESENT chunks under FUTURE search settings without
re-fetching the source document (solution-design.md §5.1.1).
Two strategies, chosen by comparing PRESENT vs FUTURE settings:
- MODEL_ONLY (model / prefix / normalize / dimension changed, enrichment did
not): the embedding input is unchanged from... | 461 | 20,320 |
onyx | backend/onyx/indexing/document_push.py | .py | """Document push — deliver successfully indexed documents to an external endpoint.
This module owns the document push payload shape and the config-driven sink.
There are two delivery mechanisms for the same payload:
- the config-driven sink below, configured entirely through environment
variables (DOCUMENT_PUSH_END... | 151 | 5,778 |
onyx | backend/onyx/indexing/indexing_heartbeat.py | .py | from abc import ABC, abstractmethod
class IndexingHeartbeatInterface(ABC):
"""Defines a callback interface to be passed to
to run_indexing_entrypoint."""
@abstractmethod
def should_stop(self) -> bool:
"""Signal to stop the looping function in flight."""
@abstractmethod
def progress(s... | 18 | 523 |
onyx | backend/onyx/indexing/chunk_batch_store.py | .py | import pickle
import shutil
import tempfile
from collections.abc import Iterator
from pathlib import Path
from onyx.indexing.models import IndexChunk
class ChunkBatchStore:
"""Manages serialization of embedded chunks to a temporary directory.
Owns the temp directory lifetime and provides save/load/stream/sc... | 90 | 3,179 |
onyx | backend/onyx/indexing/models.py | .py | import contextlib
from collections.abc import Generator
from typing import TYPE_CHECKING, Optional, Protocol
from pydantic import BaseModel, Field
from onyx.access.models import DocumentAccess
from onyx.connectors.models import Document
from onyx.db.enums import EmbeddingPrecision, SwitchoverType
from onyx.utils.logg... | 294 | 10,570 |
onyx | backend/onyx/indexing/embedder.py | .py | import time
from abc import ABC, abstractmethod
from collections import defaultdict
import sentry_sdk
from onyx.connectors.models import (
ConnectorFailure,
ConnectorStopSignal,
DocumentFailure,
)
from onyx.db.models import SearchSettings
from onyx.document_index.chunk_content_enrichment import (
gene... | 319 | 11,776 |
onyx | backend/onyx/indexing/vector_db_insertion.py | .py | import time
from collections.abc import Callable, Iterable
from http import HTTPStatus
from itertools import chain, groupby
import httpx
import sentry_sdk
from onyx.connectors.models import ConnectorFailure, DocumentFailure
from onyx.document_index.interfaces_new import (
DocumentIndex,
DocumentInsertionRecor... | 126 | 4,750 |
onyx | backend/onyx/indexing/chunker.py | .py | from chonkie import SentenceChunker
from onyx.configs.app_configs import (
AVERAGE_SUMMARY_EMBEDDINGS,
BLURB_SIZE,
LARGE_CHUNK_RATIO,
MINI_CHUNK_SIZE,
SKIP_METADATA_IN_CHUNK,
USE_CHUNK_SUMMARY,
USE_DOCUMENT_SUMMARY,
)
from onyx.configs.constants import RETURN_SEPARATOR, SECTION_SEPARATOR, D... | 310 | 11,710 |
onyx | backend/onyx/indexing/indexing_pipeline.py | .py | import time
from collections import defaultdict
from collections.abc import Callable, Generator, Iterator
from contextlib import contextmanager
from typing import NamedTuple, Protocol
import sentry_sdk
from pydantic import BaseModel, ConfigDict
from sqlalchemy.orm import Session
from onyx.configs.app_configs import (... | 1,595 | 61,968 |
onyx | backend/onyx/indexing/persistent_indexing.py | .py | """Helpers for the PERSISTENT_INDEXING catch-all error path.
These are used by the docfetching / docprocessing task entrypoints to convert
unanticipated exceptions into ConnectorFailure records so the index attempt
can finish as COMPLETED_WITH_ERRORS instead of FAILED. Use only as a
last-resort catch-all; connectors s... | 111 | 3,982 |
onyx | backend/onyx/indexing/chunking/__init__.py | .py | from onyx.indexing.chunking.document_chunker import DocumentChunker
from onyx.indexing.chunking.section_chunker import extract_blurb
__all__ = [
"DocumentChunker",
"extract_blurb",
]
| 8 | 192 |
onyx | backend/onyx/indexing/chunking/image_section_chunker.py | .py | from onyx.connectors.models import Section
from onyx.indexing.chunking.section_chunker import (
AccumulatorState,
ChunkPayload,
SectionChunker,
SectionChunkerOutput,
)
from onyx.utils.text_processing import clean_text
class ImageChunker(SectionChunker):
def chunk_section(
self,
sec... | 38 | 1,092 |
onyx | backend/onyx/indexing/chunking/text_section_chunker.py | .py | from typing import cast
from chonkie import SentenceChunker
from onyx.configs.constants import SECTION_SEPARATOR
from onyx.connectors.models import Section
from onyx.indexing.chunking.section_chunker import (
AccumulatorState,
ChunkPayload,
SectionChunker,
SectionChunkerOutput,
)
from onyx.natural_lan... | 121 | 4,118 |
onyx | backend/onyx/indexing/chunking/section_chunker.py | .py | from abc import ABC, abstractmethod
from collections.abc import Sequence
from typing import cast
from chonkie import SentenceChunker
from pydantic import BaseModel, Field
from onyx.connectors.models import IndexingDocument, Section
from onyx.indexing.models import DocAwareChunk
def extract_blurb(text: str, blurb_sp... | 98 | 2,936 |
onyx | backend/onyx/indexing/chunking/document_chunker.py | .py | from chonkie import SentenceChunker
from onyx.connectors.models import (
IndexingDocument,
Section,
SectionType,
TabularSection,
)
from onyx.indexing.chunking.image_section_chunker import ImageChunker
from onyx.indexing.chunking.section_chunker import (
AccumulatorState,
ChunkPayload,
Secti... | 129 | 4,373 |
onyx | backend/onyx/indexing/chunking/tabular_section_chunker/sheet_descriptor.py | .py | from onyx.indexing.chunking.tabular_section_chunker.analysis import SheetAnalysis
from onyx.indexing.chunking.tabular_section_chunker.util import label, pack_lines
from onyx.natural_language_processing.utils import BaseTokenizer
MAX_NUMERIC_COLS = 12
MAX_CATEGORICAL_COLS = 6
MAX_CATEGORICAL_WITH_SAMPLES = 4
MAX_DISTIN... | 99 | 3,499 |
onyx | backend/onyx/indexing/chunking/tabular_section_chunker/total_descriptor.py | .py | from collections import Counter
from onyx.indexing.chunking.tabular_section_chunker.analysis import (
NumericAggregate,
SheetAnalysis,
)
from onyx.indexing.chunking.tabular_section_chunker.util import label, pack_lines
from onyx.natural_language_processing.utils import BaseTokenizer
TOTALS_HEADER = (
"Tot... | 70 | 2,108 |
onyx | backend/onyx/indexing/chunking/tabular_section_chunker/analysis.py | .py | from collections import Counter
from collections.abc import Iterable
from datetime import date
from dateutil.parser import parse as parse_dt
from pydantic import BaseModel, ConfigDict, Field
from onyx.utils.csv_utils import ParsedRow
CATEGORICAL_DISTINCT_THRESHOLD = 20
ID_NAME_TOKENS = {"id", "uuid", "uid", "guid", ... | 204 | 6,787 |
onyx | backend/onyx/indexing/chunking/tabular_section_chunker/tabular_section_chunker.py | .py | import io
from collections.abc import Iterable
from itertools import chain
from pydantic import BaseModel
from onyx.connectors.models import Section, TabularSection
from onyx.file_store.file_store import get_default_file_store
from onyx.indexing.chunking.section_chunker import (
AccumulatorState,
ChunkPayload... | 357 | 11,855 |
onyx | backend/onyx/indexing/chunking/tabular_section_chunker/util.py | .py | from onyx.natural_language_processing.utils import BaseTokenizer, count_tokens
def label(name: str) -> str:
"""Render a column name with a space-substituted friendly alias in
parens for underscored headers so retrieval matches either surface
form (e.g. ``MTTR_hours`` → ``MTTR_hours (MTTR hours)``)."""
... | 48 | 1,678 |
onyx | backend/onyx/indexing/chunking/tabular_section_chunker/__init__.py | .py | from onyx.indexing.chunking.tabular_section_chunker.tabular_section_chunker import (
TabularChunker,
)
__all__ = ["TabularChunker"]
| 6 | 137 |
onyx | backend/onyx/indexing/adapters/document_indexing_adapter.py | .py | import contextlib
import time
from collections.abc import Generator
from sqlalchemy.orm import Session
from onyx.access.access import get_access_for_documents
from onyx.access.models import DocumentAccess
from onyx.configs.constants import DEFAULT_BOOST
from onyx.connectors.models import Document, IndexAttemptMetadat... | 316 | 12,299 |
onyx | backend/onyx/indexing/adapters/user_file_indexing_adapter.py | .py | from __future__ import annotations
import contextlib
import datetime
import time
from collections import defaultdict
from collections.abc import Generator
from uuid import UUID
from sqlalchemy import select
from sqlalchemy.exc import OperationalError
from sqlalchemy.orm import Session, selectinload
from onyx.access.... | 347 | 14,354 |
onyx | backend/onyx/secondary_llm_flows/time_filter.py | .py | import re
from datetime import datetime, time, timedelta, timezone
from enum import StrEnum
from dateutil.relativedelta import relativedelta
from pydantic import BaseModel
from onyx.configs.constants import MessageType
from onyx.context.search.models import BaseFilters, TimeRange
from onyx.llm.interfaces import LLM
f... | 194 | 7,564 |
onyx | backend/onyx/secondary_llm_flows/chat_session_naming.py | .py | from collections.abc import Sequence
from onyx.chat.llm_step import translate_history_to_llm_format
from onyx.chat.models import ChatMessageSimple
from onyx.configs.constants import MessageType
from onyx.db.models import ChatMessage
from onyx.llm.interfaces import LLM
from onyx.llm.models import ReasoningEffort
from o... | 69 | 2,261 |
onyx | backend/onyx/secondary_llm_flows/query_expansion.py | .py | from onyx.configs.constants import MessageType
from onyx.llm.interfaces import LLM
from onyx.llm.models import (
AssistantMessage,
ChatCompletionMessage,
ReasoningEffort,
SystemMessage,
UserMessage,
)
from onyx.prompts.prompt_utils import get_current_llm_day_time
from onyx.prompts.search_prompts imp... | 231 | 8,253 |
onyx | backend/onyx/secondary_llm_flows/document_filter.py | .py | import json
import re
from onyx.configs.chat_configs import SECONDARY_LLM_FLOW_TIMEOUT_S
from onyx.context.search.models import (
ContextExpansionType,
InferenceChunk,
InferenceSection,
)
from onyx.llm.interfaces import LLM
from onyx.llm.models import ReasoningEffort, UserMessage
from onyx.prompts.search_p... | 439 | 17,430 |
onyx | backend/onyx/secondary_llm_flows/source_filter.py | .py | import json
from pydantic import BaseModel
from onyx.configs.constants import DocumentSource, MessageType
from onyx.llm.interfaces import LLM
from onyx.llm.models import ChatCompletionMessage, ReasoningEffort, UserMessage
from onyx.prompts.filter_extration import SOURCE_SCOPE_DECISION_PROMPT
from onyx.tools.models im... | 125 | 4,659 |
onyx | backend/onyx/secondary_llm_flows/memory_update.py | .py | from onyx.configs.constants import MessageType
from onyx.llm.interfaces import LLM
from onyx.llm.models import ReasoningEffort, UserMessage
from onyx.prompts.basic_memory import FULL_MEMORY_UPDATE_PROMPT
from onyx.tools.models import ChatMinimalTextMessage
from onyx.tracing.flows import LLMFlow
from onyx.tracing.llm_ut... | 194 | 6,706 |
onyx | backend/onyx/configs/agent_configs.py | .py | import os
AGENT_DEFAULT_RETRIEVAL_HITS = 15
AGENT_DEFAULT_RERANKING_HITS = 10
AGENT_DEFAULT_MAX_VERIFIVATION_HITS = 30
AGENT_DEFAULT_SUB_QUESTION_MAX_CONTEXT_HITS = 8
AGENT_DEFAULT_NUM_DOCS_FOR_INITIAL_DECOMPOSITION = 3
AGENT_DEFAULT_NUM_DOCS_FOR_REFINED_DECOMPOSITION = 5
AGENT_DEFAULT_MAX_STREAMED_DOCS_FOR_INITIAL_A... | 293 | 10,846 |
onyx | backend/onyx/configs/chat_configs.py | .py | import os
NUM_RETURNED_HITS = 50
# May be less depending on model
MAX_CHUNKS_FED_TO_CHAT = int(os.environ.get("MAX_CHUNKS_FED_TO_CHAT") or 25)
# Maximum number of LLM cycles (one tool-call round-trip per cycle) before the
# agent is forced to answer. Default 6 covers the common search → open_url
# pattern documented... | 112 | 5,541 |
onyx | backend/onyx/configs/llm_configs.py | .py | from onyx.configs.app_configs import DEFAULT_IMAGE_ANALYSIS_MAX_SIZE_MB
from onyx.server.settings.store import load_settings
def get_image_extraction_and_analysis_enabled() -> bool:
"""Return the workspace setting for image extraction/analysis.
The pydantic `Settings` model defaults this field to True, so pr... | 34 | 1,237 |
onyx | backend/onyx/configs/embedding_configs.py | .py | from pydantic import BaseModel
from onyx.db.enums import EmbeddingPrecision
class _BaseEmbeddingModel(BaseModel):
"""Private model for defining base embedding model configurations."""
name: str
dim: int
index_name: str
class SupportedEmbeddingModel(BaseModel):
name: str
dim: int
index_... | 167 | 4,842 |
onyx | backend/onyx/configs/tool_configs.py | .py | import json
import os
IMAGE_GENERATION_OUTPUT_FORMAT = os.environ.get(
"IMAGE_GENERATION_OUTPUT_FORMAT", "b64_json"
)
# if specified, will pass through request headers to the call to API calls made by custom tools
CUSTOM_TOOL_PASS_THROUGH_HEADERS: list[str] | None = None
_CUSTOM_TOOL_PASS_THROUGH_HEADERS_RAW = os... | 26 | 827 |
onyx | backend/onyx/configs/constants.py | .py | import logging
import os
import platform
import re
import socket
from enum import Enum, auto
ONYX_DEFAULT_APPLICATION_NAME = "Onyx"
ONYX_DISCORD_URL = "https://discord.gg/4NA5SbzrWb"
ONYX_UTM_SOURCE = "onyx_app"
SLACK_USER_TOKEN_PREFIX = "xoxp-"
ONYX_EMAILABLE_LOGO_MAX_DIM = 512
# The mask_string() function in encryp... | 804 | 32,944 |
onyx | backend/onyx/configs/app_configs.py | .py | import json
import math
import os
import urllib.parse
from datetime import datetime, timezone
from typing import cast
from onyx.auth.schemas import AuthBackend
from onyx.cache.interface import CacheBackendType
from onyx.configs.constants import QueryHistoryType
from onyx.document_index.opensearch.constants import Open... | 2,146 | 95,424 |
onyx | backend/onyx/configs/sentry.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, Any
from sentry_sdk.scrubber import DEFAULT_DENYLIST, EventScrubber
from sentry_sdk.types import Event
from onyx.utils.logger import setup_logger
if TYPE_CHECKING:
from sentry_sdk.integrations import Integration
logger = setup_logger()
_inst... | 112 | 3,443 |
onyx | backend/onyx/configs/model_configs.py | .py | import json
import os
from shared_configs.configs import DEFAULT_DOCUMENT_ENCODER_MODEL
#####
# Embedding/Reranking Model Configs
#####
# Important considerations when choosing models
# Max tokens count needs to be high considering use case (at least 512)
# Models used must be MIT or Apache license
# Inference/Indexi... | 146 | 5,816 |
onyx | backend/onyx/configs/kg_configs.py | .py | import os
KG_RESEARCH_NUM_RETRIEVED_DOCS: int = int(
os.environ.get("KG_RESEARCH_NUM_RETRIEVED_DOCS", "25")
)
KG_SIMPLE_ANSWER_MAX_DISPLAYED_SOURCES: int = int(
os.environ.get("KG_SIMPLE_ANSWER_MAX_DISPLAYED_SOURCES", "10")
)
KG_ENTITY_EXTRACTION_TIMEOUT: int = int(
os.environ.get("KG_ENTITY_EXTRACTION... | 147 | 4,171 |
onyx | backend/onyx/configs/onyxbot_configs.py | .py | import os
#####
# Onyx Slack Bot Configs
#####
ONYX_BOT_NUM_RETRIES = int(os.environ.get("ONYX_BOT_NUM_RETRIES", "5"))
# Number of docs to display in "Reference Documents"
ONYX_BOT_NUM_DOCS_TO_DISPLAY = int(os.environ.get("ONYX_BOT_NUM_DOCS_TO_DISPLAY", "5"))
# If the LLM fails to answer, Onyx can still show the "Refe... | 60 | 2,690 |
onyx | backend/onyx/document_index/interfaces_new.py | .py | import abc
from collections.abc import Iterable
from datetime import datetime
from typing import Self
from pydantic import BaseModel, model_validator
from onyx.access.models import DocumentAccess
from onyx.configs.constants import PUBLIC_DOC_PAT
from onyx.context.search.enums import QueryType
from onyx.context.search... | 501 | 17,378 |
onyx | backend/onyx/document_index/disabled.py | .py | """A DocumentIndex implementation that raises on every operation.
Used as a safety net when DISABLE_VECTOR_DB is True. Any code path that
accidentally reaches the vector DB layer will fail loudly instead of timing
out against a nonexistent Vespa/OpenSearch instance.
"""
from collections.abc import Iterable
from onyx... | 105 | 3,707 |
onyx | backend/onyx/document_index/chunk_content_enrichment.py | .py | from onyx.configs.app_configs import BLURB_SIZE
from onyx.configs.constants import RETURN_SEPARATOR
from onyx.context.search.models import InferenceChunk, InferenceChunkUncleaned
from onyx.indexing.models import DocAwareChunk
def generate_enriched_content_for_chunk_text(chunk: DocAwareChunk) -> str:
return f"{chu... | 105 | 4,776 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.