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/scripts/build_docx_preview.py | .py | """Preview + compare harness for the build-session Markdown -> DOCX converter.
This is a developer tool for tuning ``onyx.server.features.build.session.md_to_docx``
toward the visual output that pandoc/pypandoc produces. It can:
* ``generate`` a ``.docx`` from a Markdown file using the in-tree mistune
converter, an... | 260 | 9,728 |
onyx | backend/scripts/search_loadtest.py | .py | """
Load test for the Onyx search flow (/api/search/send-search-message).
Usage:
source .venv/bin/activate
python backend/scripts/search_loadtest.py --help
"""
from __future__ import annotations
import argparse
import os
import random
import statistics
import threading
import time
from collections import Cou... | 431 | 14,517 |
onyx | backend/scripts/get_wikidocs.py | .py | #!/usr/bin/env python3
"""
Script to pull Wikipedia documents from Hugging Face and organize them into zip files.
Usage:
python get_wikidocs.py --total 1000 --per-zip 100 --output ./wikidata_zips
"""
import argparse
import os
import re
import zipfile
from pathlib import Path
from datasets import load_dataset # ... | 225 | 6,678 |
onyx | backend/scripts/hard_delete_chats.py | .py | import os
import sys
# Ensure PYTHONPATH is set up for direct script execution
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(parent_dir)
sys.path.append(parent_dir)
from onyx.db.chat import delete_chat_session # noqa: E402
from onyx.db.engine.sql_engine import ( # noqa: E402
Sql... | 55 | 1,784 |
onyx | backend/scripts/onyx_openapi_schema.py | .py | # export openapi schema without having to start the actual web server
# helpful tips: https://github.com/fastapi/fastapi/issues/1173
import argparse
import json
import os
import subprocess
import sys
from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi
from onyx.main import app as app_fn
OPENA... | 144 | 4,401 |
onyx | backend/scripts/save_load_state.py | .py | # This file is purely for development use, not included in any builds
# Remember to first to send over the schema information (run API Server)
import argparse
import json
import os
import subprocess
import requests
from alembic import command
from alembic.config import Config
from onyx.configs.app_configs import (
... | 142 | 4,669 |
onyx | backend/scripts/reencrypt_secrets.py | .py | """Re-encrypt secrets under the current ENCRYPTION_KEY_SECRET.
Decrypts all encrypted columns using the old key (or raw decode if the old key
is empty), then re-encrypts them with the current ENCRYPTION_KEY_SECRET.
Usage (docker):
docker exec -it onyx-api_server-1 \
python -m scripts.reencrypt_secrets --o... | 110 | 3,495 |
onyx | backend/scripts/chat_history_seeding.py | .py | import argparse
import logging
from logging import getLogger
from onyx.db.seeding.chat_history_seeding import seed_chat_history
# Configure the logger
logging.basicConfig(
level=logging.INFO, # Set the log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
format="%(asctime)s - %(name)s - %(levelname)s - %(messag... | 46 | 1,226 |
onyx | backend/scripts/reset_indexes.py | .py | # This file is purely for development use, not included in any builds
import os
import sys
from time import sleep
import requests
from requests.exceptions import RequestException
# makes it so `PYTHONPATH=.` is not required when running this script
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__... | 77 | 2,180 |
onyx | backend/scripts/rotate_llm_provider_keys.py | .py | """Rotate OpenAI / Anthropic API keys across all tenants.
For each tenant, iterates every LLM provider (and optionally embedding and
voice providers), decrypts the stored key, and replaces it with the new key
when it matches the old one.
Usage (docker):
docker exec -it onyx-api_server-1 \
python -m script... | 274 | 8,968 |
onyx | backend/scripts/celery_purge_queue.py | .py | # Tool to run operations on Celery/Redis in production
# this is a work in progress and isn't completely put together yet
# but can serve as a stub for future operations
import argparse
import logging
from logging import getLogger
from redis import Redis
from onyx.background.celery.celery_redis import celery_get_queu... | 88 | 2,935 |
onyx | backend/scripts/update_recommended_models.py | .py | """Regenerate recommended-models.json from the OpenRouter model catalog.
Applies the curation rules in update_recommended_models_rules.json (trusted
vendors + model-family regexes) to the official OpenRouter catalog
(https://openrouter.ai/api/v1/models) and rewrites
backend/onyx/llm/well_known_providers/recommended-mo... | 546 | 18,594 |
onyx | backend/scripts/sources_selection_analysis.py | .py | import argparse
import json
import os
import sys
import time
from datetime import datetime
from os import listdir
from os.path import isfile, join
from typing import Optional
import requests
from onyx.configs.constants import FASTAPI_USERS_AUTH_COOKIE_NAME
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath... | 748 | 26,500 |
onyx | backend/scripts/reset_postgres.py | .py | import os
import sys
import psycopg2
from sqlalchemy.orm import Session
from onyx.db.engine.sql_engine import get_sqlalchemy_engine
# makes it so `PYTHONPATH=.` is not required when running this script
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(parent_dir)
from onyx.con... | 73 | 1,998 |
onyx | backend/scripts/add_connector_creation_script.py | .py | from typing import Any, Dict
import requests
API_SERVER_URL = "http://localhost:3000" # Adjust this to your Onyx server URL
HEADERS = {"Content-Type": "application/json"}
API_KEY = "onyx-api-key" # API key here, if auth is enabled
def create_connector(
name: str,
source: str,
input_type: str,
conn... | 148 | 4,122 |
onyx | backend/scripts/run_enterpriserag_bench_questions.py | .py | from __future__ import annotations
import argparse
import asyncio
import json
import logging
import sys
import time
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any, TypedDict, TypeGuard
import aiohttp
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(lev... | 734 | 24,027 |
onyx | backend/scripts/coding_agent_test.py | .py | """Manual test harness for the coding-agent loop.
Usage (from repo root, with venv active and Onyx services running):
source .venv/bin/activate
python -m backend.scripts.coding_agent_test \\
--repo onyx-dot-app/onyx \\
--query "What does the docprocessing celery worker do?"
Optional flags:
... | 150 | 4,964 |
onyx | backend/scripts/dev_run_background_jobs.py | .py | import os
import subprocess
import threading
BACKEND_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def monitor_process(process_name: str, process: subprocess.Popen) -> None:
assert process.stdout is not None
while True:
output = process.stdout.readline()
if output:
... | 189 | 5,150 |
onyx | backend/scripts/transform_openapi_for_docs.py | .py | """
Transform OpenAPI schema for public documentation.
Filters endpoints tagged with "public", converts auth to Bearer token,
and removes internal parameters (tenant_id, db_session).
Usage:
python scripts/transform_openapi_for_docs.py -i generated/openapi.json -o openapi_docs.json
"""
import argparse
import copy... | 190 | 6,434 |
onyx | backend/scripts/test-openapi-key.py | .py | VALID_MODEL_LIST = [
"gpt-4o-mini",
"gpt-4o",
"gpt-4-1106-preview",
"gpt-4-vision-preview",
"gpt-4",
"gpt-4-0314",
"gpt-4-0613",
"gpt-4-32k",
"gpt-4-32k-0314",
"gpt-4-32k-0613",
"gpt-3.5-turbo-0125",
"gpt-3.5-turbo-1106",
"gpt-3.5-turbo",
"gpt-3.5-turbo-16k",
... | 58 | 1,667 |
onyx | backend/scripts/dev_celery_reload.py | .py | """Run a celery worker with watchfiles hot-reload, preserving VSCode breakpoints.
LOAD-BEARING: referenced by every "Celery <name>" configuration in
.vscode/launch.json (both local and k8s variants). Deleting or renaming this
file will break the vscode debugger for celery. See also CONTRIBUTING.md
("VSCode Debugger") ... | 57 | 2,022 |
onyx | backend/scripts/orphan_doc_cleanup_script.py | .py | import concurrent.futures
import os
import sys
from sqlalchemy import text
from sqlalchemy.orm import Session
from onyx.document_index.document_index_utils import get_multipass_config
# makes it so `PYTHONPATH=.` is not required when running this script
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__... | 156 | 6,378 |
onyx | backend/scripts/env_inventory.py | .py | """Environment-variable inventory for the Onyx backend.
AST-walks the backend (and optionally the frontend) to build a canonical
manifest of every environment variable the code actually reads, then
cross-references the deployment files (docker-compose env templates + Helm
values/configmap) to surface drift:
* read-... | 955 | 35,934 |
onyx | backend/scripts/seed_dev_license.py | .py | """Seed a dev license blob into the DB for CI test environments.
Usage (docker):
docker exec -e ONYX_DEV_LICENSE onyx-api_server-1 \
python -m scripts.seed_dev_license
Reads ONYX_DEV_LICENSE from the environment. Empty values no-op so the
script can be invoked unconditionally (e.g. local dev runs without ... | 48 | 1,356 |
onyx | backend/scripts/force_delete_connector_by_id.py | .py | import argparse
import os
import sys
from sqlalchemy import delete
from sqlalchemy.orm import Session
from onyx.db.document import delete_documents_complete__no_commit
from onyx.db.enums import ConnectorCredentialPairStatus
from onyx.db.search_settings import get_active_search_settings
from onyx.db.tag import delete_... | 254 | 7,994 |
onyx | backend/scripts/api_inference_sample.py | .py | # This file is used to demonstrate how to use the backend APIs directly
# In this case, the equivalent of asking a question in Onyx Chat in a new chat session
import argparse
import json
import os
import requests
def create_new_chat_session(onyx_url: str, api_key: str | None) -> int:
headers = {"Authorization": ... | 88 | 2,951 |
onyx | backend/scripts/chat_feedback_dump.py | .py | # This file is used to demonstrate how to use the backend APIs directly
# to query out feedback for all messages
import argparse
import logging
from logging import getLogger
from typing import Any
from uuid import UUID
import requests
from ee.onyx.server.query_history.api import ChatSessionSnapshot
from onyx.server.m... | 237 | 6,715 |
onyx | backend/scripts/resume_paused_connectors.py | .py | import argparse
import requests
API_SERVER_URL = "http://localhost:3000"
API_KEY = "onyx-api-key" # API key here, if auth is enabled
def resume_paused_connectors(
api_server_url: str,
api_key: str | None,
specific_connector_sources: list[str] | None = None,
) -> None:
headers = {"Content-Type": "ap... | 81 | 2,779 |
onyx | backend/scripts/query_time_check/seed_dummy_docs.py | .py | """
launch:
- api server
- postgres
- vespa
- model server (this is only needed so the api server can startup, no embedding is done)
Run this script to seed the database with dummy documents.
Then run test_query_times.py to test query times.
"""
import random
from datetime import datetime
from onyx.access.models imp... | 188 | 6,427 |
onyx | backend/scripts/lib/logger.py | .py | from __future__ import annotations
import logging
import os
import sys
# Detect CI environment
IS_CI = os.getenv("CI", "").lower() == "true"
IS_DEBUG = os.getenv("DEBUG", "").lower() == "true"
# ANSI color codes for local terminal
GRAY = "\033[90m"
RED = "\033[91m"
YELLOW = "\033[93m"
CYAN = "\033[96m"
RESET = "\033... | 68 | 2,077 |
onyx | backend/scripts/debugging/onyx_redis.py | .py | import argparse
import json
import logging
import sys
import time
from enum import Enum
from logging import getLogger
from typing import cast
from uuid import UUID
from redis import Redis
from ee.onyx.db.user_tenant_mapping import get_tenant_id_for_email
from onyx.auth.invited_users import get_invited_users, write_in... | 484 | 14,719 |
onyx | backend/scripts/debugging/onyx_list_tenants.py | .py | #!/usr/bin/env python3
"""
Tenant List Script
Simple script to list the tenant IDs in the database.
Used by the parallel migration script to determine how to split work.
Usage:
```
# List one tenant per line (default)
PYTHONPATH=. python scripts/debugging/onyx_list_tenants.py
# Output as CSV (all on one line)
PYTHO... | 89 | 2,562 |
onyx | backend/scripts/debugging/onyx_vespa_schemas.py | .py | """Tool to generate all supported schema variations for Onyx Cloud's Vespa database.
Usage:
```
PYTHONPATH=. python scripts/debugging/onyx_vespa_schemas.py
```
Then, paste them into the existing vespa schema downloaded from the Vespa console,
and then re-zip.
"""
import argparse
import os
from pathlib import Path
... | 155 | 4,535 |
onyx | backend/scripts/debugging/debug_usage_limits.py | .py | #!/usr/bin/env python3
"""
Debug script to fetch usage limit overrides from the control plane.
Run this from within a data plane pod to diagnose usage limits issues.
Usage:
python debug_usage_limits.py
Environment variables required:
- DATA_PLANE_SECRET: Secret for generating JWT tokens
- CONTROL_PLANE_AP... | 108 | 3,170 |
onyx | backend/scripts/debugging/onyx_db.py | .py | """Onyx Database tool"""
import os
# hack to work around excessive use of globals in other functions
os.environ["MULTI_TENANT"] = "True"
if True: # noqa: E402
import argparse
import csv
import heapq
from pydantic import BaseModel
from sqlalchemy import func
from onyx.db.engine.sql_engine i... | 186 | 6,146 |
onyx | backend/scripts/debugging/litellm/directly_hit_azure_api.py | .py | #!/usr/bin/env python3
"""
Directly hit Azure OpenAI endpoints for debugging.
This script bypasses LiteLLM and directly calls Azure OpenAI APIs.
Uses URL and API key constants plus a payload.json in the same directory.
Usage:
python directly_hit_azure_api.py
"""
from __future__ import annotations
import json
fr... | 90 | 2,387 |
onyx | backend/scripts/debugging/litellm/call_litellm.py | .py | #!/usr/bin/env python3
"""
Test LiteLLM integration and output raw stream events.
This script uses Onyx's LiteLLM instance (with monkey patches) to make a completion
request and outputs the raw stream events as JSON, one per line.
Usage:
# Set environment variables if needed:
export LITELLM_DEBUG=1 # Optiona... | 228 | 7,992 |
onyx | backend/scripts/debugging/opensearch/embed_and_save.py | .py | #!/usr/bin/env python3
"""Embeds a query and saves the embedding to a file.
Requires Onyx to be running as it reads search settings from the database.
Usage:
source .venv/bin/activate
python backend/scripts/debugging/opensearch/embed_and_save.py --help
"""
import argparse
import time
from scripts.debugging.... | 65 | 1,885 |
onyx | backend/scripts/debugging/opensearch/embedding_io.py | .py | from shared_configs.model_server_models import Embedding
def load_query_embedding_from_file(file_path: str) -> Embedding:
"""Returns an embedding vector read from a file.
The file should be formatted as follows:
- The first line should contain an integer representing the embedding
dimension.
- ... | 44 | 1,595 |
onyx | backend/scripts/debugging/opensearch/query_hierarchy_debug.py | .py | #!/usr/bin/env python3
"""
Debug utility for querying and inspecting hierarchy data in OpenSearch.
This script connects to OpenSearch and allows you to:
- Query documents by ID and view their hierarchy ancestor node IDs
- List documents that have hierarchy data
Usage:
python query_hierarchy_debug.py --document-id... | 145 | 4,520 |
onyx | backend/scripts/debugging/opensearch/benchmark_retrieval.py | .py | #!/usr/bin/env python3
"""Benchmarks OpenSearchDocumentIndex latency.
Requires Onyx to be running as it reads search settings from the database.
Usage:
source .venv/bin/activate
python backend/scripts/debugging/opensearch/benchmark_retrieval.py --help
"""
import argparse
import statistics
import time
from s... | 173 | 5,950 |
onyx | backend/scripts/debugging/opensearch/opensearch_debug.py | .py | #!/usr/bin/env python3
"""A utility to interact with OpenSearch.
Example Usage:
Assuming running from ~/onyx/
source .venv/bin/activate
python backend/scripts/debugging/opensearch/opensearch_debug.py --help
python backend/scripts/debugging/opensearch/opensearch_debug.py list
python ... | 412 | 14,925 |
onyx | backend/scripts/tenant_cleanup/cleanup_utils.py | .py | import csv
import os
import random
import subprocess
import sys
from dataclasses import dataclass
from pathlib import Path
class TenantNotFoundInControlPlaneError(Exception):
"""Exception raised when tenant/table is not found in control plane."""
@dataclass
class ControlPlaneConfig:
"""Configuration for con... | 202 | 5,967 |
onyx | backend/scripts/tenant_cleanup/activity_utils.py | .py | from collections.abc import Mapping, Sequence
from datetime import datetime
CRAFT_ACTIVITY_FIELD = "last_craft_activity_time"
ACTIVITY_CSV_FIELDNAMES = (
"last_query_time",
CRAFT_ACTIVITY_FIELD,
"last_activity_time",
"days_since_last_activity",
)
def _parse_activity_time(value: object) -> datetime | ... | 53 | 1,595 |
onyx | backend/scripts/tenant_cleanup/mark_connectors_for_deletion.py | .py | #!/usr/bin/env python3
"""
Mark connectors for deletion script that:
1. Finds all connectors for the specified tenant(s)
2. Cancels any scheduled indexing attempts
3. Marks each connector credential pair as DELETING
4. Triggers the cleanup task
Usage:
python backend/scripts/tenant_cleanup/mark_connectors_for_delet... | 425 | 16,089 |
onyx | backend/scripts/tenant_cleanup/no_bastion_cleanup_tenants.py | .py | #!/usr/bin/env python3
"""
Tenant cleanup script that works WITHOUT bastion access.
All queries run directly from pods.
Supports two-cluster architecture (data plane and control plane in separate clusters).
Usage:
PYTHONPATH=. python scripts/tenant_cleanup/no_bastion_cleanup_tenants.py <tenant_id> \
--data... | 953 | 34,387 |
onyx | backend/scripts/tenant_cleanup/no_bastion_cleanup_utils.py | .py | """
Cleanup utilities that work WITHOUT bastion access.
Control plane and data plane are in SEPARATE clusters.
"""
import csv
import json
import re
import subprocess
import sys
from pathlib import Path
class TenantNotFoundInControlPlaneError(Exception):
"""Exception raised when tenant/table is not found in contr... | 327 | 10,438 |
onyx | backend/scripts/tenant_cleanup/cleanup_tenants.py | .py | #!/usr/bin/env python3
"""
Tenant cleanup script that:
1. Deletes all documents from Vespa
2. Drops the data plane PostgreSQL schema
3. Clean up control plane (tenants, subscription table)
Usage:
python backend/scripts/cleanup_tenant.py <tenant_id> [--force]
python backend/scripts/cleanup_tenant.py --csv <csv_... | 764 | 26,839 |
onyx | backend/scripts/tenant_cleanup/no_bastion_analyze_tenants.py | .py | #!/usr/bin/env python3
"""
Tenant analysis script that works WITHOUT bastion access.
Control plane and data plane are in SEPARATE clusters.
Usage:
PYTHONPATH=. python scripts/tenant_cleanup/no_bastion_analyze_tenants.py \
[--skip-cache] \
[--data-plane-context <context>] \
[--control-plane-... | 506 | 18,096 |
onyx | backend/scripts/tenant_cleanup/check_no_bastion_setup.py | .py | #!/usr/bin/env python3
"""
Verification script to check if your environment is ready for no-bastion tenant cleanup.
Usage:
python scripts/tenant_cleanup/check_no_bastion_setup.py
"""
import subprocess
import sys
def print_header(text: str) -> None:
"""Print a formatted header."""
print(f"\n{'=' * 80}")
... | 285 | 8,884 |
onyx | backend/scripts/tenant_cleanup/analyze_current_tenants.py | .py | #!/usr/bin/env python3
"""
Full tenant analysis script that:
1. Finds a heavy worker pod
2. Runs the tenant data collection script on the pod
3. Analyzes the collected data
"""
import argparse
import csv
import json
import os
import subprocess
import sys
from datetime import datetime, timedelta, timezone
from pathlib ... | 458 | 16,171 |
onyx | backend/scripts/tenant_cleanup/no_bastion_mark_connectors.py | .py | #!/usr/bin/env python3
"""
Mark connectors for deletion script that works WITHOUT bastion access.
All queries run directly from pods.
Supports two-cluster architecture (data plane and control plane in separate clusters).
Usage:
PYTHONPATH=. python scripts/tenant_cleanup/no_bastion_mark_connectors.py <tenant_id> \
... | 578 | 20,975 |
onyx | backend/scripts/tenant_cleanup/on_pod_scripts/get_tenant_index_name.py | .py | #!/usr/bin/env python3
"""
Script to get the default index name for a tenant.
Designed to be run on a heavy worker pod.
Usage:
python get_tenant_index_name.py <tenant_id>
"""
import json
import sys
from onyx.db.engine.sql_engine import SqlEngine, get_session_with_tenant
from onyx.db.search_settings import get_cu... | 50 | 1,530 |
onyx | backend/scripts/tenant_cleanup/on_pod_scripts/execute_connector_deletion.py | .py | #!/usr/bin/env python3
"""
Script to mark connector credential pairs for deletion.
Runs on a Kubernetes pod with access to the data plane database.
Usage:
# Mark a specific connector for deletion
python mark_connector_for_deletion.py <tenant_id> <cc_pair_id>
# Mark all connectors for deletion
python m... | 349 | 11,428 |
onyx | backend/scripts/tenant_cleanup/on_pod_scripts/understand_tenants.py | .py | import json
import sys
from typing import Any
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.orm import Session
from onyx.db.engine.sql_engine import SqlEngine, get_session_with_shared_schema
def get_tenant_activity_summary(session: Session) -> list[dict[str, Any]]:
"""R... | 111 | 3,544 |
onyx | backend/scripts/tenant_cleanup/on_pod_scripts/cleanup_tenant_schema.py | .py | #!/usr/bin/env python3
"""
Script to drop a tenant's PostgreSQL schema.
Designed to be run on a heavy worker pod.
Usage:
python cleanup_tenant_schema.py <tenant_id>
"""
import json
import sys
from sqlalchemy import text
from onyx.db.engine.shard_registry import get_engine_for_shard, get_shard_specs
from onyx.db... | 114 | 4,433 |
onyx | backend/scripts/tenant_cleanup/on_pod_scripts/get_tenant_connectors.py | .py | #!/usr/bin/env python3
"""
Script to fetch connector credential pairs for a tenant.
Runs on a Kubernetes pod with access to the data plane database.
Usage:
python get_tenant_connectors.py <tenant_id>
Output:
JSON to stdout with structure:
{
"status": "success" | "error",
"connectors": [
... | 107 | 2,668 |
onyx | backend/scripts/tenant_cleanup/on_pod_scripts/get_tenant_users.py | .py | #!/usr/bin/env python3
"""
Script to fetch user emails from a tenant's data plane schema.
Must be run on a pod with access to the data plane PostgreSQL database.
Usage:
python get_tenant_users.py <tenant_id>
Output:
JSON object with status and users list
"""
import json
import sys
from sqlalchemy import sel... | 80 | 2,129 |
onyx | backend/scripts/tenant_cleanup/on_pod_scripts/check_documents_deleted.py | .py | #!/usr/bin/env python3
"""
Script to check for remaining ConnectorCredentialPairs and Documents in a tenant's schema.
Must be run on a pod with access to the data plane PostgreSQL database.
Usage:
python check_documents_deleted.py <tenant_id>
Output:
JSON object with status, message, and counts of remaining r... | 107 | 3,302 |
onyx | backend/alembic_tenants/env.py | .py | import asyncio
from logging.config import fileConfig
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import create_async_engine
from alembic import context
from onyx.db.engine.pg_ssl import create_pg_ssl_context
from onyx.db.engine.sql_engine import build_connection_st... | 115 | 3,519 |
onyx | backend/alembic_tenants/versions/3b45e0018bf1_add_new_available_tenant_table.py | .py | """add new available tenant table
Revision ID: 3b45e0018bf1
Revises: ac842f85f932
Create Date: 2025-03-06 09:55:18.229910
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "3b45e0018bf1"
down_revision = "ac842f85f932"
branch_labels = None
depends_on = None
def... | 34 | 778 |
onyx | backend/alembic_tenants/versions/3b9f09038764_add_read_only_kg_user.py | .py | """add_db_readonly_user
Revision ID: 3b9f09038764
Revises: 3b45e0018bf1
Create Date: 2025-05-11 11:05:11.436977
"""
from sqlalchemy import text
from alembic import op
from onyx.configs.app_configs import DB_READONLY_PASSWORD
from onyx.configs.app_configs import DB_READONLY_USER
# revision identifiers, used by Alem... | 68 | 2,517 |
onyx | backend/alembic_tenants/versions/ac842f85f932_new_column_user_tenant_mapping.py | .py | """new column user tenant mapping
Revision ID: ac842f85f932
Revises: 34e3630c7f32
Create Date: 2025-03-03 13:30:14.802874
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "ac842f85f932"
down_revision = "34e3630c7f32"
branch_labels = None
depends_on = None
def... | 52 | 1,300 |
onyx | backend/alembic_tenants/versions/a4f6ee863c47_mapping_for_anonymous_user_path.py | .py | """mapping for anonymous user path
Revision ID: a4f6ee863c47
Revises: 14a83a331951
Create Date: 2025-01-04 14:16:58.697451
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "a4f6ee863c47"
down_revision = "14a83a331951"
branch_labels = None
depends_on = None
de... | 32 | 729 |
onyx | backend/alembic_tenants/versions/d4e7a92c1b38_add_tenant_invite_counter.py | .py | """add_tenant_invite_counter_table
Revision ID: d4e7a92c1b38
Revises: 3b9f09038764
Create Date: 2026-04-20 18:00:00.000000
Adds `public.tenant_invite_counter`, the lifetime invite-quota counter used by
the trial-tenant cap in `bulk_invite_users`. One row per tenant; holds a
monotonically-incremented total of invites ... | 80 | 2,805 |
onyx | backend/alembic_tenants/versions/14a83a331951_create_usertenantmapping_table.py | .py | import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "14a83a331951"
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"user_tenant_mapping",
sa.Column("email", sa.String(), nullable=False),
sa... | 25 | 616 |
onyx | backend/alembic_tenants/versions/8f3d2c7b91ae_add_user_tenant_mapping_oauth_account.py | .py | """add user tenant mapping oauth account table
Revision ID: 8f3d2c7b91ae
Revises: b1c4e9d72f38
Create Date: 2026-07-29 20:14:03.117204
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "8f3d2c7b91ae"
down_revision = "b1c4e9d72f38"
branch_labels = None
depends_on... | 54 | 1,500 |
onyx | backend/alembic_tenants/versions/b1c4e9d72f38_add_tenant_shard_map.py | .py | """add tenant shard map
Adds the tenant -> physical database ("shard") mapping used to route sessions when
tenants are spread across more than one Postgres database.
Deliberately not backfilled: a tenant with no row lives on the default shard, so this
table stays empty until tenants are actually migrated, and existin... | 64 | 1,891 |
onyx | backend/alembic_tenants/versions/34e3630c7f32_lowercase_multi_tenant_user_auth.py | .py | """lowercase multi-tenant user auth
Revision ID: 34e3630c7f32
Revises: a4f6ee863c47
Create Date: 2025-02-26 15:03:01.211894
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "34e3630c7f32"
down_revision = "a4f6ee863c47"
branch_labels = None
depends_on = None
def upgrade() -> None:
... | 41 | 905 |
onyx | backend/shared_configs/model_server_models.py | .py | from pydantic import BaseModel
from shared_configs.enums import EmbeddingProvider, EmbedTextType, RerankerProvider
Embedding = list[float]
class EmbedRequest(BaseModel):
texts: list[str]
# Can be none for cloud embedding model requests, error handling logic exists for other cases
model_name: str | None ... | 63 | 1,758 |
onyx | backend/shared_configs/utils.py | .py | from typing import TypeVar
T = TypeVar("T")
def batch_list(
lst: list[T],
batch_size: int,
) -> list[list[T]]:
return [lst[i : i + batch_size] for i in range(0, len(lst), batch_size)]
| 11 | 199 |
onyx | backend/shared_configs/configs.py | .py | import os
from typing import Any, List
from urllib.parse import urlparse
# Used for logging
SLACK_CHANNEL_ID = "channel_id"
# Skip model warmup at startup
# Default to True (skip warmup) if not set, otherwise respect the value
SKIP_WARM_UP = os.environ.get("SKIP_WARM_UP", "true").lower() == "true"
# Check if model s... | 279 | 11,160 |
onyx | backend/shared_configs/enums.py | .py | from enum import Enum
class EmbeddingProvider(str, Enum):
OPENAI = "openai"
COHERE = "cohere"
VOYAGE = "voyage"
GOOGLE = "google"
LITELLM = "litellm"
AZURE = "azure"
class RerankerProvider(str, Enum):
COHERE = "cohere"
LITELLM = "litellm"
BEDROCK = "bedrock"
class EmbedTextType... | 54 | 1,078 |
onyx | backend/shared_configs/contextvars.py | .py | import contextvars
from typing import NamedTuple
from shared_configs.configs import MULTI_TENANT, POSTGRES_DEFAULT_SCHEMA
from shared_configs.enums import UsageCredentialType
# Context variable for the current tenant id
CURRENT_TENANT_ID_CONTEXTVAR: contextvars.ContextVar[str | None] = (
contextvars.ContextVar(
... | 101 | 3,766 |
onyx | loadtest/locustfile.py | .py | """Locust entrypoint for Onyx chat load tests.
With no user classes named, the default weighted mix runs (BasicChat 70 /
ChatWithSearch 20 / MultiTool 8 / DeepResearch 2); name a class to run a
targeted reproducer (LongConversationUser, DisconnectUser). For the worker /
threadpool concurrency sweep, name ThreadHogUser... | 46 | 1,363 |
onyx | loadtest/prometheus_exporter.py | .py | """Locust integration for the Prometheus collector.
Imported for its side effect (the init listener) by locustfile.py. On the
master/standalone runner it registers the collector and serves /metrics on a
dedicated port (default 9646; set LOCUST_PROMETHEUS_PORT to override) so chat
milestone latency / failure rate can b... | 38 | 1,300 |
onyx | loadtest/shapes.py | .py | """Staged ramp for collapse-point hunting.
StepRampShape holds the user count at successive plateaus so the knee where
the system stops keeping up is visible in the timeline. Opt-in only: the
locustfile binds it when ONYX_SHAPE=stepramp, since Locust auto-activates any
shape it finds and overrides -u/-r. Tune via ONYX... | 50 | 1,799 |
onyx | loadtest/prometheus_collector.py | .py | """Prometheus collector for Locust stats — pure prometheus_client, no locust
import (so it stays gevent-free and unit-testable alongside the fastapi tests).
The locust integration (init listener + http server) lives in
prometheus_exporter.py, which is imported by locustfile.py for its side effect.
"""
from __future__... | 69 | 2,452 |
onyx | loadtest/onyx_client/chat_user.py | .py | """Locust user that drives the Onyx chat streaming endpoint.
Each turn POSTs /api/chat/send-chat-message with stream=True and consumes the
NDJSON response line by line, firing a named pseudo-request the moment each
milestone packet arrives:
<prefix>:first_packet — time to first stream line
<prefix>:fi... | 279 | 11,206 |
onyx | loadtest/onyx_client/env.py | .py | """Small env-var parsing helpers shared across users and scenarios."""
from __future__ import annotations
import os
def env_float(name: str, default: float) -> float:
raw = os.environ.get(name)
return float(raw) if raw else default
def env_int(name: str, default: int) -> int:
raw = os.environ.get(name... | 16 | 362 |
onyx | loadtest/onyx_client/stream_parser.py | .py | """Incremental parser for the Onyx chat NDJSON stream.
Vendored from backend/tests/integration/common_utils/managers/chat.py
(analyze_response) and backend/onyx/server/query_and_chat/streaming_models.py,
restructured to process one line at a time so milestone latencies can be
recorded the moment a packet arrives.
MUS... | 154 | 5,570 |
onyx | loadtest/scenarios/thread_hog.py | .py | """Deterministic thread-occupancy driver for the worker / threadpool sweep.
Each turn streams a deliberately slow mock response, so the api-server holds one
anyio threadpool thread (the chat stream is a sync generator) for the whole
turn. Pile up enough concurrent ThreadHogUsers and the pool saturates — the
failure mo... | 37 | 1,365 |
onyx | loadtest/scenarios/__init__.py | .py | from scenarios.chat_with_search import ChatWithSearchUser
from scenarios.compression import CompressionUser
from scenarios.deep_research import DeepResearchUser
from scenarios.disconnect import DisconnectUser
from scenarios.file_attachment import FileAttachmentUser
from scenarios.health_probe import HealthProbeUser
fro... | 22 | 701 |
onyx | loadtest/scenarios/disconnect.py | .py | """Client drops the stream mid-turn (default: after the first answer token)
to exercise server-side disconnect cleanup (held transactions/connections/
buffers). Recorded as `<prefix>:disconnected`, not a failure. Run on its own
(not in the default mix). See README.
"""
from __future__ import annotations
import os
fr... | 21 | 586 |
onyx | loadtest/scenarios/compression.py | .py | """Long-history chat that drives the summarization / compression path.
Builds on LongConversationUser: keeps one session alive for many turns and
sends large messages (default ONYX_MSG_CHARS), so the history quickly crosses
the model's input-token limit and Onyx summarizes/recompresses it every turn.
This is the path ... | 34 | 1,326 |
onyx | loadtest/scenarios/file_attachment.py | .py | """Chat turns that carry a file attachment.
Each user uploads one file up front, then attaches it to every message. This
exercises the chat-setup path that loads attached files from object storage
(MinIO/S3) inside `build_chat_turn` *while the DB connection is held* — the
suspected connection-pool-hold contributor tha... | 64 | 2,389 |
onyx | loadtest/scenarios/deep_research.py | .py | """Deep research turn.
No special model knobs are needed: the DR orchestrator and research agents
call the LLM with tool_choice=REQUIRED, and the mock's branching handles the
whole sequence statelessly — clarification (`generate_plan`), plan text,
research_agent spawn (parallelism via the `-agents<N>` knob), per-agent... | 34 | 1,210 |
onyx | loadtest/scenarios/health_probe.py | .py | """Health-probe user for the worker / threadpool concurrency experiment.
Hits the api-server /health endpoint on a fixed cadence, independent of the
chat load, and fails any probe slower than the liveness SLA. Run it alongside a
heavy chat workload (ThreadHogUser or DeepResearchUser) and watch the
``HEALTH:probe`` fai... | 86 | 3,756 |
onyx | loadtest/scenarios/multi_tool.py | .py | """Chat turn that calls several retrieval tools in parallel (the `-tools3`
knob), exercising concurrent tool execution within one turn. Degrades to a
single search if the persona offers fewer tools. Part of the default mix.
"""
from __future__ import annotations
import os
from onyx_client.chat_user import OnyxChatUs... | 19 | 519 |
onyx | loadtest/scenarios/long_conversation.py | .py | """Long multi-turn chat: grows one session's history to stress the
full-history load / token-counting / compression path that single-turn runs
never reach. Run on its own (not in the default mix). See README.
"""
from __future__ import annotations
import os
from onyx_client.chat_user import OnyxChatUser
from onyx_cl... | 22 | 739 |
onyx | loadtest/scenarios/chat_with_search.py | .py | """Chat turn that exercises the search tool path.
The `-tools1` model knob makes the mock LLM answer the first AUTO-tool-choice
cycle with an `internal_search` tool call, so Onyx genuinely executes the
search tool: query expansion, embedding model server, Vespa/OpenSearch
retrieval, document streaming. The follow-up L... | 26 | 809 |
onyx | loadtest/mock_llm/app.py | .py | """Mock OpenAI-compatible LLM server for Onyx load testing.
The whole point: drive unlimited LLM call volume at zero cost with
deterministic timing, so load tests measure Onyx's application code and
infrastructure — never answer quality or a real provider's latency.
Register in Onyx as an `openai_compatible` provider... | 490 | 19,074 |
onyx | loadtest/mock_llm/models.py | .py | """Pydantic models for the mock LLM server's OpenAI-compatible wire format.
Request models use extra="allow" and optional fields throughout: litellm
sends provider-specific extras (stream_options, user, etc.) and the mock must
never 422 a request the real OpenAI API would accept.
"""
from __future__ import annotation... | 143 | 3,441 |
onyx | loadtest/tests/test_stream_parser.py | .py | """Tests for the NDJSON parser's milestone + message-id extraction."""
from __future__ import annotations
import json
from onyx_client.stream_parser import (
FIRST_ANSWER_TOKEN,
FIRST_PACKET,
ChatStreamAnalyzer,
)
def _feed_all(analyzer: ChatStreamAnalyzer, lines: list[str]) -> list[str]:
hit: list... | 66 | 2,042 |
onyx | loadtest/tests/test_exporter.py | .py | """Tests for the Locust Prometheus collector.
Uses lightweight fakes for the runner/stats so it imports neither locust nor
gevent — keeping it safe to run in the same pytest session as the fastapi
mock_llm tests.
"""
from __future__ import annotations
from typing import Any
from prometheus_collector import LocustCo... | 82 | 2,500 |
onyx | loadtest/tests/test_mock_llm.py | .py | """Contract tests for the mock LLM server.
Each test replays the exact request shapes Onyx's LLM loops send (per
backend/onyx/chat/llm_loop.py, llm_step.py and deep_research/dr_loop.py) and
asserts the mock responds the way those loops need to make progress.
Run: uv run pytest tests/ -q
"""
from __future__ import a... | 395 | 13,406 |
MoneyPrinterV2 | tests/test_config.py | .py | import json
import os
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT_DIR = os.path.dirname(os.path.dirname(__file__))
SRC_DIR = os.path.join(ROOT_DIR, "src")
if SRC_DIR not in sys.path:
sys.path.insert(0, SRC_DIR)
import config
class PostBridgeConfigTests(unittest.TestCase):
... | 85 | 2,762 |
MoneyPrinterV2 | tests/test_post_bridge_client.py | .py | import os
import sys
import unittest
from unittest.mock import Mock
from unittest.mock import patch
ROOT_DIR = os.path.dirname(os.path.dirname(__file__))
SRC_DIR = os.path.join(ROOT_DIR, "src")
if SRC_DIR not in sys.path:
sys.path.insert(0, SRC_DIR)
from classes.PostBridge import PostBridge
class MockResponse... | 157 | 5,374 |
MoneyPrinterV2 | tests/test_post_bridge_integration.py | .py | import os
import sys
import tempfile
import unittest
from unittest.mock import Mock
from unittest.mock import patch
ROOT_DIR = os.path.dirname(os.path.dirname(__file__))
SRC_DIR = os.path.join(ROOT_DIR, "src")
if SRC_DIR not in sys.path:
sys.path.insert(0, SRC_DIR)
from post_bridge_integration import maybe_cros... | 153 | 5,166 |
MoneyPrinterV2 | tests/test_cron_post_bridge.py | .py | import os
import sys
import types
import unittest
from unittest.mock import Mock
from unittest.mock import patch
ROOT_DIR = os.path.dirname(os.path.dirname(__file__))
SRC_DIR = os.path.join(ROOT_DIR, "src")
if SRC_DIR not in sys.path:
sys.path.insert(0, SRC_DIR)
fake_kittentts = types.ModuleType("kittentts")
fa... | 89 | 2,663 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.