Files
lancedb/python/python/tests/test_openai_reranker_credentials.py
T
Kerman LauandXuanwo 0dd78656b9 fix(python): honor explicit OpenAI reranker API keys (#4515)
Fixes #4514

## Summary
Honor an explicitly supplied `OpenaiReranker(api_key=...)` before
falling back to `OPENAI_API_KEY`, matching the constructor
documentation. Previously the environment key always won when both were
set, so an instance configured for a different account still used the
process-wide account.

## Tests
Added four cases using real OpenAI client construction without sending
requests: explicit/environment conflict, explicit key alone, environment
fallback, and missing credentials. The conflict case fails before the
change; all four pass afterward. Clients are closed after each
assertion.

- Targeted source-module tests: 4 passed.
- Ruff check and format check: passed for both changed files.
- Full native source build was attempted but failed because the
environment has no Rust toolchain; bootstrap then attempted a cache path
outside the writable workspace. The targeted tests load the current
Python reranker module against installed dependencies and the released
LanceDB package; no database/native behavior is exercised. Full
native/integration suite not run.

This change and its tests were prepared with an AI coding agent. The
diff was reviewed and the failure/pass behavior verified locally.

Co-authored-by: Xuanwo <github@xuanwo.io>
2026-10-24 07:13:09 +08:00

39 lines
1.1 KiB
Python

# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import pytest
from lancedb.rerankers import OpenaiReranker
@pytest.mark.parametrize(
"explicit_key, environment_key, expected_key",
[
("explicit-test-key", "environment-test-key", "explicit-test-key"),
("explicit-test-key", None, "explicit-test-key"),
(None, "environment-test-key", "environment-test-key"),
],
)
def test_openai_reranker_api_key_precedence(
monkeypatch, explicit_key, environment_key, expected_key
):
pytest.importorskip("openai")
if environment_key is None:
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
else:
monkeypatch.setenv("OPENAI_API_KEY", environment_key)
reranker = OpenaiReranker(api_key=explicit_key)
client = reranker._client
try:
assert client.api_key == expected_key
finally:
client.close()
def test_openai_reranker_requires_api_key(monkeypatch):
pytest.importorskip("openai")
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
with pytest.raises(ValueError, match="OPENAI_API_KEY not set"):
OpenaiReranker()._client