Skip to content

armgit / dify

Public Imported from GitHub
0

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.

fix: skip empty tool entries in agent_chat config validation (#37775)

Yufeng Hecf7ac6120feb
diff --git a/api/core/app/apps/agent_chat/app_config_manager.py b/api/core/app/apps/agent_chat/app_config_manager.py
index c3c55973ce0..095967bc078 100644
--- a/api/core/app/apps/agent_chat/app_config_manager.py
+++ b/api/core/app/apps/agent_chat/app_config_manager.py
@@ -171,11 +171,15 @@ class AgentChatAppConfigManager(BaseAppConfigManager):
def validate_agent_mode_and_set_defaults(
cls, tenant_id: str, config: dict[str, Any], session: Session
) -> tuple[dict[str, Any], list[str]]:
- """
- Validate agent_mode and set defaults for agent feature
+ """Validate agent settings and populate defaults in place.
+
+ The caller supplies untrusted config and a session for tenant-scoped
+ dataset checks. On success, every tool entry is a non-empty object.
+ Empty or non-object entries raise ValueError rather than being ignored.
:param tenant_id: tenant ID
- :param config: app model config args
+ :param config: app model config args, updated with defaults
+ :param session: session used to validate dataset references
"""
if not config.get("agent_mode"):
config["agent_mode"] = {"enabled": False, "tools": []}
@@ -206,6 +210,8 @@ class AgentChatAppConfigManager(BaseAppConfigManager):
raise ValueError("tools in agent_mode must be a list of objects")
for tool in agent_mode["tools"]:
+ if not isinstance(tool, dict) or not tool:
+ raise ValueError("Each item in agent_mode.tools must be a non-empty object")
key = list(tool.keys())[0]
if key in OLD_TOOLS:
# old style, use tool name as key
diff --git a/api/tests/unit_tests/controllers/console/app/test_completion.py b/api/tests/unit_tests/controllers/console/app/test_completion.py
new file mode 100644
index 00000000000..51d34fc3c39
--- /dev/null
+++ b/api/tests/unit_tests/controllers/console/app/test_completion.py
@@ -0,0 +1,141 @@
+from __future__ import annotations
+
+from collections.abc import Callable
+from inspect import unwrap
+from uuid import uuid4
+
+import pytest
+from flask import Flask
+from flask.typing import ResponseReturnValue
+from flask_restx import Resource
+from sqlalchemy.orm import Session
+
+from controllers.console.app import completion as completion_module
+from core.app.app_config.easy_ui_based_app.model_config import manager as model_config_manager_module
+from core.entities.model_entities import ModelStatus, ModelWithProviderEntity, SimpleModelProviderEntity
+from core.entities.provider_configuration import ProviderConfigurations
+from core.plugin.impl.model_runtime_factory import PluginModelAssembly
+from enums import DeploymentEdition
+from graphon.model_runtime.entities.common_entities import I18nObject
+from graphon.model_runtime.entities.model_entities import FetchFrom, ModelPropertyKey, ModelType
+from graphon.model_runtime.entities.provider_entities import ProviderEntity
+from libs.external_api import ExternalApi
+from models.model import AppMode, AppModelConfig
+from tests.helpers.unit.model_factories import make_account, make_app
+
+_TENANT_ID = "tenant-1"
+_PROVIDER_ID = "langgenius/openai/openai"
+_MODEL_ID = "gpt-4o-mini"
+
+
+def _install_model_discovery(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Replace plugin-daemon I/O while retaining the production model validation objects."""
+ provider = ProviderEntity(
+ provider=_PROVIDER_ID,
+ label=I18nObject(en_US="OpenAI"),
+ supported_model_types=[ModelType.LLM],
+ configurate_methods=[],
+ )
+ model = ModelWithProviderEntity(
+ model=_MODEL_ID,
+ label=I18nObject(en_US="GPT-4o mini"),
+ model_type=ModelType.LLM,
+ fetch_from=FetchFrom.PREDEFINED_MODEL,
+ model_properties={ModelPropertyKey.MODE: "chat"},
+ status=ModelStatus.ACTIVE,
+ provider=SimpleModelProviderEntity(provider),
+ )
+ assembly = PluginModelAssembly(tenant_id=_TENANT_ID)
+ configurations = ProviderConfigurations(tenant_id=_TENANT_ID)
+
+ def get_providers() -> list[ProviderEntity]:
+ return [provider]
+
+ def get_configurations(tenant_id: str) -> ProviderConfigurations:
+ assert tenant_id == _TENANT_ID
+ return configurations
+
+ def get_models(
+ self: ProviderConfigurations, *, provider: str, model_type: ModelType
+ ) -> list[ModelWithProviderEntity]:
+ assert self is configurations
+ assert provider == _PROVIDER_ID
+ assert model_type == ModelType.LLM
+ return [model]
+
+ def create_assembly(*, tenant_id: str) -> PluginModelAssembly:
+ assert tenant_id == _TENANT_ID
+ return assembly
+
+ monkeypatch.setattr(assembly.model_provider_factory, "get_providers", get_providers)
+ monkeypatch.setattr(assembly.provider_manager, "get_configurations", get_configurations)
+ monkeypatch.setattr(ProviderConfigurations, "get_models", get_models)
+ monkeypatch.setattr(model_config_manager_module, "create_plugin_model_assembly", create_assembly)
+
+
+def test_chat_message_rejects_empty_agent_tool_as_invalid_param(
+ sqlite_session: Session,
+ monkeypatch: pytest.MonkeyPatch,
+ config_overrides: Callable[..., None],
+) -> None:
+ """The debugger HTTP path rejects malformed tools before generation starts."""
+ config_overrides(
+ DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY,
+ APP_DEFAULT_ACTIVE_REQUESTS=0,
+ APP_MAX_ACTIVE_REQUESTS=0,
+ )
+ _install_model_discovery(monkeypatch)
+
+ account = make_account(account_id=str(uuid4()))
+ app_id = str(uuid4())
+ stored_config = AppModelConfig(app_id=app_id, created_by=account.id, updated_by=account.id)
+ app_model = make_app(
+ app_id=app_id,
+ tenant_id=_TENANT_ID,
+ mode=AppMode.AGENT_CHAT,
+ app_model_config_id=stored_config.id,
+ max_active_requests=0,
+ created_by=account.id,
+ )
+ sqlite_session.add_all([stored_config, app_model])
+ sqlite_session.commit()
+
+ class ChatMessageHttpResource(Resource):
+ def post(self) -> ResponseReturnValue:
+ # Admission is supplied by this harness; parsing, generation validation,
+ # and HTTP error translation remain the real production path.
+ return unwrap(completion_module.ChatMessageApi.post)(
+ completion_module.ChatMessageApi(), sqlite_session, _TENANT_ID, account, app_model
+ )
+
+ http_app = Flask(__name__)
+ http_app.config.update(TESTING=True)
+ ExternalApi(http_app).add_resource(ChatMessageHttpResource, "/chat-messages")
+
+ response = http_app.test_client().post(
+ "/chat-messages",
+ json={
+ "inputs": {},
+ "query": "hello",
+ "response_mode": "streaming",
+ "model_config": {
+ "model": {
+ "provider": _PROVIDER_ID,
+ "name": _MODEL_ID,
+ "completion_params": {},
+ },
+ "agent_mode": {
+ "enabled": True,
+ "strategy": "router",
+ "tools": [{}],
+ },
+ },
+ },
+ )
+
+ assert response.status_code == 400
+ assert response.get_json() == {
+ "code": "invalid_param",
+ "message": "Each item in agent_mode.tools must be a non-empty object",
+ "status": 400,
+ }
diff --git a/api/tests/unit_tests/core/app/apps/agent_chat/test_app_config_manager.py b/api/tests/unit_tests/core/app/apps/agent_chat/test_app_config_manager.py
index cd309ed6e20..222421db3ce 100644
--- a/api/tests/unit_tests/core/app/apps/agent_chat/test_app_config_manager.py
+++ b/api/tests/unit_tests/core/app/apps/agent_chat/test_app_config_manager.py
@@ -1,3 +1,4 @@
+import json
import uuid
import pytest
@@ -94,6 +95,7 @@ class TestAgentChatAppConfigManagerGetAppConfig:
assert result.agent is not None
assert result.agent.strategy.value == "function-calling"
+ @pytest.mark.parametrize("tools", [[], [{}]], ids=["no-tools", "legacy-empty-tool"])
@pytest.mark.parametrize(
("conversation", "expected_from"),
[
@@ -103,11 +105,13 @@ class TestAgentChatAppConfigManagerGetAppConfig:
)
def test_get_app_config_stored_config(
self,
+ tools: list[dict[str, object]],
conversation: Conversation | None,
expected_from: EasyUIBasedAppModelConfigFrom,
) -> None:
"""None selects the latest app config; a conversation selects its supplied config."""
app_model_config = _config()
+ app_model_config.agent_mode = json.dumps({**app_model_config.agent_mode_dict, "tools": tools})
result = AgentChatAppConfigManager.get_app_config(
app_model=_app(),
app_model_config=app_model_config,
@@ -124,6 +128,7 @@ class TestAgentChatAppConfigManagerGetAppConfig:
assert result.model.model == "m"
assert result.agent is not None
assert result.agent.strategy.value == "function-calling"
+ assert result.agent.tools == []
def test_get_app_config_requires_annotation_reply_without_override(self):
with pytest.raises(ValueError, match="Annotation reply config is required"):
@@ -343,3 +348,27 @@ class TestValidateAgentModeAndSetDefaults:
updated, _ = AgentChatAppConfigManager.validate_agent_mode_and_set_defaults("tenant", config, _session())
assert updated["agent_mode"]["tools"][0]["dataset"]["enabled"] is False
assert updated["agent_mode"]["tools"][1]["enabled"] is False
+
+ @pytest.mark.parametrize(
+ "tool",
+ [
+ pytest.param({}, id="empty-object"),
+ pytest.param(None, id="null"),
+ pytest.param(False, id="boolean"),
+ pytest.param(0, id="number"),
+ pytest.param("", id="empty-string"),
+ pytest.param("tool", id="string"),
+ pytest.param([], id="empty-list"),
+ pytest.param(["tool"], id="list"),
+ ],
+ )
+ def test_tool_entries_must_be_non_empty_objects(self, tool: object) -> None:
+ config = {
+ "agent_mode": {
+ "enabled": True,
+ "strategy": PlanningStrategy.ROUTER.value,
+ "tools": [tool],
+ }
+ }
+ with pytest.raises(ValueError, match=r"Each item in agent_mode\.tools must be a non-empty object"):
+ AgentChatAppConfigManager.validate_agent_mode_and_set_defaults("tenant", config, _session())