Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,11 @@ def __init__(
self,
*,
model: str | None = None,
aws_secret_key: str | None = None,
aws_access_key: str | None = None,
aws_secret_key: str | SecretString | None = None,
aws_access_key: str | SecretString | None = None,
aws_region: str | None = None,
aws_profile: str | None = None,
aws_session_token: str | None = None,
aws_session_token: str | SecretString | None = None,
base_url: str | None = None,
anthropic_client: AsyncAnthropicBedrock | None = None,
additional_beta_flags: list[str] | None = None,
Expand Down Expand Up @@ -118,11 +118,11 @@ def __init__(
self,
*,
model: str | None = None,
aws_secret_key: str | None = None,
aws_access_key: str | None = None,
aws_secret_key: str | SecretString | None = None,
aws_access_key: str | SecretString | None = None,
aws_region: str | None = None,
aws_profile: str | None = None,
aws_session_token: str | None = None,
aws_session_token: str | SecretString | None = None,
base_url: str | None = None,
anthropic_client: AsyncAnthropicBedrock | None = None,
additional_beta_flags: list[str] | None = None,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ class RawAnthropicClient(
def __init__(
self,
*,
api_key: str | None = None,
api_key: str | SecretString | None = None,
model: str | None = None,
base_url: str | None = None,
anthropic_client: AnthropicAsyncClient | None = None,
Expand Down Expand Up @@ -1634,7 +1634,7 @@ class AnthropicClient(
def __init__(
self,
*,
api_key: str | None = None,
api_key: str | SecretString | None = None,
model: str | None = None,
base_url: str | None = None,
anthropic_client: AnthropicAsyncClient | None = None,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def __init__(
*,
model: str | None = None,
resource: str | None = None,
api_key: str | None = None,
api_key: str | SecretString | None = None,
azure_ad_token_provider: AnthropicFoundryAzureADTokenProvider | None = None,
base_url: str | None = None,
anthropic_client: AsyncAnthropicFoundry | None = None,
Expand Down Expand Up @@ -123,7 +123,7 @@ def __init__(
*,
model: str | None = None,
resource: str | None = None,
api_key: str | None = None,
api_key: str | SecretString | None = None,
azure_ad_token_provider: AnthropicFoundryAzureADTokenProvider | None = None,
base_url: str | None = None,
anthropic_client: AsyncAnthropicFoundry | None = None,
Expand Down
17 changes: 12 additions & 5 deletions python/packages/anthropic/tests/test_anthropic_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
SupportsChatGetResponse,
tool,
)
from agent_framework._settings import load_settings
from agent_framework._settings import SecretString, load_settings
from agent_framework._tools import SHELL_TOOL_KIND_VALUE
from agent_framework.observability import ChatTelemetryLayer
from anthropic.types.beta import (
Expand Down Expand Up @@ -94,17 +94,20 @@ def test_anthropic_settings_init(anthropic_unit_test_env: dict[str, str]) -> Non
assert settings["chat_model"] == anthropic_unit_test_env["ANTHROPIC_CHAT_MODEL"]


def test_anthropic_settings_init_with_explicit_values() -> None:
@pytest.mark.parametrize("api_key", ["custom-api-key", SecretString("custom-api-key")], ids=["str", "secret"])
def test_anthropic_settings_init_with_explicit_values(api_key: str | SecretString) -> None:
"""Test AnthropicSettings initialization with explicit values."""
settings = load_settings(
AnthropicSettings,
env_prefix="ANTHROPIC_",
api_key="custom-api-key",
api_key=api_key,
chat_model="claude-3-opus-20240229",
)

assert settings["api_key"] is not None
assert isinstance(settings["api_key"], SecretString)
assert settings["api_key"].get_secret_value() == "custom-api-key"
assert "custom-api-key" not in str(settings["api_key"])
assert "custom-api-key" not in repr(settings)
assert settings["chat_model"] == "claude-3-opus-20240229"


Expand Down Expand Up @@ -153,16 +156,20 @@ def test_agent_accepts_anthropic_clients() -> None:
assert agent.client is client


@pytest.mark.parametrize("secret_type", [str, SecretString], ids=["str", "secret"])
def test_anthropic_client_init_auto_create_client(
anthropic_unit_test_env: dict[str, str],
secret_type: type[str] | type[SecretString],
) -> None:
"""Test AnthropicClient initialization with auto-created anthropic_client."""
client = AnthropicClient(
api_key=anthropic_unit_test_env["ANTHROPIC_API_KEY"],
api_key=secret_type(anthropic_unit_test_env["ANTHROPIC_API_KEY"]),
model=anthropic_unit_test_env["ANTHROPIC_CHAT_MODEL"],
)

assert client.anthropic_client is not None
assert type(client.anthropic_client.api_key) is str
assert client.anthropic_client.api_key == anthropic_unit_test_env["ANTHROPIC_API_KEY"]
assert client.model == anthropic_unit_test_env["ANTHROPIC_CHAT_MODEL"]


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import pytest
from agent_framework import Agent, ChatMiddlewareLayer, FunctionInvocationLayer
from agent_framework._settings import SecretString
from agent_framework._telemetry import get_user_agent
from agent_framework.observability import ChatTelemetryLayer

Expand Down Expand Up @@ -107,7 +108,10 @@ def test_agent_accepts_anthropic_vertex_clients() -> None:
assert agent.client is client


def test_raw_anthropic_foundry_client_creates_sdk_client_from_settings(tmp_path) -> None:
@pytest.mark.parametrize("api_key", [None, "test-key", SecretString("test-key")], ids=["env", "str", "secret"])
def test_raw_anthropic_foundry_client_creates_sdk_client_from_settings(
tmp_path, api_key: str | SecretString | None
) -> None:
env_file = tmp_path / ".env"
env_file.write_text(
"ANTHROPIC_CHAT_MODEL=claude-foundry-test\n"
Expand All @@ -119,10 +123,11 @@ def test_raw_anthropic_foundry_client_creates_sdk_client_from_settings(tmp_path)
with patch(
"agent_framework_anthropic._foundry_client.AsyncAnthropicFoundry", return_value=mock_transport
) as factory:
client = RawAnthropicFoundryClient(env_file_path=str(env_file))
client = RawAnthropicFoundryClient(api_key=api_key, env_file_path=str(env_file))

assert client.model == "claude-foundry-test"
assert client.anthropic_client is mock_transport
assert type(factory.call_args.kwargs["api_key"]) is str
factory.assert_called_once_with(
resource="test-resource",
api_key="test-key",
Expand Down Expand Up @@ -174,16 +179,20 @@ def test_raw_anthropic_foundry_client_requires_resource_or_base_url() -> None:
RawAnthropicFoundryClient()


def test_raw_anthropic_bedrock_client_creates_sdk_client_from_arguments() -> None:
@pytest.mark.parametrize("secret_type", [str, SecretString], ids=["str", "secret"])
def test_raw_anthropic_bedrock_client_creates_sdk_client_from_arguments(
secret_type: type[str] | type[SecretString],
) -> None:
mock_transport = _create_mock_transport("https://bedrock-runtime.us-east-1.amazonaws.com")

with patch(
"agent_framework_anthropic._bedrock_client.AsyncAnthropicBedrock", return_value=mock_transport
) as factory:
client = RawAnthropicBedrockClient(
model="claude-bedrock-test",
aws_access_key="access-key",
aws_secret_key="secret-key",
aws_access_key=secret_type("access-key"),
aws_secret_key=secret_type("secret-key"),
aws_session_token=secret_type("session-token"),
aws_region="us-east-1",
)

Expand All @@ -194,10 +203,12 @@ def test_raw_anthropic_bedrock_client_creates_sdk_client_from_arguments() -> Non
aws_access_key="access-key",
aws_region="us-east-1",
aws_profile=None,
aws_session_token=None,
aws_session_token="session-token",
base_url=None,
default_headers={"User-Agent": get_user_agent()},
)
for key in ("aws_access_key", "aws_secret_key", "aws_session_token"):
assert type(factory.call_args.kwargs[key]) is str


def test_raw_anthropic_vertex_client_creates_sdk_client_from_arguments() -> None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ def __init__(
source_id: str = DEFAULT_SOURCE_ID,
endpoint: str | None = None,
index_name: str | None = None,
api_key: str | AzureKeyCredential | None = None,
api_key: str | SecretString | AzureKeyCredential | None = None,
credential: AzureCredentialTypes | None = None,
*,
mode: Literal["semantic"] = "semantic",
Expand All @@ -201,7 +201,7 @@ def __init__(
model: str | None = None,
knowledge_base_name: None = None,
retrieval_instructions: str | None = None,
azure_openai_api_key: str | None = None,
azure_openai_api_key: str | SecretString | None = None,
knowledge_base_output_mode: KnowledgeBaseOutputModeLiteral = "extractive_data",
retrieval_reasoning_effort: RetrievalReasoningEffortLiteral = "minimal",
query_source_credential: AzureCredentialTypes | None = None,
Expand Down Expand Up @@ -243,7 +243,7 @@ def __init__(
source_id: str = DEFAULT_SOURCE_ID,
endpoint: str | None = None,
index_name: str | None = None,
api_key: str | AzureKeyCredential | None = None,
api_key: str | SecretString | AzureKeyCredential | None = None,
credential: AzureCredentialTypes | None = None,
*,
mode: Literal["agentic"],
Expand All @@ -256,7 +256,7 @@ def __init__(
model: str,
knowledge_base_name: None = None,
retrieval_instructions: str | None = None,
azure_openai_api_key: str | None = None,
azure_openai_api_key: str | SecretString | None = None,
knowledge_base_output_mode: KnowledgeBaseOutputModeLiteral = "extractive_data",
retrieval_reasoning_effort: RetrievalReasoningEffortLiteral = "minimal",
query_source_credential: AzureCredentialTypes | None = None,
Expand Down Expand Up @@ -299,7 +299,7 @@ def __init__(
source_id: str = DEFAULT_SOURCE_ID,
endpoint: str | None = None,
index_name: None = None,
api_key: str | AzureKeyCredential | None = None,
api_key: str | SecretString | AzureKeyCredential | None = None,
credential: AzureCredentialTypes | None = None,
*,
mode: Literal["agentic"],
Expand All @@ -312,7 +312,7 @@ def __init__(
model: str | None = None,
knowledge_base_name: str,
retrieval_instructions: str | None = None,
azure_openai_api_key: str | None = None,
azure_openai_api_key: str | SecretString | None = None,
knowledge_base_output_mode: KnowledgeBaseOutputModeLiteral = "extractive_data",
retrieval_reasoning_effort: RetrievalReasoningEffortLiteral = "minimal",
query_source_credential: AzureCredentialTypes | None = None,
Expand Down Expand Up @@ -355,7 +355,7 @@ def __init__(
source_id: str = DEFAULT_SOURCE_ID,
endpoint: str | None = None,
index_name: None = None,
api_key: str | AzureKeyCredential | None = None,
api_key: str | SecretString | AzureKeyCredential | None = None,
credential: AzureCredentialTypes | None = None,
*,
mode: Literal["agentic"],
Expand All @@ -368,7 +368,7 @@ def __init__(
model: str | None = None,
knowledge_base_name: None = None,
retrieval_instructions: str | None = None,
azure_openai_api_key: str | None = None,
azure_openai_api_key: str | SecretString | None = None,
knowledge_base_output_mode: KnowledgeBaseOutputModeLiteral = "extractive_data",
retrieval_reasoning_effort: RetrievalReasoningEffortLiteral = "minimal",
query_source_credential: AzureCredentialTypes | None = None,
Expand Down Expand Up @@ -414,7 +414,7 @@ def __init__(
source_id: str = DEFAULT_SOURCE_ID,
endpoint: str | None = None,
index_name: str | None = None,
api_key: str | AzureKeyCredential | None = None,
api_key: str | SecretString | AzureKeyCredential | None = None,
credential: AzureCredentialTypes | None = None,
*,
mode: Literal["semantic", "agentic"] = "semantic",
Expand All @@ -427,7 +427,7 @@ def __init__(
model: str | None = None,
knowledge_base_name: str | None = None,
retrieval_instructions: str | None = None,
azure_openai_api_key: str | None = None,
azure_openai_api_key: str | SecretString | None = None,
knowledge_base_output_mode: KnowledgeBaseOutputModeLiteral = "extractive_data",
retrieval_reasoning_effort: RetrievalReasoningEffortLiteral = "minimal",
query_source_credential: AzureCredentialTypes | None = None,
Expand Down Expand Up @@ -499,7 +499,7 @@ def __init__(
endpoint=endpoint,
index_name=index_name,
knowledge_base_name=knowledge_base_name,
api_key=api_key if isinstance(api_key, str) else None,
api_key=api_key if isinstance(api_key, (str, SecretString)) else None,
env_file_path=env_file_path,
env_file_encoding=env_file_encoding,
)
Expand Down Expand Up @@ -866,7 +866,9 @@ async def _ensure_knowledge_base(self) -> None:
resource_url=self.azure_openai_resource_url,
deployment_name=self.azure_openai_model,
model_name=self.azure_openai_model,
api_key=self.azure_openai_api_key,
api_key=self.azure_openai_api_key.get_secret_value()
if isinstance(self.azure_openai_api_key, SecretString)
else self.azure_openai_api_key,
)

kb_kwargs: dict[str, Any] = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import pytest
from agent_framework import Content, Message
from agent_framework._sessions import AgentSession, SessionContext
from agent_framework._settings import SecretString
from agent_framework.exceptions import SettingNotFoundError
from azure.core.credentials import AzureKeyCredential
from azure.core.pipeline.transport import AioHttpTransport
Expand Down Expand Up @@ -205,6 +206,9 @@ def test_env_variable_fallback(self) -> None:
provider = AzureAISearchContextProvider(source_id="env-test")
assert provider.endpoint == "https://env.search.windows.net"
assert provider.index_name == "env-index"
assert isinstance(provider.credential, AzureKeyCredential)
assert type(provider.credential.key) is str
assert provider.credential.key == "env-key"

def test_top_k_and_semantic_config(self) -> None:
provider = _make_provider(top_k=10, semantic_configuration_name="my-config")
Expand Down Expand Up @@ -235,6 +239,18 @@ def test_model_explicit(self) -> None:
class TestInitCredentialResolution:
"""Tests for credential resolution paths."""

@pytest.mark.parametrize("api_key", ["test-key", SecretString("test-key")], ids=["str", "secret"])
def test_api_key_unwrapped(self, api_key: str | SecretString, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("AZURE_SEARCH_API_KEY", "env-key")
provider = AzureAISearchContextProvider(
endpoint="https://test.search.windows.net",
index_name="idx",
api_key=api_key,
)
assert isinstance(provider.credential, AzureKeyCredential)
assert type(provider.credential.key) is str
assert provider.credential.key == "test-key"

def test_token_credential_used(self) -> None:
mock_cred = AsyncMock()
provider = AzureAISearchContextProvider(
Expand Down Expand Up @@ -1273,10 +1289,11 @@ async def test_missing_index_name_raises(self) -> None:
with pytest.raises(ValueError, match="index_name is required"):
await provider._ensure_knowledge_base()

async def test_creates_knowledge_source_when_not_found(self) -> None:
@pytest.mark.parametrize("api_key", [None, "aoai-key", SecretString("aoai-key")], ids=["none", "str", "secret"])
async def test_creates_knowledge_source_when_not_found(self, api_key: str | SecretString | None) -> None:
from azure.core.exceptions import ResourceNotFoundError

provider = _make_provider()
provider = _make_provider(azure_openai_api_key=api_key)
provider._knowledge_base_initialized = False
provider._use_existing_knowledge_base = False
provider.knowledge_base_name = "test-kb"
Expand All @@ -1296,6 +1313,16 @@ async def test_creates_knowledge_source_when_not_found(self) -> None:

mock_index_client.create_knowledge_source.assert_awaited_once()
mock_index_client.create_or_update_knowledge_base.assert_awaited_once()
knowledge_base = mock_index_client.create_or_update_knowledge_base.call_args.args[0]
sdk_api_key = knowledge_base.models[0].azure_open_ai_parameters.api_key
if api_key is None:
assert sdk_api_key is None
else:
assert type(sdk_api_key) is str
assert sdk_api_key == "aoai-key"
if isinstance(api_key, SecretString):
assert provider.azure_openai_api_key is api_key
assert "aoai-key" not in repr(provider.azure_openai_api_key)
assert provider._knowledge_base_initialized is True

async def test_uses_existing_knowledge_source(self) -> None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ def __init__(
endpoint: str | None = None,
database_name: str | None = None,
container_name: str | None = None,
credential: str | AzureCredentialTypes | None = None,
credential: str | SecretString | AzureCredentialTypes | None = None,
cosmos_client: CosmosClient | None = None,
container_client: ContainerProxy | None = None,
env_file_path: str | None = None,
Expand Down Expand Up @@ -186,14 +186,16 @@ def __init__(
endpoint=endpoint,
database_name=database_name,
container_name=container_name,
key=credential if isinstance(credential, str) else None,
key=credential if isinstance(credential, (str, SecretString)) else None,
env_file_path=env_file_path,
env_file_encoding=env_file_encoding,
)
self.database_name = settings["database_name"] # type: ignore[assignment]
self.container_name = settings["container_name"] # type: ignore[assignment]

if self._cosmos_client is None:
if isinstance(credential, SecretString):
credential = credential.get_secret_value()
self._cosmos_client = CosmosClient(
url=settings["endpoint"], # type: ignore[arg-type]
credential=credential or settings["key"].get_secret_value(), # type: ignore[arg-type,union-attr]
Expand Down
Loading
Loading