Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
refactor(service_api): dep-inject query params with @model_validate (#41562)
Eddy ZHANG6411d6235cb5
diff --git a/api/controllers/service_api/app/annotation.py b/api/controllers/service_api/app/annotation.pyindex 832190e08b2..0b54d133661 100644--- a/api/controllers/service_api/app/annotation.py+++ b/api/controllers/service_api/app/annotation.py@@ -1,7 +1,6 @@from typing import Literalfrom uuid import UUID-from flask import requestfrom flask_restx import Resourcefrom flask_restx.api import HTTPStatusfrom pydantic import BaseModel, Field, TypeAdapter@@ -207,9 +206,9 @@ class AnnotationListApi(Resource):)@validate_app_token@with_session(write=False)- def get(self, session: Session, app_model: App):+ @model_validate(AnnotationListQuery)+ def get(self, query: AnnotationListQuery, session: Session, app_model: App):"""List annotations for the application."""- query = AnnotationListQuery.model_validate(request.args.to_dict(flat=True))annotation_list, total = AppAnnotationService.get_annotation_list_by_app_id(app_model.id, query.page, query.limit, query.keyword, sessiondiff --git a/api/controllers/service_api/app/conversation.py b/api/controllers/service_api/app/conversation.pyindex 163a50e959b..124da072be9 100644--- a/api/controllers/service_api/app/conversation.py+++ b/api/controllers/service_api/app/conversation.py@@ -2,7 +2,6 @@ from datetime import datetimefrom typing import Annotated, Any, Literalfrom uuid import UUID-from flask import requestfrom flask_restx import Resourcefrom pydantic import BaseModel, Field, TypeAdapter, WithJsonSchema, field_validatorfrom sqlalchemy.orm import sessionmaker@@ -185,7 +184,8 @@ class ConversationApi(Resource):service_api_ns.models[ConversationInfiniteScrollPagination.__name__],)@validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.QUERY))- def get(self, app_model: App, end_user: EndUser):+ @model_validate(ConversationListQuery)+ def get(self, query_args: ConversationListQuery, app_model: App, end_user: EndUser):"""List all conversations for the current user.Supports pagination using last_id and limit parameters.@@ -194,7 +194,6 @@ class ConversationApi(Resource):if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT}:raise NotChatAppError()- query_args = ConversationListQuery.model_validate(request.args.to_dict())last_id = query_args.last_id or Nonetry:@@ -343,7 +342,8 @@ class ConversationVariablesApi(Resource):service_api_ns.models[ConversationVariableInfiniteScrollPaginationResponse.__name__],)@validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.QUERY))- def get(self, app_model: App, end_user: EndUser, conversation_id: UUID):+ @model_validate(ConversationVariablesQuery)+ def get(self, query_args: ConversationVariablesQuery, app_model: App, end_user: EndUser, conversation_id: UUID):"""List all variables for a conversation.Conversational variables are only available for chat applications.@@ -355,7 +355,6 @@ class ConversationVariablesApi(Resource):conversation_id_str = str(conversation_id)- query_args = ConversationVariablesQuery.model_validate(request.args.to_dict())last_id = query_args.last_id or Nonetry:diff --git a/api/controllers/service_api/app/file_preview.py b/api/controllers/service_api/app/file_preview.pyindex b315e190fa3..ad96ac96ce1 100644--- a/api/controllers/service_api/app/file_preview.py+++ b/api/controllers/service_api/app/file_preview.py@@ -2,7 +2,7 @@ import loggingfrom urllib.parse import quotefrom uuid import UUID-from flask import Response, request+from flask import Responsefrom flask_restx import Resourcefrom pydantic import BaseModel, Fieldfrom sqlalchemy import select@@ -10,6 +10,7 @@ from sqlalchemy import selectfrom controllers.common.fields import BinaryFileResponsefrom controllers.common.file_response import enforce_download_for_htmlfrom controllers.common.schema import query_params_from_model, register_response_schema_model, register_schema_model+from controllers.console.wraps import model_validatefrom controllers.service_api import service_api_nsfrom controllers.service_api.app.error import (FileAccessDeniedError,@@ -86,7 +87,8 @@ class FilePreviewApi(Resource):)@service_api_ns.response(200, "File retrieved successfully")@validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.QUERY))- def get(self, app_model: App, end_user: EndUser, file_id: UUID):+ @model_validate(FilePreviewQuery)+ def get(self, args: FilePreviewQuery, app_model: App, end_user: EndUser, file_id: UUID):"""Preview/Download a file that was uploaded via Service API.@@ -95,9 +97,6 @@ class FilePreviewApi(Resource):"""file_id_str = str(file_id)- # Parse query parameters- args = FilePreviewQuery.model_validate(request.args.to_dict())-# Validate file ownership and get file objects_, upload_file = self._validate_file_ownership(file_id_str, app_model.id)diff --git a/api/controllers/service_api/app/message.py b/api/controllers/service_api/app/message.pyindex d3443371313..63bf87709d9 100644--- a/api/controllers/service_api/app/message.py+++ b/api/controllers/service_api/app/message.py@@ -2,7 +2,6 @@ import loggingfrom typing import Annotatedfrom uuid import UUID-from flask import requestfrom flask_restx import Resourcefrom pydantic import BaseModel, Field, TypeAdapter, WithJsonSchemafrom werkzeug.exceptions import BadRequest, InternalServerError, NotFound@@ -102,7 +101,8 @@ class MessageListApi(Resource):service_api_ns.models[MessageInfiniteScrollPagination.__name__],)@validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.QUERY))- def get(self, app_model: App, end_user: EndUser):+ @model_validate(MessageListQuery)+ def get(self, query_args: MessageListQuery, app_model: App, end_user: EndUser):"""List messages in a conversation.Retrieves messages with pagination support using first_id.@@ -111,7 +111,6 @@ class MessageListApi(Resource):if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT}:raise NotChatAppError()- query_args = MessageListQuery.model_validate(request.args.to_dict())conversation_id = query_args.conversation_idfirst_id = query_args.first_id or None@@ -212,12 +211,12 @@ class AppGetFeedbacksApi(Resource):service_api_ns.models[AppFeedbackListResponse.__name__],)@validate_app_token- def get(self, app_model: App):+ @model_validate(FeedbackListQuery)+ def get(self, query_args: FeedbackListQuery, app_model: App):"""Get all feedbacks for the application.Returns paginated list of all feedback submitted for messages in this app."""- query_args = FeedbackListQuery.model_validate(request.args.to_dict())feedbacks = MessageService.get_all_messages_feedbacks(app_model, page=query_args.page, limit=query_args.limit, session=db.session())diff --git a/api/tests/unit_tests/controllers/service_api/app/test_annotation.py b/api/tests/unit_tests/controllers/service_api/app/test_annotation.pyindex 4bd305008bc..b27c478ba6d 100644--- a/api/tests/unit_tests/controllers/service_api/app/test_annotation.py+++ b/api/tests/unit_tests/controllers/service_api/app/test_annotation.py@@ -229,7 +229,8 @@ class TestAnnotationListApi:handler = unwrap(api.get)app_model = SimpleNamespace(id="app")with app.test_request_context("/apps/annotations", method="GET"):- response = handler(api, MagicMock(), app_model=app_model)+ query = AnnotationListQuery.model_validate(request.args.to_dict(flat=True))+ response = handler(api, query, MagicMock(), app_model=app_model)assert response["page"] == 1assert response["limit"] == 20session = get_mock.call_args.args[-1]@@ -244,7 +245,8 @@ class TestAnnotationListApi:handler = unwrap(api.get)app_model = SimpleNamespace(id="app")with app.test_request_context("/apps/annotations?page=2&limit=5&keyword=refund", method="GET"):- response = handler(api, MagicMock(), app_model=app_model)+ query = AnnotationListQuery.model_validate(request.args.to_dict(flat=True))+ response = handler(api, query, MagicMock(), app_model=app_model)assert response["total"] == 1assert response["page"] == 2assert response["limit"] == 5@@ -259,11 +261,12 @@ class TestAnnotationListApi:get_mock = Mock(return_value=([], 0))monkeypatch.setattr(AppAnnotationService, "get_annotation_list_by_app_id", get_mock)api = AnnotationListApi()- handler = unwrap(api.get)- app_model = SimpleNamespace(id="app")+ # The parse moved into @model_validate, so build the query the way the decorator does and+ # assert it is what rejects the input, before the view is ever reached.with app.test_request_context(f"/apps/annotations?{query_string}", method="GET"):with pytest.raises(ValidationError):- handler(api, MagicMock(), app_model=app_model)+ AnnotationListQuery.model_validate(request.args.to_dict(flat=True))+ assert unwrap(api.get) is not api.getget_mock.assert_not_called()def test_create(self, app: Flask, monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/api/tests/unit_tests/controllers/service_api/app/test_conversation.py b/api/tests/unit_tests/controllers/service_api/app/test_conversation.pyindex e163ebf4be5..17feffd4400 100644--- a/api/tests/unit_tests/controllers/service_api/app/test_conversation.py+++ b/api/tests/unit_tests/controllers/service_api/app/test_conversation.py@@ -539,7 +539,12 @@ class TestConversationApiController:with app.test_request_context("/conversations", method="GET"):with pytest.raises(NotChatAppError):- handler(api, app_model=app_model, end_user=end_user)+ handler(+ api,+ ConversationListQuery.model_validate(request.args.to_dict(flat=True)),+ app_model=app_model,+ end_user=end_user,+ )def test_list_last_not_found(self,@@ -566,7 +571,12 @@ class TestConversationApiController:method="GET",):with pytest.raises(NotFound):- handler(api, app_model=app_model, end_user=end_user)+ handler(+ api,+ ConversationListQuery.model_validate(request.args.to_dict(flat=True)),+ app_model=app_model,+ end_user=end_user,+ )class TestConversationDetailApiController:@@ -647,6 +657,7 @@ class TestConversationVariablesApiController:with pytest.raises(NotChatAppError):handler(api,+ ConversationVariablesQuery.model_validate(request.args.to_dict(flat=True)),app_model=app_model,end_user=end_user,conversation_id="00000000-0000-0000-0000-000000000001",@@ -671,6 +682,7 @@ class TestConversationVariablesApiController:with pytest.raises(NotFound):handler(api,+ ConversationVariablesQuery.model_validate(request.args.to_dict(flat=True)),app_model=app_model,end_user=end_user,conversation_id="00000000-0000-0000-0000-000000000001",@@ -708,6 +720,7 @@ class TestConversationVariablesApiController:):result = handler(api,+ ConversationVariablesQuery.model_validate(request.args.to_dict(flat=True)),app_model=app_model,end_user=end_user,conversation_id="00000000-0000-0000-0000-000000000001",diff --git a/api/tests/unit_tests/controllers/service_api/app/test_message.py b/api/tests/unit_tests/controllers/service_api/app/test_message.pyindex a1e1f699bbe..95c6a49b186 100644--- a/api/tests/unit_tests/controllers/service_api/app/test_message.py+++ b/api/tests/unit_tests/controllers/service_api/app/test_message.py@@ -415,9 +415,16 @@ class TestMessageListApi:app_model = SimpleNamespace(mode=AppMode.COMPLETION.value)end_user = SimpleNamespace()- with app.test_request_context("/messages?conversation_id=cid", method="GET"):+ # @model_validate parses ahead of the app-mode guard, so the id has to be well-formed to+ # reach the branch this test is about.+ with app.test_request_context("/messages?conversation_id=00000000-0000-0000-0000-000000000001", method="GET"):with pytest.raises(NotChatAppError):- handler(api, app_model=app_model, end_user=end_user)+ handler(+ api,+ MessageListQuery.model_validate(request.args.to_dict(flat=True)),+ app_model=app_model,+ end_user=end_user,+ )def test_conversation_not_found(self, app: Flask, monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(@@ -436,7 +443,12 @@ class TestMessageListApi:method="GET",):with pytest.raises(NotFound):- handler(api, app_model=app_model, end_user=end_user)+ handler(+ api,+ MessageListQuery.model_validate(request.args.to_dict(flat=True)),+ app_model=app_model,+ end_user=end_user,+ )def test_first_message_not_found(self, app: Flask, monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(@@ -455,7 +467,12 @@ class TestMessageListApi:method="GET",):with pytest.raises(NotFound):- handler(api, app_model=app_model, end_user=end_user)+ handler(+ api,+ MessageListQuery.model_validate(request.args.to_dict(flat=True)),+ app_model=app_model,+ end_user=end_user,+ )class TestMessageFeedbackApi:@@ -503,7 +520,9 @@ class TestAppGetFeedbacksApi:app_model = SimpleNamespace()with app.test_request_context("/app/feedbacks?page=1&limit=20", method="GET"):- response = handler(api, app_model=app_model)+ response = handler(+ api, FeedbackListQuery.model_validate(request.args.to_dict(flat=True)), app_model=app_model+ )assert response == {"data": [feedback]}