Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat: rerank support extra headers (#1359)

caisirius37e106a958f4
diff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.md
index 9e114b44c..0d4a24542 100644
--- a/docs/en/guides/01-configuration.md
+++ b/docs/en/guides/01-configuration.md
@@ -566,6 +566,7 @@ Reranking model for search result refinement. Supports VikingDB (Volcengine), Co
| `api_base` | str | Endpoint URL (for `openai` provider) |
| `model` | str | Model name (for `openai` or `litellm` providers) |
| `threshold` | float | Score threshold between `0.0` and `1.0`; results below this are filtered out. Default: `0.1` |
+| `extra_headers` | object | Custom HTTP headers (for OpenAI-compatible providers, optional) |
**Supported providers:**
- `vikingdb`: Volcengine VikingDB Rerank API (uses AK/SK)
@@ -1006,7 +1007,8 @@ For detailed encryption explanations, see [Data Encryption](../concepts/10-encry
"api_key": "string",
"model": "string",
"api_base": "string",
- "threshold": 0.1
+ "threshold": 0.1,
+ "extra_headers": {}
},
"encryption": {
"enabled": false,
diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.md
index 12774f5f9..9f2c10ac5 100644
--- a/docs/zh/guides/01-configuration.md
+++ b/docs/zh/guides/01-configuration.md
@@ -537,6 +537,7 @@ AST 提取支持:Python、JavaScript/TypeScript、Rust、Go、Java、C/C++。
| `api_base` | str | 接口地址(用于 `openai` 提供方) |
| `model` | str | 模型名称(用于 `openai` 或 `litellm` 提供方) |
| `threshold` | float | 分数阈值,范围为 `0.0` 到 `1.0`。低于此值的结果会被过滤。默认:`0.1` |
+| `extra_headers` | object | 自定义 HTTP 请求头(OpenAI 兼容 provider 可用,可选) |
**支持的提供方:**
- `vikingdb`: 火山引擎 VikingDB Rerank API (使用 AK/SK)
@@ -979,7 +980,8 @@ openviking add-resource ./docs --exclude "*.tmp"
"api_key": "string",
"model": "string",
"api_base": "string",
- "threshold": 0.1
+ "threshold": 0.1,
+ "extra_headers": {}
},
"encryption": {
"enabled": false,
diff --git a/openviking/models/rerank/openai_rerank.py b/openviking/models/rerank/openai_rerank.py
index 0760cb339..490743f38 100644
--- a/openviking/models/rerank/openai_rerank.py
+++ b/openviking/models/rerank/openai_rerank.py
@@ -9,7 +9,7 @@ via api_key + api_base configuration.
# For logging, use Python's built-in logging
import logging
-from typing import List, Optional
+from typing import Dict, List, Optional
import requests
@@ -25,7 +25,13 @@ class OpenAIRerankClient(RerankBase):
Compatible with services like Alibaba Cloud DashScope.
"""
- def __init__(self, api_key: str, api_base: str, model_name: str):
+ def __init__(
+ self,
+ api_key: str,
+ api_base: str,
+ model_name: str,
+ extra_headers: Optional[Dict[str, str]] = None,
+ ) -> None:
"""
Initialize OpenAI-compatible rerank client.
@@ -33,11 +39,13 @@ class OpenAIRerankClient(RerankBase):
api_key: Bearer token for authentication
api_base: Full endpoint URL for the rerank API
model_name: Model name to use for reranking
+ extra_headers: Optional extra headers for API requests
"""
super().__init__()
self.api_key = api_key
self.api_base = api_base
self.model_name = model_name
+ self.extra_headers = extra_headers or {}
self.provider = "openai"
def rerank_batch(self, query: str, documents: List[str]) -> Optional[List[float]]:
@@ -62,12 +70,16 @@ class OpenAIRerankClient(RerankBase):
}
try:
+ headers = {
+ "Authorization": f"Bearer {self.api_key}",
+ "Content-Type": "application/json",
+ }
+ if self.extra_headers:
+ headers.update(self.extra_headers)
+
response = requests.post(
url=self.api_base,
- headers={
- "Authorization": f"Bearer {self.api_key}",
- "Content-Type": "application/json",
- },
+ headers=headers,
json=req_body,
timeout=30,
)
@@ -126,4 +138,5 @@ class OpenAIRerankClient(RerankBase):
api_key=config.api_key,
api_base=config.api_base,
model_name=config.model or "qwen3-rerank",
+ extra_headers=config.extra_headers,
)
diff --git a/openviking_cli/utils/config/rerank_config.py b/openviking_cli/utils/config/rerank_config.py
index 9d6c8e468..86d579843 100644
--- a/openviking_cli/utils/config/rerank_config.py
+++ b/openviking_cli/utils/config/rerank_config.py
@@ -1,6 +1,6 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
-from typing import Optional
+from typing import Dict, Optional
from pydantic import BaseModel, Field, model_validator
@@ -31,6 +31,11 @@ class RerankConfig(BaseModel):
default=None, description="Model name for OpenAI-compatible or LiteLLM providers"
)
+ extra_headers: Optional[Dict[str, str]] = Field(
+ default=None,
+ description="Extra HTTP headers for OpenAI-compatible providers"
+ )
+
threshold: float = Field(
default=0.1, description="Relevance threshold (score > threshold is relevant)"
)
diff --git a/tests/unit/config/test_rerank_extra_headers_config.py b/tests/unit/config/test_rerank_extra_headers_config.py
new file mode 100644
index 000000000..87483f84f
--- /dev/null
+++ b/tests/unit/config/test_rerank_extra_headers_config.py
@@ -0,0 +1,64 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+"""Tests for rerank extra_headers configuration."""
+import pytest
+from pydantic import ValidationError
+
+
+def test_rerank_config_with_extra_headers():
+ """Test that extra_headers can be parsed from config."""
+ from openviking_cli.utils.config.rerank_config import RerankConfig
+
+ config_data = {
+ "model": "gpt-4",
+ "api_key": "test-key",
+ "api_base": "https://api.example.com/v1",
+ "extra_headers": {
+ "x-gw-apikey": "Bearer real-key",
+ "X-Custom-Header": "custom-value"
+ }
+ }
+
+ config = RerankConfig(**config_data)
+
+ assert config.extra_headers == {
+ "x-gw-apikey": "Bearer real-key",
+ "X-Custom-Header": "custom-value"
+ }
+
+
+def test_rerank_config_without_extra_headers():
+ """Test that extra_headers defaults to None when not provided."""
+ from openviking_cli.utils.config.rerank_config import RerankConfig
+
+ config_data = {
+ "model": "gpt-4",
+ "api_key": "test-key",
+ "api_base": "https://api.example.com/v1"
+ }
+
+ config = RerankConfig(**config_data)
+
+ assert config.extra_headers is None
+
+
+def test_rerank_config_extra_headers_type_validation():
+ """Test that extra_headers must be a dict with string keys and values."""
+ from openviking_cli.utils.config.rerank_config import RerankConfig
+
+ # Invalid: not a dict
+ with pytest.raises(ValidationError):
+ RerankConfig(
+ model="gpt-4",
+ api_key="test-key",
+ extra_headers="invalid"
+ )
+
+ # Invalid: dict with non-string value
+ with pytest.raises(ValidationError):
+ RerankConfig(
+ model="gpt-4",
+ api_key="test-key",
+ extra_headers={"header": 123}
+ )
diff --git a/tests/unit/models/rerank/test_openai_rerank_extra_headers.py b/tests/unit/models/rerank/test_openai_rerank_extra_headers.py
new file mode 100644
index 000000000..ef24e8236
--- /dev/null
+++ b/tests/unit/models/rerank/test_openai_rerank_extra_headers.py
@@ -0,0 +1,162 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Tests for OpenAIRerankClient extra_headers support."""
+from unittest.mock import Mock, patch
+import pytest
+
+from openviking_cli.utils.config.rerank_config import RerankConfig
+from openviking.models.rerank.openai_rerank import OpenAIRerankClient
+
+
+def test_openai_rerank_client_init_with_extra_headers():
+ """Test that OpenAIRerankClient accepts and stores extra_headers."""
+ client = OpenAIRerankClient(
+ api_key="test-key",
+ api_base="https://api.example.com/v1",
+ model_name="gpt-4",
+ extra_headers={"x-gw-apikey": "Bearer real-key"}
+ )
+
+ assert client.extra_headers == {"x-gw-apikey": "Bearer real-key"}
+
+
+def test_openai_rerank_client_init_without_extra_headers():
+ """Test that OpenAIRerankClient defaults to empty dict when extra_headers is None."""
+ client = OpenAIRerankClient(
+ api_key="test-key",
+ api_base="https://api.example.com/v1",
+ model_name="gpt-4",
+ extra_headers=None
+ )
+
+ assert client.extra_headers == {}
+
+
+def test_openai_rerank_from_config_with_extra_headers():
+ """Test that from_config correctly extracts extra_headers from RerankConfig."""
+ config = RerankConfig(
+ model="gpt-4",
+ api_key="test-key",
+ api_base="https://api.example.com/v1",
+ extra_headers={"x-custom": "value"}
+ )
+
+ client = OpenAIRerankClient.from_config(config)
+
+ assert client.extra_headers == {"x-custom": "value"}
+
+
+def test_openai_rerank_from_config_without_extra_headers():
+ """Test that from_config handles None extra_headers correctly."""
+ config = RerankConfig(
+ model="gpt-4",
+ api_key="test-key",
+ api_base="https://api.example.com/v1"
+ )
+
+ client = OpenAIRerankClient.from_config(config)
+
+ assert client.extra_headers == {}
+
+
+@patch("openviking.models.rerank.openai_rerank.requests.post")
+def test_rerank_batch_includes_extra_headers(mock_post):
+ """Test that rerank_batch includes extra_headers in the API request."""
+ # Setup mock response
+ mock_response = Mock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {
+ "results": [
+ {"index": 0, "relevance_score": 0.9},
+ {"index": 1, "relevance_score": 0.8}
+ ]
+ }
+ mock_post.return_value = mock_response
+
+ # Create client with extra_headers
+ client = OpenAIRerankClient(
+ api_key="test-key",
+ api_base="https://api.example.com/v1",
+ model_name="gpt-4",
+ extra_headers={
+ "x-gw-apikey": "Bearer real-key",
+ "X-Custom-Header": "custom-value"
+ }
+ )
+
+ # Call rerank_batch
+ result = client.rerank_batch(
+ query="test query",
+ documents=["doc1", "doc2"]
+ )
+
+ # Verify the request included extra_headers
+ assert mock_post.called
+ call_kwargs = mock_post.call_args.kwargs
+ headers = call_kwargs["headers"]
+
+ # Check default headers
+ assert headers["Authorization"] == "Bearer test-key"
+ assert headers["Content-Type"] == "application/json"
+
+ # Check extra headers are merged
+ assert headers["x-gw-apikey"] == "Bearer real-key"
+ assert headers["X-Custom-Header"] == "custom-value"
+
+
+@patch("openviking.models.rerank.openai_rerank.requests.post")
+def test_rerank_batch_without_extra_headers(mock_post):
+ """Test that rerank_batch works correctly when no extra_headers provided."""
+ mock_response = Mock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {
+ "results": [
+ {"index": 0, "relevance_score": 0.9}
+ ]
+ }
+ mock_post.return_value = mock_response
+
+ client = OpenAIRerankClient(
+ api_key="test-key",
+ api_base="https://api.example.com/v1",
+ model_name="gpt-4"
+ )
+
+ result = client.rerank_batch(
+ query="test query",
+ documents=["doc1"]
+ )
+
+ assert mock_post.called
+ call_kwargs = mock_post.call_args.kwargs
+ headers = call_kwargs["headers"]
+
+ # Should only have default headers
+ assert headers["Authorization"] == "Bearer test-key"
+ assert headers["Content-Type"] == "application/json"
+ # No extra headers
+ assert "x-gw-apikey" not in headers
+
+
+@patch("openviking.models.rerank.openai_rerank.requests.post")
+def test_extra_headers_can_override_defaults(mock_post):
+ """Test that extra_headers can override default headers if needed."""
+ mock_response = Mock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {"results": []}
+ mock_post.return_value = mock_response
+
+ client = OpenAIRerankClient(
+ api_key="test-key",
+ api_base="https://api.example.com/v1",
+ model_name="gpt-4",
+ extra_headers={"Content-Type": "application/json; charset=utf-8"}
+ )
+
+ client.rerank_batch(query="test", documents=["doc"])
+
+ call_kwargs = mock_post.call_args.kwargs
+ headers = call_kwargs["headers"]
+
+ # Extra header overrides default
+ assert headers["Content-Type"] == "application/json; charset=utf-8"