Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions api/controllers/console/app/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
ConfigDict,
Field,
RootModel,
ValidationError,
field_validator,
model_validator,
)
Expand Down Expand Up @@ -660,7 +659,7 @@ def post(self, current_user: Account, app_model: App):
elif "text/plain" in content_type:
try:
args_model = SyncDraftWorkflowPayload.model_validate_json(request.data)
except (ValueError, ValidationError):
except ValueError:
raise InvalidArgumentError("Invalid JSON data")
else:
abort(415)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from flask import abort, request
from flask_restx import Resource
from pydantic import BaseModel, Field, RootModel, ValidationError
from pydantic import BaseModel, Field, RootModel
from sqlalchemy.orm import Session, sessionmaker
from werkzeug.exceptions import BadRequest, Forbidden, InternalServerError, NotFound

Expand Down Expand Up @@ -253,7 +253,7 @@ def post(self, current_user: Account, pipeline: Pipeline):
elif "text/plain" in content_type:
try:
payload = DraftWorkflowSyncPayload.model_validate_json(request.data)
except (ValueError, ValidationError):
except ValueError:
raise InvalidArgumentError("Invalid JSON data")
else:
abort(415)
Expand Down
4 changes: 2 additions & 2 deletions api/controllers/console/explore/trial.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@
from controllers.console.remote_files import RemoteFileUploadPayload, upload_remote_file
from controllers.console.wraps import cloud_edition_billing_resource_check, model_validate
from controllers.web.error import InvokeRateLimitError as InvokeRateLimitHttpError
from core.app.apps.agent_app.errors import AgentAppGeneratorError, AgentAppNotPublishedError
from core.app.apps.agent_app.errors import AgentAppGeneratorError
from core.app.entities.app_invoke_entities import InvokeFrom
from core.errors.error import (
AppInvokeQuotaExceededError,
Expand Down Expand Up @@ -668,7 +668,7 @@ def post(self, req_data: ChatRequest, request_context: RequestContext, trial_app
except services.errors.app_model_config.AppModelConfigBrokenError:
logger.exception("App model config broken.")
raise AppUnavailableError()
except (AgentAppGeneratorError, AgentAppNotPublishedError):
except AgentAppGeneratorError:
raise AppUnavailableError() from None
except ProviderTokenNotInitError as ex:
raise ProviderNotInitializeError(ex.description)
Expand Down
4 changes: 2 additions & 2 deletions api/core/plugin/plugin_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from typing import Literal, Protocol

import zstandard
from pydantic import BaseModel, TypeAdapter, ValidationError
from pydantic import BaseModel, TypeAdapter
from redis import RedisError
from redis.exceptions import LockError
from sqlalchemy import delete, select, update
Expand Down Expand Up @@ -336,7 +336,7 @@ def _load_cached_plugin_model_providers_for_generation(
try:
providers = cls._get_or_parse_plugin_model_providers_cache_payload(cached_providers)
return providers, True
except (TypeError, ValueError, ValidationError):
except (TypeError, ValueError):
logger.warning(
"Invalid cached plugin model providers for tenant %s; deleting cache key %s.",
tenant_id,
Expand Down
5 changes: 2 additions & 3 deletions api/core/provider_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from collections.abc import Callable, Sequence
from dataclasses import asdict, dataclass
from enum import StrEnum
from json import JSONDecodeError
from typing import TYPE_CHECKING, Any, Protocol, Self

from pydantic import TypeAdapter, ValidationError
Expand Down Expand Up @@ -1493,7 +1492,7 @@ def _get_and_decrypt_credentials(

try:
credentials = _credentials_adapter.validate_json(encrypted_config)
except (ValueError, JSONDecodeError):
except ValueError:
return {}

# Decrypt secret variables
Expand Down Expand Up @@ -1793,7 +1792,7 @@ def _to_model_settings(
provider_model_credentials = _credentials_adapter.validate_json(
load_balancing_model_config.encrypted_config
)
except (ValueError, JSONDecodeError):
except ValueError:
continue

# Get decoding context for decrypting credentials
Expand Down
2 changes: 1 addition & 1 deletion api/core/workflow/file_reference.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def parse_file_reference(reference: str | None) -> FileReference | None:
encoded_payload = reference.removeprefix(_FILE_REFERENCE_PREFIX)
try:
payload = json.loads(base64.urlsafe_b64decode(encoded_payload.encode()))
except (ValueError, json.JSONDecodeError):
except ValueError:
return FileReference(record_id=reference)

record_id = payload.get("record_id")
Expand Down
2 changes: 1 addition & 1 deletion api/libs/oauth.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def decode_oauth_state(state: str | None) -> OAuthState:
padded_state = state + "=" * (-len(state) % 4)
raw_state = base64.urlsafe_b64decode(padded_state.encode("ascii")).decode("utf-8")
return OAUTH_STATE_ADAPTER.validate_python(json.loads(raw_state))
except (binascii.Error, ValueError, UnicodeDecodeError, json.JSONDecodeError, ValidationError):
except (binascii.Error, ValueError):
return {}


Expand Down
1 change: 0 additions & 1 deletion api/libs/token.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,6 @@ def _unauthorized():
verified = PassportService().verify(csrf_token)
except Exception:
_unauthorized()
raise # unreachable, but helps the type checker see verified is always bound

if verified.get("sub") != user_id:
_unauthorized()
Expand Down
2 changes: 1 addition & 1 deletion api/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ dev = [
# "locust>=2.40.4", # Temporarily removed due to compatibility issues. Uncomment when resolved.
"pytest-timeout>=2.4.0",
"pytest-xdist>=3.8.0",
"pyrefly>=1.3.2",
"pyrefly>=1.4.0",
"xinference-client>=2.7.0",
"types-pytz>=2026.3.1.20260727",
"types-bleach>=6.4.0.20260728",
Expand Down
4 changes: 2 additions & 2 deletions api/repositories/data_source/credential_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from collections.abc import Mapping
from typing import cast

from pydantic import TypeAdapter, ValidationError
from pydantic import TypeAdapter
from sqlalchemy import cast as sql_cast
from sqlalchemy import select, update
from sqlalchemy.engine import CursorResult
Expand All @@ -24,7 +24,7 @@ def _source_mapping(value: object) -> Mapping[str, object]:
if isinstance(value, str):
return _CREDENTIALS_ADAPTER.validate_json(value)
return _CREDENTIALS_ADAPTER.validate_python(value)
except (TypeError, ValueError, ValidationError):
except (TypeError, ValueError):
return {}


Expand Down
4 changes: 2 additions & 2 deletions api/repositories/knowledge/document_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from collections.abc import Mapping

from pydantic import TypeAdapter, ValidationError
from pydantic import TypeAdapter
from sqlalchemy import exists, select, update
from sqlalchemy.orm import Session, sessionmaker

Expand All @@ -27,7 +27,7 @@ def _mapping(value: object) -> Mapping[str, object] | None:
if isinstance(value, str):
return _MAPPING_ADAPTER.validate_json(value)
return _MAPPING_ADAPTER.validate_python(value)
except (TypeError, ValueError, ValidationError):
except (TypeError, ValueError):
return {}


Expand Down
4 changes: 2 additions & 2 deletions api/services/dataset_storage_cleanup_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import logging
from typing import Literal

from pydantic import BaseModel, ValidationError, field_validator
from pydantic import BaseModel, field_validator
from sqlalchemy import select

from core.db.session_factory import session_factory
Expand All @@ -30,7 +30,7 @@ def _crawl_cache_key(data_source_info: str | None) -> str | None:
return None
try:
info = FirecrawlDataSourceInfo.model_validate_json(data_source_info)
except (ValueError, TypeError, ValidationError):
except (ValueError, TypeError):
return None
return f"website_files/{info.job_id}.txt"

Expand Down
3 changes: 0 additions & 3 deletions api/services/knowledge/dataset_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -3204,9 +3204,6 @@ def process_rule_args_validate(cls, knowledge_config: KnowledgeConfig):

unique_pre_processing_rule_dicts = {}
for pre_processing_rule in knowledge_config.process_rule.rules.pre_processing_rules:
if not pre_processing_rule.id:
raise ValueError("Process rule pre_processing_rules id is required")

if not isinstance(pre_processing_rule.enabled, bool):
raise ValueError("Process rule pre_processing_rules enabled is invalid")

Expand Down
4 changes: 1 addition & 3 deletions api/services/knowledge/documents/adapters.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,8 +344,6 @@ def _creation_dataset(
) -> DocumentCreationDataset:
with self._sessions() as session:
dataset = _require_dataset(session, ref)
if not dataset.indexing_technique and not config.indexing_technique:
raise ValueError("indexing_technique is required.")
self._actor(session, context)
DatasetService.check_doc_form(dataset, config.doc_form, session=session)
return DocumentCreationDataset(
Expand Down Expand Up @@ -542,7 +540,7 @@ def change_status(
DocumentService.batch_update_document_status(
dataset, [doc.id for doc in documents], action, account, session
)
except (ValueError, DocumentIndexingError) as error:
except ValueError as error:
raise DocumentInvalidActionError(str(error)) from error

def sync_website(self, ref: DocumentRef) -> None:
Expand Down
2 changes: 1 addition & 1 deletion api/services/tools/tools_transform_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def get_tool_provider_icon_url(
parsed = emoji_icon_adapter.validate_json(icon)
return {"background": parsed["background"], "content": parsed["content"]}
return {"background": icon["background"], "content": icon["content"]}
except (ValueError, ValidationError, KeyError):
except (ValueError, KeyError):
return {"background": "#252525", "content": "\ud83d\ude01"}
case ToolProviderType.MCP:
if isinstance(icon, Mapping):
Expand Down
4 changes: 2 additions & 2 deletions api/services/workflow_draft_variable_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
from enum import StrEnum
from typing import Any, ClassVar, NotRequired, TypedDict, cast, override
from typing import Any, ClassVar, NotRequired, TypedDict, override

from sqlalchemy import Engine, delete, orm, select
from sqlalchemy.dialects.mysql import insert as mysql_insert
Expand Down Expand Up @@ -1072,7 +1072,7 @@ def _try_offload_large_variable(
original_content_serialized: str
if isinstance(value_seg, StringSegment):
# For string types, store as plain text
original_content_serialized = cast(str, value_seg.value)
original_content_serialized = value_seg.value
content_type = "text/plain"
filename = f"{self._generate_filename(name)}.txt"
else:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -619,7 +619,7 @@ def test_export_skill_maps_service_error(app: Flask, request_context: RequestCon

def test_inner_api_pulls_published_skill_archive(app: Flask) -> None:
api = PublishedSkillPullApi()
method = unwrap(api.get)
method = unwrap(PublishedSkillPullApi.get)
service, pull_published_archive = _recording_service(
"pull_published_archive",
result=PublishedSkillArchive(
Expand All @@ -646,7 +646,7 @@ def test_inner_api_pulls_published_skill_archive(app: Flask) -> None:

def test_inner_api_pull_maps_missing_tenant_to_invalid_request(app: Flask) -> None:
api = PublishedSkillPullApi()
method = unwrap(api.get)
method = unwrap(PublishedSkillPullApi.get)

with app.test_request_context("/", method="GET"):
payload, status = method(api, "skill-1")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def test_upload_returns_the_existing_plugin_file_contract(
service = application_services.return_value.plugin_file_uploads
service.upload.return_value = _result()

response, status = unwrap(module.PluginUploadFileApi().post)(module.PluginUploadFileApi())
response, status = unwrap(module.PluginUploadFileApi.post)(module.PluginUploadFileApi())

assert status == 201
assert response == {
Expand Down Expand Up @@ -134,7 +134,7 @@ def test_missing_file_has_a_specific_client_error(self, monkeypatch: pytest.Monk
monkeypatch.setattr(module, "request", _fake_request(_valid_args()))

with pytest.raises(module.NoFileUploadedError):
unwrap(module.PluginUploadFileApi().post)(module.PluginUploadFileApi())
unwrap(module.PluginUploadFileApi.post)(module.PluginUploadFileApi())

@pytest.mark.parametrize(
("file", "expected_error"),
Expand All @@ -152,7 +152,7 @@ def test_invalid_file_metadata_has_a_specific_client_error(
monkeypatch.setattr(module, "request", _fake_request(_valid_args(), file=file))

with pytest.raises(expected_error):
unwrap(module.PluginUploadFileApi().post)(module.PluginUploadFileApi())
unwrap(module.PluginUploadFileApi.post)(module.PluginUploadFileApi())

@patch.object(module, "application_services")
def test_access_denied_is_reported_without_leaking_identity_details(
Expand All @@ -164,7 +164,7 @@ def test_access_denied_is_reported_without_leaking_identity_details(
application_services.return_value.plugin_file_uploads.upload.side_effect = PluginFileUploadAccessDeniedError()

with pytest.raises(module.InvalidPluginFileUploadError) as error_info:
unwrap(module.PluginUploadFileApi().post)(module.PluginUploadFileApi())
unwrap(module.PluginUploadFileApi.post)(module.PluginUploadFileApi())

assert error_info.value.code == 403
assert error_info.value.error_code == "invalid_plugin_file_upload"
Expand All @@ -181,7 +181,7 @@ def test_signed_size_limit_is_reported_as_413(
)

with pytest.raises(module.FileTooLargeError) as error_info:
unwrap(module.PluginUploadFileApi().post)(module.PluginUploadFileApi())
unwrap(module.PluginUploadFileApi.post)(module.PluginUploadFileApi())

assert error_info.value.code == 413
assert error_info.value.__cause__ is not None
Expand All @@ -196,7 +196,7 @@ def test_unsupported_file_type_is_reported_as_415(
application_services.return_value.plugin_file_uploads.upload.side_effect = ServiceUnsupportedFileTypeError()

with pytest.raises(module.UnsupportedFileTypeError) as error_info:
unwrap(module.PluginUploadFileApi().post)(module.PluginUploadFileApi())
unwrap(module.PluginUploadFileApi.post)(module.PluginUploadFileApi())

assert error_info.value.code == 415
assert error_info.value.__cause__ is not None
Expand All @@ -212,7 +212,7 @@ def test_unexpected_failure_is_not_relabelled_as_a_client_error(
application_services.return_value.plugin_file_uploads.upload.side_effect = storage_error

with pytest.raises(OSError) as error_info:
unwrap(module.PluginUploadFileApi().post)(module.PluginUploadFileApi())
unwrap(module.PluginUploadFileApi.post)(module.PluginUploadFileApi())

assert error_info.value is storage_error

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def _mint(app: Flask, payload: dict[str, object]) -> dict[str, object]:
with app.test_request_context("/", method="POST", json=payload):
with patch(f"{CONTROLLER_MODULE}.inner_api_ns") as mock_ns:
mock_ns.payload = payload
return inspect.unwrap(handler.post)(handler)
return inspect.unwrap(EnterpriseFileGrantApi.post)(handler)


def _subject_of(response: dict[str, object]) -> str:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import pytest
from flask import Flask
from pytest_mock import MockerFixture

from core.app.apps.base_app_queue_manager import PublishFrom
from core.app.apps.message_based_app_queue_manager import MessageBasedAppQueueManager
Expand All @@ -18,7 +19,7 @@ def _publish_mock(manager: MessageBasedAppQueueManager) -> MagicMock:

class TestOutputModeration:
@pytest.fixture
def queue_manager(self) -> MessageBasedAppQueueManager:
def queue_manager(self, mocker: MockerFixture) -> MessageBasedAppQueueManager:
with patch("core.app.apps.base_app_queue_manager.redis_client.setex"):
manager = MessageBasedAppQueueManager(
task_id="test-task",
Expand All @@ -28,7 +29,7 @@ def queue_manager(self) -> MessageBasedAppQueueManager:
app_mode="chat",
message_id="test-message",
)
manager.publish = MagicMock(wraps=manager.publish)
mocker.patch.object(manager, "publish", wraps=manager.publish)
return manager

@pytest.fixture
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from unittest.mock import MagicMock

from pytest_mock import MockerFixture

from core.prompt.agent_history_prompt_transform import AgentHistoryPromptTransform
Expand Down Expand Up @@ -53,13 +51,13 @@ def side_effect_get_num_tokens(*args: object) -> int:
)

max_token_limit = 5
transform._calculate_rest_token = MagicMock(return_value=max_token_limit)
mocker.patch.object(transform, "_calculate_rest_token", return_value=max_token_limit)
result = transform.get_prompt()

assert len(result) == 4

max_token_limit = 20
transform._calculate_rest_token = MagicMock(return_value=max_token_limit)
mocker.patch.object(transform, "_calculate_rest_token", return_value=max_token_limit)
result = transform.get_prompt()

assert len(result) == 12
Loading
Loading