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/llm/cost.py
.py
"""LLM cost calculation utilities.""" from pydantic import BaseModel from sqlalchemy.orm import Session from onyx.configs.app_configs import ( DEFAULT_IMAGE_COST_CENTS, DEFAULT_LLM_INPUT_COST_PER_MTOK, DEFAULT_LLM_OUTPUT_COST_PER_MTOK, ) from onyx.llm import cost_overrides from onyx.tracing.flows import I...
211
7,741
onyx
backend/onyx/llm/request_context.py
.py
import contextvars _LLM_MOCK_RESPONSE_CONTEXTVAR: contextvars.ContextVar[str | None] = ( contextvars.ContextVar("llm_mock_response", default=None) ) def get_llm_mock_response() -> str | None: return _LLM_MOCK_RESPONSE_CONTEXTVAR.get() def set_llm_mock_response(mock_response: str | None) -> contextvars.Toke...
23
746
onyx
backend/onyx/llm/api_surfaces.py
.py
"""Wire protocols ("API surfaces") that provider endpoints speak. Routing depends on the surface rather than the provider: which LiteLLM provider to impersonate, whether to coerce the base URL to `/v1`, and how to address the model. A gateway can expose several surfaces, with the admin picking one. """ from enum impo...
82
3,192
onyx
backend/onyx/llm/factory.py
.py
from collections.abc import Callable from typing import Any from sqlalchemy.orm import Session from onyx.auth.schemas import UserRole from onyx.configs.model_configs import GEN_AI_TEMPERATURE from onyx.db.engine.sql_engine import get_session_with_current_tenant from onyx.db.enums import LLMModelFlowType from onyx.db....
502
17,940
onyx
backend/onyx/llm/interfaces.py
.py
import abc from collections.abc import Callable, Iterator from typing import Any from pydantic import BaseModel from onyx.llm.model_response import ModelResponse, ModelResponseStream from onyx.llm.models import ( LanguageModelInput, ReasoningEffort, ToolChoice, ToolChoiceOptions, # noqa: F401 # re-e...
112
3,778
onyx
backend/onyx/llm/model_response.py
.py
from __future__ import annotations from typing import TYPE_CHECKING, Any, List from pydantic import BaseModel, Field from onyx.llm.models import AnyThinkingBlock, RedactedThinkingBlock, ThinkingBlock from onyx.utils.logger import setup_logger logger = setup_logger() class FunctionCall(BaseModel): arguments: s...
278
8,824
onyx
backend/onyx/llm/litellm_singleton/monkey_patches.py
.py
""" LiteLLM Monkey Patches This module addresses the following issues in LiteLLM: Status checked against LiteLLM v1.93.0 (2026-07-20): 1. Ollama Streaming Reasoning Content (_patch_ollama_chunk_parser): - LiteLLM's chunk_parser doesn't properly handle reasoning content in streaming responses from Ollama -...
718
31,273
onyx
backend/onyx/llm/litellm_singleton/__init__.py
.py
""" Singleton module for litellm configuration. This ensures litellm is configured exactly once when first imported. All other modules should import litellm from here instead of directly. """ import litellm from .config import initialize_litellm from .monkey_patches import apply_monkey_patches initialize_litellm() a...
17
414
onyx
backend/onyx/llm/litellm_singleton/config.py
.py
import json from pathlib import Path import litellm from onyx.utils.logger import remove_litellm_native_log_handlers, setup_logger logger = setup_logger() def configure_litellm_settings() -> None: # If a user configures a different model and it doesn't support all the same # parameters like frequency and p...
166
8,978
onyx
backend/onyx/llm/well_known_providers/models.py
.py
from enum import Enum from pydantic import BaseModel, Field from onyx.server.manage.llm.models import ModelConfigurationView class CustomConfigKeyType(str, Enum): # used for configuration values that require manual input # i.e., textual API keys (e.g., "abcd1234") TEXT_INPUT = "text_input" # used f...
32
982
onyx
backend/onyx/llm/well_known_providers/auto_update_models.py
.py
"""Pydantic models for GitHub-hosted Auto LLM configuration.""" from datetime import datetime from typing import Any from pydantic import BaseModel, field_validator from onyx.llm.well_known_providers.models import SimpleKnownModel class LLMProviderRecommendation(BaseModel): """Configuration for a single provid...
61
2,235
onyx
backend/onyx/llm/well_known_providers/constants.py
.py
from onyx.llm.constants import LlmProviderNames OPENAI_PROVIDER_NAME = "openai" BEDROCK_PROVIDER_NAME = "bedrock" OLLAMA_PROVIDER_NAME = "ollama_chat" LM_STUDIO_PROVIDER_NAME = "lm_studio" LM_STUDIO_API_KEY_CONFIG_KEY = "LM_STUDIO_API_KEY" LITELLM_PROXY_PROVIDER_NAME = "litellm_proxy" BIFROST_PROVIDER_NAME = "bi...
71
2,523
onyx
backend/onyx/llm/well_known_providers/auto_update_service.py
.py
"""Service for fetching and syncing LLM model configurations from GitHub. This service manages Auto mode LLM providers, where models and configuration are managed centrally via a GitHub-hosted JSON file. In Auto mode: - Model list is controlled by GitHub config - Model visibility is controlled by GitHub config - Defau...
151
4,847
onyx
backend/onyx/llm/well_known_providers/llm_provider_options.py
.py
import json import pathlib import threading import time from onyx.llm.constants import ( PROVIDER_DISPLAY_NAMES, WELL_KNOWN_PROVIDER_NAMES, LlmProviderNames, ) from onyx.llm.model_capabilities import get_max_input_tokens from onyx.llm.utils import model_supports_image_input from onyx.llm.well_known_provide...
378
13,737
onyx
backend/onyx/llm/prompt_cache/utils.py
.py
# pyright: reportMissingTypeStubs=false """Utility functions for prompt caching.""" import json from collections.abc import Callable, Sequence from typing import Any from onyx.llm.models import ChatCompletionMessage, LanguageModelInput from onyx.utils.logger import setup_logger logger = setup_logger() def combine_...
120
4,203
onyx
backend/onyx/llm/prompt_cache/models.py
.py
"""Interfaces and data structures for prompt caching.""" from datetime import datetime from pydantic import BaseModel class CacheMetadata(BaseModel): """Metadata for cached prompt prefixes.""" cache_key: str provider: str model_name: str tenant_id: str created_at: datetime last_accessed...
21
551
onyx
backend/onyx/llm/prompt_cache/cache_manager.py
.py
"""Cache manager for storing and retrieving prompt cache metadata.""" import hashlib import json from datetime import datetime, timezone from onyx.configs.model_configs import PROMPT_CACHE_REDIS_TTL_MULTIPLIER from onyx.key_value_store.store import PgRedisKVStore from onyx.llm.interfaces import LanguageModelInput fro...
230
7,899
onyx
backend/onyx/llm/prompt_cache/__init__.py
.py
"""Prompt caching framework for LLM providers. This module provides a framework for enabling prompt caching across different LLM providers. It supports both implicit caching (automatic provider-side caching) and explicit caching (with cache metadata management). """ from onyx.llm.prompt_cache.cache_manager import Cac...
36
1,466
onyx
backend/onyx/llm/prompt_cache/processor.py
.py
"""Main processor for prompt caching.""" from datetime import datetime, timezone from onyx.configs.model_configs import ENABLE_PROMPT_CACHING from onyx.llm.interfaces import LLMConfig from onyx.llm.models import LanguageModelInput from onyx.llm.prompt_cache.cache_manager import generate_cache_key_hash from onyx.llm.p...
153
6,047
onyx
backend/onyx/llm/prompt_cache/providers/openai.py
.py
"""OpenAI provider adapter for prompt caching.""" from onyx.llm.interfaces import LanguageModelInput from onyx.llm.prompt_cache.models import CacheMetadata from onyx.llm.prompt_cache.providers.base import PromptCacheProvider from onyx.llm.prompt_cache.utils import prepare_messages_with_cacheable_transform class Open...
70
2,587
onyx
backend/onyx/llm/prompt_cache/providers/__init__.py
.py
"""Provider adapters for prompt caching.""" from onyx.llm.prompt_cache.providers.anthropic import AnthropicPromptCacheProvider from onyx.llm.prompt_cache.providers.base import PromptCacheProvider from onyx.llm.prompt_cache.providers.factory import get_provider_adapter from onyx.llm.prompt_cache.providers.noop import N...
18
704
onyx
backend/onyx/llm/prompt_cache/providers/anthropic.py
.py
"""Anthropic provider adapter for prompt caching.""" from collections.abc import Sequence from onyx.llm.interfaces import LanguageModelInput from onyx.llm.models import ChatCompletionMessage from onyx.llm.prompt_cache.models import CacheMetadata from onyx.llm.prompt_cache.providers.base import PromptCacheProvider fro...
98
3,580
onyx
backend/onyx/llm/prompt_cache/providers/factory.py
.py
"""Factory for creating provider-specific prompt cache adapters.""" import logging from onyx.llm.constants import LlmProviderNames from onyx.llm.interfaces import LLMConfig from onyx.llm.prompt_cache.providers.anthropic import AnthropicPromptCacheProvider from onyx.llm.prompt_cache.providers.base import PromptCachePr...
74
3,282
onyx
backend/onyx/llm/prompt_cache/providers/vertex.py
.py
"""Vertex AI provider adapter for prompt caching.""" from collections.abc import Sequence from onyx.llm.interfaces import LanguageModelInput from onyx.llm.models import ChatCompletionMessage from onyx.llm.prompt_cache.models import CacheMetadata from onyx.llm.prompt_cache.providers.base import PromptCacheProvider fro...
128
5,199
onyx
backend/onyx/llm/prompt_cache/providers/base.py
.py
"""Base interface for provider-specific prompt caching adapters.""" from abc import ABC, abstractmethod from onyx.llm.interfaces import LanguageModelInput from onyx.llm.prompt_cache.models import CacheMetadata class PromptCacheProvider(ABC): """Abstract base class for provider-specific prompt caching logic.""" ...
70
2,285
onyx
backend/onyx/llm/prompt_cache/providers/noop.py
.py
"""No-op provider adapter for providers without caching support.""" from onyx.llm.models import LanguageModelInput from onyx.llm.prompt_cache.models import CacheMetadata from onyx.llm.prompt_cache.providers.base import PromptCacheProvider from onyx.llm.prompt_cache.utils import prepare_messages_with_cacheable_transfor...
54
2,004
onyx
backend/onyx/tools/utils.py
.py
import json from collections.abc import Callable from typing import Any from sqlalchemy.orm import Session from onyx.configs.app_configs import AZURE_IMAGE_API_KEY from onyx.db.connector import check_connectors_exist from onyx.db.document import check_docs_exist from onyx.db.models import LLMProvider from onyx.llm.co...
73
2,190
onyx
backend/onyx/tools/built_in_tools.py
.py
from typing import Type, Union from onyx.tools.tool_implementations.coding_agent.coding_agent_tool import ( CodingAgentTool, ) from onyx.tools.tool_implementations.file_reader.file_reader_tool import FileReaderTool from onyx.tools.tool_implementations.images.image_generation_tool import ( ImageGenerationTool, ...
81
2,675
onyx
backend/onyx/tools/models.py
.py
from __future__ import annotations import json from enum import Enum from typing import Any, Callable, Literal from uuid import UUID from pydantic import BaseModel, ConfigDict, model_validator from onyx.chat.emitter import Emitter from onyx.configs.chat_configs import MAX_CHUNKS_FED_TO_CHAT, NUM_RETURNED_HITS from o...
340
11,124
onyx
backend/onyx/tools/constants.py
.py
"""Tool name and ID constants matching frontend definitions.""" # Tool names as referenced by tool results / tool calls SEARCH_TOOL_NAME = "run_search" INTERNET_SEARCH_TOOL_NAME = "run_internet_search" IMAGE_GENERATION_TOOL_NAME = "run_image_generation" PYTHON_TOOL_NAME = "run_python" OPEN_URL_TOOL_NAME = "open_url" ...
22
804
onyx
backend/onyx/tools/tool_constructor.py
.py
from collections import Counter from collections.abc import Sequence from typing import cast from uuid import UUID from pydantic import BaseModel from sqlalchemy.orm import Session from onyx.auth.oauth_token_manager import OAuthTokenManager from onyx.chat.emitter import Emitter from onyx.configs.app_configs import DI...
538
22,481
onyx
backend/onyx/tools/tool_runner.py
.py
import traceback from collections import defaultdict from typing import Any import onyx.tracing.framework._error_tracing as _error_tracing from onyx.chat.models import ChatMessageSimple from onyx.configs.constants import MessageType from onyx.context.search.models import SearchDocsResponse from onyx.db.memory import U...
454
18,557
onyx
backend/onyx/tools/tool_name.py
.py
import re # Bedrock rejects toolUse.name values that don't match [a-zA-Z0-9_-]+, and # OpenAI imposes the same constraint on function names. User-supplied Tool.name # and OpenAPI operationId can contain spaces, dots, etc. _INVALID_TOOL_NAME_CHARS = re.compile(r"[^a-zA-Z0-9_-]") def sanitize_tool_name(name: str) -> s...
11
375
onyx
backend/onyx/tools/interface.py
.py
from __future__ import annotations import abc from typing import Any, Generic, TypeVar from sqlalchemy.orm import Session from onyx.chat.emitter import Emitter from onyx.server.query_and_chat.placement import Placement from onyx.tools.models import ToolResponse TOverride = TypeVar("TOverride") class Tool(abc.ABC,...
96
2,879
onyx
backend/onyx/tools/fake_tools/research_agent.py
.py
import queue import time from collections.abc import Callable from typing import Any, cast from onyx.chat.chat_state import ChatStateContainer from onyx.chat.chat_utils import create_tool_call_failure_messages from onyx.chat.citation_processor import ( CitationMapping, CitationMode, DynamicCitationProcesso...
818
36,142
onyx
backend/onyx/tools/fake_tools/coding_agent.py
.py
import time from collections.abc import Iterator from contextlib import contextmanager from typing import Callable from onyx.chat.emitter import Emitter from onyx.chat.llm_loop import construct_message_history from onyx.chat.llm_step import run_llm_step_pkt_generator from onyx.chat.models import ChatMessageSimple, Too...
521
21,466
onyx
backend/onyx/tools/tool_implementations/utils.py
.py
import json from onyx.context.search.models import InferenceSection from onyx.context.search.utils import sandbox_filename_for_document from onyx.utils.logger import setup_logger logger = setup_logger() def truncate_output(output: str, max_length: int, label: str = "output") -> str: """Truncate to ``max_length`...
126
4,606
onyx
backend/onyx/tools/tool_implementations/search_like_tool_utils.py
.py
from onyx.connectors.models import Document, IndexingDocument, Section FINAL_CONTEXT_DOCUMENTS_ID = "final_context_documents" FINAL_SEARCH_QUERIES_ID = "final_search_queries" SEARCH_INFERENCE_SECTIONS_ID = "search_inference_sections" def documents_to_indexing_documents( documents: list[Document], ) -> list[Index...
29
940
onyx
backend/onyx/tools/tool_implementations/open_url/utils.py
.py
from onyx.tools.tool_implementations.open_url.models import WebContent def filter_web_contents_with_no_title_or_content( contents: list[WebContent], ) -> list[WebContent]: """Filter out content entries that have neither a title nor any extracted text. Some content providers can return placeholder/partial...
18
694
onyx
backend/onyx/tools/tool_implementations/open_url/onyx_web_crawler.py
.py
from __future__ import annotations from collections.abc import Sequence from concurrent.futures import ThreadPoolExecutor import requests from onyx.configs.app_configs import OPEN_URL_PLAYWRIGHT_FALLBACK_ENABLED from onyx.file_processing.html_utils import ParsedHTML, web_html_cleanup from onyx.server.security.models...
391
15,798
onyx
backend/onyx/tools/tool_implementations/open_url/snippet_matcher.py
.py
import unicodedata from pydantic import BaseModel from rapidfuzz import fuzz, utils from onyx.utils.text_processing import is_zero_width_char, normalize_char class SnippetMatchResult(BaseModel): snippet_located: bool start_idx: int = -1 end_idx: int = -1 NegativeSnippetMatchResult = SnippetMatchResul...
245
7,837
onyx
backend/onyx/tools/tool_implementations/open_url/models.py
.py
from abc import ABC, abstractmethod from collections.abc import Sequence from datetime import datetime from pydantic import BaseModel, field_validator from onyx.utils.url import normalize_url class WebContent(BaseModel): title: str link: str full_content: str published_date: datetime | None = None ...
39
1,091
onyx
backend/onyx/tools/tool_implementations/open_url/tavily.py
.py
from __future__ import annotations from collections.abc import Sequence from typing import Any import requests from onyx.tools.tool_implementations.open_url.models import ( WebContent, WebContentProvider, ) from onyx.utils.logger import setup_logger logger = setup_logger() TAVILY_EXTRACT_URL = "https://api...
147
4,352
onyx
backend/onyx/tools/tool_implementations/open_url/firecrawl.py
.py
from __future__ import annotations from collections.abc import Sequence from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass from datetime import datetime from typing import Any import requests from onyx.connectors.cross_connector_utils.miscellaneous_utils import time_str_to_utc from o...
167
5,290
onyx
backend/onyx/tools/tool_implementations/open_url/open_url_tool.py
.py
import json from collections import defaultdict from typing import Any from pydantic import BaseModel from sqlalchemy.orm import Session from typing_extensions import override from onyx.chat.emitter import Emitter from onyx.configs.app_configs import DISABLE_VECTOR_DB from onyx.context.search.models import ( Inde...
993
38,619
onyx
backend/onyx/tools/tool_implementations/open_url/url_normalization.py
.py
"""URL normalization for OpenURL tool. Each connector implements normalize_url() as a class method to normalize URLs to match the canonical Document.id format used during ingestion. This ensures OpenURL can find indexed documents. Usage: normalized = normalize_url("https://docs.google.com/document/d/123/edit") ...
133
4,730
onyx
backend/onyx/tools/tool_implementations/file_reader/file_reader_tool.py
.py
import io import json from typing import Any, cast from uuid import UUID from sqlalchemy.orm import Session from typing_extensions import override from onyx.chat.emitter import Emitter from onyx.configs.app_configs import DISABLE_VECTOR_DB from onyx.db.engine.sql_engine import get_session_with_current_tenant from ony...
259
9,002
onyx
backend/onyx/tools/tool_implementations/images/models.py
.py
from pydantic import BaseModel from onyx.server.query_and_chat.streaming_models import GeneratedImage class ImageGenerationResponse(BaseModel): revised_prompt: str image_data: str class FinalImageGenerationResponse(BaseModel): generated_images: list[GeneratedImage]
13
283
onyx
backend/onyx/tools/tool_implementations/images/image_generation_tool.py
.py
import json import threading from typing import Any, cast import requests from sqlalchemy.orm import Session from typing_extensions import override from onyx.chat.emitter import Emitter from onyx.configs.app_configs import IMAGE_MODEL_NAME, IMAGE_MODEL_PROVIDER from onyx.file_store.models import ChatFileType from ony...
433
15,930
onyx
backend/onyx/tools/tool_implementations/search/search_utils.py
.py
from collections import defaultdict from collections.abc import Callable from typing import TypeVar from onyx.context.search.models import ( ContextExpansionType, IndexFilters, InferenceChunk, InferenceSection, ) from onyx.context.search.utils import inference_section_from_chunks from onyx.document_ind...
500
19,377
onyx
backend/onyx/tools/tool_implementations/search/constants.py
.py
"""Constants for search tool implementations.""" # Query Expansion and Fusion Weights # Taking an opinionated stance on the weights, no chance users can do a good job customizing this. # The dedicated rephrased/extracted semantic query is likely the best for hybrid search LLM_SEMANTIC_QUERY_WEIGHT = 1.3 # The keyword ...
30
1,537
onyx
backend/onyx/tools/tool_implementations/search/search_tool.py
.py
""" An explanation of the search tool found below: Step 1: Queries - The LLM will generate some queries based on the chat history for what it thinks are the best things to search for. This has a pretty generic prompt so it's not perfectly tuned for search but provides breadth and also the LLM can often break up the qu...
1,229
49,044
onyx
backend/onyx/tools/tool_implementations/python/code_interpreter_client.py
.py
from __future__ import annotations import json import re import time from collections.abc import Callable, Generator from functools import wraps from typing import Any, Concatenate, Literal, ParamSpec, TypedDict, TypeVar, Union import requests from pydantic import BaseModel from onyx.configs.app_configs import CODE_...
513
16,741
onyx
backend/onyx/tools/tool_implementations/python/python_tool.py
.py
import hashlib import mimetypes import os import re from io import BytesIO from typing import Any, cast from pydantic import BaseModel, TypeAdapter from sqlalchemy.orm import Session from typing_extensions import override from onyx.chat.emitter import Emitter from onyx.configs.app_configs import ( CODE_INTERPRETE...
595
23,165
onyx
backend/onyx/tools/tool_implementations/bash/bash_tool.py
.py
from typing import Any from pydantic import BaseModel, TypeAdapter from sqlalchemy.orm import Session from typing_extensions import override from onyx.chat.emitter import Emitter from onyx.configs.app_configs import ( CODE_INTERPRETER_BASE_URL, CODE_INTERPRETER_DEFAULT_TIMEOUT_MS, CODE_INTERPRETER_MAX_OUT...
234
7,649
onyx
backend/onyx/tools/tool_implementations/custom/openapi_parsing.py
.py
from typing import Any, cast from pydantic import BaseModel from onyx.tools.tool_name import sanitize_tool_name REQUEST_BODY = "requestBody" class PathSpec(BaseModel): path: str methods: dict[str, Any] class MethodSpec(BaseModel): # Sanitized, LLM-safe name; used in tool definitions and dispatch. ...
244
8,020
onyx
backend/onyx/tools/tool_implementations/custom/custom_tool.py
.py
import csv import json import queue import uuid from io import BytesIO, StringIO from typing import Any, Dict, List import requests from requests import JSONDecodeError from onyx.chat.emitter import Emitter from onyx.configs.constants import FileOrigin from onyx.file_store.file_store import get_default_file_store fro...
414
14,088
onyx
backend/onyx/tools/tool_implementations/custom/base_tool_types.py
.py
# should really be `JSON_ro`, but this causes issues with pydantic ToolResultType = dict | list | str | int | float | bool
3
123
onyx
backend/onyx/tools/tool_implementations/web_search/utils.py
.py
from onyx.configs.constants import DocumentSource from onyx.context.search.models import InferenceChunk, InferenceSection, SearchDoc from onyx.tools.tool_implementations.open_url.models import WebContent from onyx.tools.tool_implementations.open_url.snippet_matcher import ( find_snippet_in_content, ) from onyx.tool...
207
6,093
onyx
backend/onyx/tools/tool_implementations/web_search/models.py
.py
from abc import abstractmethod from collections.abc import Sequence from datetime import datetime from enum import Enum from pydantic import BaseModel, field_validator from onyx.utils.url import normalize_url # Fairly loose number but assuming LLMs can easily handle this amount of context # Approximately 2 pages of ...
58
1,455
onyx
backend/onyx/tools/tool_implementations/web_search/web_search_tool.py
.py
import json from typing import Any from sqlalchemy.orm import Session from typing_extensions import override from onyx.chat.emitter import Emitter from onyx.context.search.models import SearchDocsResponse from onyx.context.search.utils import convert_inference_sections_to_search_docs from onyx.db.engine.sql_engine im...
359
13,207
onyx
backend/onyx/tools/tool_implementations/web_search/providers.py
.py
from onyx.db.engine.sql_engine import get_session_with_current_tenant from onyx.db.models import InternetSearchProvider from onyx.db.web_search import ( fetch_active_web_content_provider, fetch_active_web_search_provider, ) from onyx.tools.tool_implementations.open_url.firecrawl import FirecrawlClient from onyx...
216
8,080
onyx
backend/onyx/tools/tool_implementations/web_search/clients/brave_client.py
.py
from __future__ import annotations from typing import Any import requests from fastapi import HTTPException from onyx.tools.tool_implementations.web_search.models import ( WebSearchProvider, WebSearchResult, ) from onyx.utils.logger import setup_logger from onyx.utils.retry_wrapper import retry_builder logg...
258
8,267
onyx
backend/onyx/tools/tool_implementations/web_search/clients/tavily_client.py
.py
from __future__ import annotations from typing import Any import requests from fastapi import HTTPException from onyx.tools.tool_implementations.web_search.models import ( WebSearchProvider, WebSearchResult, ) from onyx.utils.logger import setup_logger from onyx.utils.retry_wrapper import retry_builder logg...
228
6,977
onyx
backend/onyx/tools/tool_implementations/web_search/clients/searxng_client.py
.py
import requests from fastapi import HTTPException from onyx.tools.tool_implementations.web_search.models import ( WebSearchProvider, WebSearchResult, ) from onyx.utils.logger import setup_logger from onyx.utils.retry_wrapper import retry_builder logger = setup_logger() class SearXNGClient(WebSearchProvider)...
139
5,401
onyx
backend/onyx/tools/tool_implementations/web_search/clients/exa_client.py
.py
import re from collections.abc import Sequence from typing import Any import requests from exa_py import Exa from exa_py.api import HighlightsContentsOptions from fastapi import HTTPException from onyx.connectors.cross_connector_utils.miscellaneous_utils import time_str_to_utc from onyx.tools.tool_implementations.ope...
224
7,601
onyx
backend/onyx/tools/tool_implementations/web_search/clients/serper_client.py
.py
import json from collections.abc import Sequence from concurrent.futures import ThreadPoolExecutor import requests from fastapi import HTTPException from onyx.connectors.cross_connector_utils.miscellaneous_utils import time_str_to_utc from onyx.tools.tool_implementations.open_url.models import ( WebContent, W...
197
6,181
onyx
backend/onyx/tools/tool_implementations/web_search/clients/google_pse_client.py
.py
from __future__ import annotations from datetime import datetime from typing import Any import requests from fastapi import HTTPException from onyx.tools.tool_implementations.web_search.models import ( WebSearchProvider, WebSearchResult, ) from onyx.utils.logger import setup_logger from onyx.utils.retry_wrap...
160
5,773
onyx
backend/onyx/tools/tool_implementations/mcp/mcp_tool.py
.py
import json import time from typing import Any from mcp.client.auth import OAuthClientProvider from onyx.chat.emitter import Emitter from onyx.db.enums import MCPAuthenticationType, MCPTransport from onyx.db.models import MCPConnectionConfig, MCPServer from onyx.server.features.mcp.client import call_mcp_tool from on...
342
12,757
onyx
backend/onyx/tools/tool_implementations/coding_agent/coding_agent_tool.py
.py
from typing import Any, cast from uuid import uuid4 from pydantic import BaseModel from sqlalchemy.orm import Session from typing_extensions import override from onyx.chat.emitter import Emitter from onyx.coding_agent.mock_tools import ( CODING_AGENT_QUERY_KEY, CODING_AGENT_REPO_KEY, CODING_AGENT_TOOL_NAM...
192
6,374
onyx
backend/onyx/tools/tool_implementations/knowledge_graph/knowledge_graph_tool.py
.py
from typing import Any from sqlalchemy.orm import Session from onyx.chat.emitter import Emitter from onyx.db.kg_config import get_kg_config_settings from onyx.server.query_and_chat.placement import Placement from onyx.tools.interface import Tool from onyx.tools.models import ToolResponse from onyx.utils.logger import...
82
2,356
onyx
backend/onyx/tools/tool_implementations/memory/memory_tool.py
.py
""" Memory Tool for storing user-specific information. This tool allows the LLM to save memories about the user for future conversations. The memories are passed in via override_kwargs which contains the current list of memories that exist for the user. """ from typing import Any, Literal, cast from pydantic import ...
163
5,408
onyx
backend/onyx/tools/tool_implementations/memory/models.py
.py
from pydantic import BaseModel class MemoryToolResponse(BaseModel): memory_text: str index_to_replace: int | None # None = add new, int = replace at 0-based index
7
174
onyx
backend/onyx/onyxbot/discord/handle_commands.py
.py
"""Discord bot command handlers for registration and channel sync.""" import asyncio from datetime import datetime, timezone import discord from onyx.configs.app_configs import DISCORD_BOT_INVOKE_CHAR from onyx.configs.constants import ONYX_DISCORD_URL from onyx.db.discord_bot import ( bulk_create_channel_config...
440
16,376
onyx
backend/onyx/onyxbot/discord/utils.py
.py
from onyx.configs.app_configs import DISCORD_BOT_TOKEN from onyx.db.discord_bot import get_discord_bot_config from onyx.db.engine.sql_engine import get_session_with_tenant from onyx.utils.logger import setup_logger from onyx.utils.sensitive import SensitiveValue from shared_configs.configs import MULTI_TENANT, POSTGRES...
43
1,510
onyx
backend/onyx/onyxbot/discord/exceptions.py
.py
"""Custom exception classes for Discord bot.""" class DiscordBotError(Exception): """Base exception for Discord bot errors.""" class RegistrationError(DiscordBotError): """Error during guild registration.""" class SyncChannelsError(DiscordBotError): """Error during channel sync.""" class APIError(Di...
38
800
onyx
backend/onyx/onyxbot/discord/handle_message.py
.py
"""Discord bot message handling and response logic.""" import asyncio import discord from pydantic import BaseModel from onyx.chat.models import ChatFullResponse from onyx.db.discord_bot import ( get_channel_config_by_discord_ids, get_guild_config_by_discord_id, ) from onyx.db.engine.sql_engine import get_se...
501
16,578
onyx
backend/onyx/onyxbot/discord/constants.py
.py
"""Discord bot constants.""" # API settings API_REQUEST_TIMEOUT: int = 3 * 60 # 3 minutes # Cache settings CACHE_REFRESH_INTERVAL: int = 60 # 1 minute # Message settings MAX_MESSAGE_LENGTH: int = 2000 # Discord's character limit MAX_CONTEXT_MESSAGES: int = 10 # Max messages to include in conversation context # N...
20
659
onyx
backend/onyx/onyxbot/discord/client.py
.py
"""Discord bot client with integrated message handling.""" import asyncio import time import discord from discord.ext import commands from onyx.configs.app_configs import DISCORD_BOT_INVOKE_CHAR from onyx.onyxbot.discord.api_client import OnyxAPIClient from onyx.onyxbot.discord.cache import DiscordCacheManager from ...
238
7,868
onyx
backend/onyx/onyxbot/discord/api_client.py
.py
"""Async HTTP client for communicating with Onyx API pods.""" import aiohttp from onyx.chat.models import ChatFullResponse from onyx.onyxbot.discord.constants import API_REQUEST_TIMEOUT from onyx.onyxbot.discord.exceptions import ( APIConnectionError, APIResponseError, APITimeoutError, ) from onyx.server....
222
7,710
onyx
backend/onyx/onyxbot/discord/cache.py
.py
"""Multi-tenant cache for Discord bot guild-tenant mappings and API keys.""" import asyncio from typing import NamedTuple from onyx.db.discord_bot import get_guild_configs, get_or_create_discord_service_api_key from onyx.db.engine.sql_engine import get_session_with_tenant from onyx.db.engine.tenant_utils import get_a...
194
7,471
onyx
backend/onyx/onyxbot/slack/utils.py
.py
import random import re import string import threading import time import uuid from collections.abc import Generator from contextlib import contextmanager from typing import Any, cast from slack_sdk import WebClient from slack_sdk.errors import SlackApiError from slack_sdk.models.blocks import Block, SectionBlock from...
769
26,640
onyx
backend/onyx/onyxbot/slack/listener.py
.py
import os import signal import sys import threading import time from collections.abc import Callable from contextvars import Token from threading import Event from types import FrameType from typing import Any, Dict, cast import psycopg2.errors from prometheus_client import Gauge, start_http_server from redis.exceptio...
1,341
51,183
onyx
backend/onyx/onyxbot/slack/models.py
.py
from enum import Enum from typing import Literal from pydantic import BaseModel from onyx.configs.constants import MessageType class ChannelType(str, Enum): """Slack channel types.""" IM = "im" # Direct message MPIM = "mpim" # Multi-person direct message PRIVATE_CHANNEL = "private_channel" # Pri...
79
2,326
onyx
backend/onyx/onyxbot/slack/constants.py
.py
import re from enum import Enum # Matches Slack channel references like <#C097NBWMY8Y> or <#C097NBWMY8Y|channel-name> SLACK_CHANNEL_REF_PATTERN = re.compile(r"<#([A-Z0-9]+)(?:\|([^>]+))?>") LIKE_BLOCK_ACTION_ID = "feedback-like" DISLIKE_BLOCK_ACTION_ID = "feedback-dislike" SHOW_EVERYONE_ACTION_ID = "show-everyone" KE...
24
870
onyx
backend/onyx/onyxbot/slack/config.py
.py
import os from sqlalchemy.orm import Session from onyx.db.models import SlackChannelConfig from onyx.db.slack_channel_config import ( fetch_slack_channel_config_for_channel_or_default, fetch_slack_channel_configs, ) VALID_SLACK_FILTERS = [ "answerable_prefilter", "well_answered_postfilter", "ques...
72
2,496
onyx
backend/onyx/onyxbot/slack/icons.py
.py
from collections.abc import Mapping from onyx.configs.constants import DocumentSource _PUBLIC_SOURCE_IMAGE_BASE_URL = "https://raw.githubusercontent.com/onyx-dot-app/onyx/main/web/public/slackbot-source-icons" _DEFAULT_SOURCE_IMAGE_FILENAME = "File.png" _SOURCE_IMAGE_FILENAMES: Mapping[DocumentSource, str] = { D...
76
3,284
onyx
backend/onyx/onyxbot/slack/blocks.py
.py
from datetime import datetime from typing import cast import pytz import timeago from slack_sdk.models.blocks import ( ActionsBlock, Block, ButtonElement, ContextBlock, DividerBlock, HeaderBlock, Option, RadioButtonsElement, SectionBlock, ) from slack_sdk.models.blocks.basic_compone...
536
18,398
onyx
backend/onyx/onyxbot/slack/formatting.py
.py
import re from collections.abc import Callable from typing import Any from mistune import ( BlockState, HTMLRenderer, InlineParser, InlineState, Markdown, PluginRef, create_markdown, ) # Tags that should be replaced with a newline (line-break and block-level elements) _HTML_NEWLINE_TAG_PAT...
464
16,341
onyx
backend/onyx/onyxbot/slack/handlers/handle_standard_answers.py
.py
from slack_sdk import WebClient from sqlalchemy.orm import Session from onyx.db.models import SlackChannelConfig from onyx.onyxbot.slack.models import SlackMessageInfo from onyx.utils.logger import OnyxLoggingAdapter, setup_logger from onyx.utils.variable_functionality import fetch_versioned_implementation logger = s...
52
1,733
onyx
backend/onyx/onyxbot/slack/handlers/handle_message.py
.py
import datetime from slack_sdk import WebClient from slack_sdk.errors import SlackApiError from sqlalchemy.orm import Session from onyx.configs.onyxbot_configs import ( ONYX_BOT_FEEDBACK_REMINDER, ONYX_BOT_REACT_EMOJI, ) from onyx.db.engine.sql_engine import get_session_with_current_tenant from onyx.db.enums ...
461
19,037
onyx
backend/onyx/onyxbot/slack/handlers/handle_buttons.py
.py
import json from typing import Any, cast from slack_sdk import WebClient from slack_sdk.models.blocks import SectionBlock from slack_sdk.models.views import View from slack_sdk.socket_mode.request import SocketModeRequest from slack_sdk.webhook import WebhookClient from onyx.chat.models import ChatBasicResponse from ...
586
21,562
onyx
backend/onyx/onyxbot/slack/handlers/handle_regular_answer.py
.py
import functools from collections.abc import Callable from typing import Any, Optional, TypeVar from slack_sdk import WebClient from sqlalchemy.orm import Session from onyx.auth.users import get_anonymous_user from onyx.chat.models import ChatBasicResponse from onyx.chat.process_message import gather_stream, handle_s...
502
18,191
onyx
backend/onyx/context/search/pipeline.py
.py
from collections import defaultdict from datetime import datetime from sqlalchemy.orm import Session from onyx.context.search.forced_document_set import get_forced_document_set_names from onyx.context.search.models import ( BaseFilters, ChunkIndexRequest, ChunkSearchRequest, IndexFilters, Inferenc...
349
13,759
onyx
backend/onyx/context/search/utils.py
.py
import os import re from typing import TypeVar from sqlalchemy.orm import Session from onyx.configs.app_configs import ( QUERY_EMBEDDING_CACHE_ENABLED, QUERY_EMBEDDING_CACHE_TTL_S, ) from onyx.context.search.models import ( InferenceChunk, InferenceSection, SavedSearchDoc, SavedSearchDocWithCo...
213
6,754
onyx
backend/onyx/context/search/models.py
.py
from collections.abc import Sequence from datetime import datetime, timezone from enum import Enum from typing import Any from pydantic import BaseModel, Field, field_validator, model_validator from onyx.configs.constants import DocumentSource from onyx.db.models import SearchSettings from onyx.indexing.models import...
496
18,252
onyx
backend/onyx/context/search/forced_document_set.py
.py
"""Operator-forced document-set search scope (self-hosted Search UI only). When ``FORCED_DOCUMENT_SET_NAMES`` is set, the Onyx Search UI is hard-restricted to those document sets. The vector index stores document set NAMES, so the configured names are used directly β€” no resolution needed. Disabled under MULTI_TENANT. ...
47
1,871
onyx
backend/onyx/context/search/enums.py
.py
"""NOTE: this needs to be separate from models.py because of circular imports. Both search/models.py and db/models.py import enums from this file AND search/models.py imports from db/models.py.""" from enum import Enum class RecencyBiasSetting(str, Enum): FAVOR_RECENT = "favor_recent" # 2x decay rate BASE_D...
32
834
onyx
backend/onyx/context/search/preprocessing/access_filters.py
.py
from sqlalchemy.orm import Session from onyx.access.access import get_acl_for_user from onyx.context.search.models import IndexFilters from onyx.db.models import User def build_access_filters_for_user(user: User, session: Session) -> list[str]: user_acl = get_acl_for_user(user, session) return list(user_acl)...
23
683
onyx
backend/onyx/context/search/federated/slack_search_utils.py
.py
import fnmatch import json import re from datetime import datetime, timedelta, timezone from typing import Any from pydantic import ValidationError from onyx.configs.app_configs import MAX_SLACK_QUERY_EXPANSIONS from onyx.context.search.federated.models import ChannelMetadata, DirectThreadFetch from onyx.context.sear...
758
26,751