From de8491ea9945462396a162ddecdda331d14fe3fe Mon Sep 17 00:00:00 2001 From: xiao8 <1018053166@qq.com> Date: Tue, 28 Jul 2026 13:10:52 +0800 Subject: [PATCH] fix(openai_compatible): omit rerank authorization without an API key (#206) Co-authored-by: WH-2099 --- .../model/openai_compatible/rerank.py | 7 ++- .../model/openai_compatible/test_rerank.py | 51 +++++++++++++++++++ 2 files changed, 54 insertions(+), 4 deletions(-) create mode 100644 tests/interfaces/model/openai_compatible/test_rerank.py diff --git a/src/dify_plugin/interfaces/model/openai_compatible/rerank.py b/src/dify_plugin/interfaces/model/openai_compatible/rerank.py index 21f119dc..bcc164a0 100644 --- a/src/dify_plugin/interfaces/model/openai_compatible/rerank.py +++ b/src/dify_plugin/interfaces/model/openai_compatible/rerank.py @@ -66,10 +66,9 @@ class OAICompatRerankModel(RerankModel): raise CredentialsValidateFailedError(msg) url = server_url - headers = { - "Authorization": f"Bearer {credentials.get('api_key')}", - "Content-Type": "application/json", - } + headers = {"Content-Type": "application/json"} + if api_key := credentials.get("api_key"): + headers["Authorization"] = f"Bearer {api_key}" # Open question: truncate docs before llama.cpp-compatible requests? diff --git a/tests/interfaces/model/openai_compatible/test_rerank.py b/tests/interfaces/model/openai_compatible/test_rerank.py new file mode 100644 index 00000000..174ed851 --- /dev/null +++ b/tests/interfaces/model/openai_compatible/test_rerank.py @@ -0,0 +1,51 @@ +from unittest.mock import MagicMock, patch + +import pytest + +from dify_plugin.interfaces.model.openai_compatible.rerank import ( + OAICompatRerankModel, +) + + +@pytest.mark.parametrize( + ("credentials", "expected_headers"), + [ + ( + {"endpoint_url": "https://example.com/v1"}, + {"Content-Type": "application/json"}, + ), + ( + {"endpoint_url": "https://example.com/v1", "api_key": None}, + {"Content-Type": "application/json"}, + ), + ( + {"endpoint_url": "https://example.com/v1", "api_key": ""}, + {"Content-Type": "application/json"}, + ), + ( + {"endpoint_url": "https://example.com/v1", "api_key": str(123)}, + { + "Authorization": "Bearer 123", + "Content-Type": "application/json", + }, + ), + ], +) +def test_invoke_only_sends_authorization_with_api_key( + credentials: dict, expected_headers: dict[str, str] +) -> None: + response = MagicMock() + response.json.return_value = {"results": [{"index": 0, "relevance_score": 1.0}]} + + with patch( + "dify_plugin.interfaces.model.openai_compatible.rerank.post", + return_value=response, + ) as post: + OAICompatRerankModel([]).invoke( + model="model", + credentials=credentials, + query="query", + docs=["document"], + ) + + assert post.call_args.kwargs["headers"] == expected_headers