Python: Replace Pydantic Settings with TypedDict + load_settings() (#3843)

* Replace Pydantic Settings with TypedDict + load_settings()

- Remove pydantic-settings dependency, add python-dotenv
- Delete _pydantic.py (AFBaseSettings, HTTPsUrl)
- Add _settings.py with generic load_settings() function, SecretString,
  type coercion, and Required field validation (SettingNotFoundError)
- Convert all 13 settings classes from AFBaseSettings subclasses to
  TypedDict definitions with load_settings() calls
- Update all consumers from attribute access to dict access
- Add 20 unit tests for load_settings() covering basic loading, dotenv,
  SecretString, type coercion, and required field validation
- Update all existing tests for new settings patterns

* Fix mypy type errors from settings conversion

- Fix str | None attribute access in responses_client (walrus operator)
- Fix SecretString | None narrowing in bedrock (type: ignore after guard)
- Convert _context_provider.py attribute access to dict access (missed file)
- Fix endpoint type narrowing in search_provider and context_provider
- Fix purview: str | None .rstrip(), int | None defaults, urlparse bytes

* Address PR review: required_fields param, type validation, fixes

- Move required field validation from TypedDict annotations (Required)
  to a required_fields parameter on load_settings(), enabling runtime
  decisions about which fields are required
- Remove Required imports and restore from __future__ import annotations
  in ollama and foundry_local
- Add _check_override_type() for deterministic ServiceInitializationError
  on invalid override types (e.g. dict passed for str field)
- Fix all multi-exception test catches back to single exception type
- Fix Ollama host=None: use .get() so None is passed through to SDK default
- Fix Purview processor: use explicit is-None checks instead of or operator
- Remove unused BaseModel import from openai/_shared.py
- Add 4 new tests (24 total): required_fields param, type validation

* Fix type validation: allow int for float fields

_check_override_type now permits int values for float-typed fields,
matching Python's standard numeric promotion behavior.

* fix: wrap urlparse arg with str() to fix mypy bytes endswith error
This commit is contained in:
Eduard van Valkenburg
2026-02-12 09:51:20 +01:00
committed by GitHub
Unverified
parent b488158abe
commit 8457533c69
58 changed files with 1526 additions and 1113 deletions
@@ -4,7 +4,7 @@ from __future__ import annotations
import sys
from collections.abc import Sequence
from typing import Any, ClassVar, Generic
from typing import Any, Generic
from agent_framework import (
ChatAndFunctionMiddlewareTypes,
@@ -13,7 +13,7 @@ from agent_framework import (
FunctionInvocationConfiguration,
FunctionInvocationLayer,
)
from agent_framework._pydantic import AFBaseSettings
from agent_framework._settings import load_settings
from agent_framework.exceptions import ServiceInitializationError
from agent_framework.observability import ChatTelemetryLayer
from agent_framework.openai._chat_client import RawOpenAIChatClient
@@ -115,25 +115,19 @@ FoundryLocalChatOptionsT = TypeVar(
# endregion
class FoundryLocalSettings(AFBaseSettings):
class FoundryLocalSettings(TypedDict, total=False):
"""Foundry local model settings.
The settings are first loaded from environment variables with the prefix 'FOUNDRY_LOCAL_'.
If the environment variables are not found, the settings can be loaded from a .env file
with the encoding 'utf-8'. If the settings are not found in the .env file, the settings
are ignored; however, validation will fail alerting that the settings are missing.
with the encoding 'utf-8'.
Attributes:
Keys:
model_id: The name of the model deployment to use.
(Env var FOUNDRY_LOCAL_MODEL_ID)
Parameters:
env_file_path: If provided, the .env settings are read from this file path location.
env_file_encoding: The encoding of the .env file, defaults to 'utf-8'.
"""
env_prefix: ClassVar[str] = "FOUNDRY_LOCAL_"
model_id: str
model_id: str | None
class FoundryLocalClient(
@@ -247,21 +241,27 @@ class FoundryLocalClient(
type that is not supported by the model, it will not be found.
"""
settings = FoundryLocalSettings(
model_id=model_id, # type: ignore
settings = load_settings(
FoundryLocalSettings,
env_prefix="FOUNDRY_LOCAL_",
required_fields=["model_id"],
model_id=model_id,
env_file_path=env_file_path,
env_file_encoding=env_file_encoding,
)
manager = FoundryLocalManager(bootstrap=bootstrap, timeout=timeout)
model_info = manager.get_model_info(
alias_or_model_id=settings.model_id,
alias_or_model_id=settings["model_id"],
device=device,
)
if model_info is None:
message = (
f"Model with ID or alias '{settings.model_id}:{device.value}' not found in Foundry Local."
f"Model with ID or alias '{settings['model_id']}:{device.value}' not found in Foundry Local."
if device
else f"Model with ID or alias '{settings.model_id}' for your current device not found in Foundry Local."
else (
f"Model with ID or alias '{settings['model_id']}' for your current device "
"not found in Foundry Local."
)
)
raise ServiceInitializationError(message)
if prepare_model:
@@ -4,8 +4,8 @@ from unittest.mock import MagicMock, patch
import pytest
from agent_framework import SupportsChatGetResponse
from agent_framework.exceptions import ServiceInitializationError
from pydantic import ValidationError
from agent_framework._settings import load_settings
from agent_framework.exceptions import ServiceInitializationError, SettingNotFoundError
from agent_framework_foundry_local import FoundryLocalClient
from agent_framework_foundry_local._foundry_local_client import FoundryLocalSettings
@@ -15,31 +15,43 @@ from agent_framework_foundry_local._foundry_local_client import FoundryLocalSett
def test_foundry_local_settings_init_from_env(foundry_local_unit_test_env: dict[str, str]) -> None:
"""Test FoundryLocalSettings initialization from environment variables."""
settings = FoundryLocalSettings(env_file_path="test.env")
settings = load_settings(FoundryLocalSettings, env_prefix="FOUNDRY_LOCAL_", env_file_path="test.env")
assert settings.model_id == foundry_local_unit_test_env["FOUNDRY_LOCAL_MODEL_ID"]
assert settings["model_id"] == foundry_local_unit_test_env["FOUNDRY_LOCAL_MODEL_ID"]
def test_foundry_local_settings_init_with_explicit_values() -> None:
"""Test FoundryLocalSettings initialization with explicit values."""
settings = FoundryLocalSettings(model_id="custom-model-id", env_file_path="test.env")
settings = load_settings(
FoundryLocalSettings,
env_prefix="FOUNDRY_LOCAL_",
model_id="custom-model-id",
env_file_path="test.env",
)
assert settings.model_id == "custom-model-id"
assert settings["model_id"] == "custom-model-id"
@pytest.mark.parametrize("exclude_list", [["FOUNDRY_LOCAL_MODEL_ID"]], indirect=True)
def test_foundry_local_settings_missing_model_id(foundry_local_unit_test_env: dict[str, str]) -> None:
"""Test FoundryLocalSettings when model_id is missing raises ValidationError."""
with pytest.raises(ValidationError):
FoundryLocalSettings(env_file_path="test.env")
"""Test FoundryLocalSettings when model_id is missing raises error."""
with pytest.raises(SettingNotFoundError, match="Required setting 'model_id'"):
load_settings(
FoundryLocalSettings,
env_prefix="FOUNDRY_LOCAL_",
required_fields=["model_id"],
env_file_path="test.env",
)
def test_foundry_local_settings_explicit_overrides_env(foundry_local_unit_test_env: dict[str, str]) -> None:
"""Test that explicit values override environment variables."""
settings = FoundryLocalSettings(model_id="override-model-id", env_file_path="test.env")
settings = load_settings(
FoundryLocalSettings, env_prefix="FOUNDRY_LOCAL_", model_id="override-model-id", env_file_path="test.env"
)
assert settings.model_id == "override-model-id"
assert settings.model_id != foundry_local_unit_test_env["FOUNDRY_LOCAL_MODEL_ID"]
assert settings["model_id"] == "override-model-id"
assert settings["model_id"] != foundry_local_unit_test_env["FOUNDRY_LOCAL_MODEL_ID"]
# Client Initialization Tests