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 08:51:20 +00:00
committed by GitHub
parent b488158abe
commit 8457533c69
58 changed files with 1526 additions and 1113 deletions
@@ -30,9 +30,8 @@ from agent_framework import (
UsageDetails,
get_logger,
)
from agent_framework._pydantic import AFBaseSettings
from agent_framework._settings import load_settings
from agent_framework.exceptions import (
ServiceInitializationError,
ServiceInvalidRequestError,
ServiceResponseException,
)
@@ -42,7 +41,7 @@ from ollama import AsyncClient
# Rename imported types to avoid naming conflicts with Agent Framework types
from ollama._types import ChatResponse as OllamaChatResponse
from ollama._types import Message as OllamaMessage
from pydantic import BaseModel, ValidationError
from pydantic import BaseModel
if sys.version_info >= (3, 13):
from typing import TypeVar # type: ignore # pragma: no cover
@@ -275,13 +274,11 @@ OllamaChatOptionsT = TypeVar("OllamaChatOptionsT", bound=TypedDict, default="Oll
# endregion
class OllamaSettings(AFBaseSettings):
class OllamaSettings(TypedDict, total=False):
"""Ollama settings."""
env_prefix: ClassVar[str] = "OLLAMA_"
host: str | None = None
model_id: str | None = None
host: str | None
model_id: str | None
logger = get_logger("agent_framework.ollama")
@@ -322,23 +319,19 @@ class OllamaChatClient(
env_file_encoding: The encoding to use when reading the dotenv (.env) file. Defaults to 'utf-8'.
**kwargs: Additional keyword arguments passed to BaseChatClient.
"""
try:
ollama_settings = OllamaSettings(
host=host,
model_id=model_id,
env_file_encoding=env_file_encoding,
env_file_path=env_file_path,
)
except ValidationError as ex:
raise ServiceInitializationError("Failed to create Ollama settings.", ex) from ex
ollama_settings = load_settings(
OllamaSettings,
env_prefix="OLLAMA_",
required_fields=["model_id"],
host=host,
model_id=model_id,
env_file_encoding=env_file_encoding,
env_file_path=env_file_path,
)
if ollama_settings.model_id is None:
raise ServiceInitializationError(
"Ollama chat model ID must be provided via model_id or OLLAMA_MODEL_ID environment variable."
)
self.model_id = ollama_settings.model_id
self.client = client or AsyncClient(host=ollama_settings.host)
self.model_id = ollama_settings["model_id"]
# we can just pass in None for the host, the default is set by the Ollama package.
self.client = client or AsyncClient(host=ollama_settings.get("host"))
# Save Host URL for serialization with to_dict()
self.host = str(self.client._client.base_url) # pyright: ignore[reportUnknownMemberType,reportPrivateUsage,reportUnknownArgumentType]
@@ -15,9 +15,9 @@ from agent_framework import (
tool,
)
from agent_framework.exceptions import (
ServiceInitializationError,
ServiceInvalidRequestError,
ServiceResponseException,
SettingNotFoundError,
)
from ollama import AsyncClient
from ollama._types import ChatResponse as OllamaChatResponse
@@ -182,7 +182,7 @@ def test_init_client(ollama_unit_test_env: dict[str, str]) -> None:
@pytest.mark.parametrize("exclude_list", [["OLLAMA_MODEL_ID"]], indirect=True)
def test_with_invalid_settings(ollama_unit_test_env: dict[str, str]) -> None:
with pytest.raises(ServiceInitializationError):
with pytest.raises(SettingNotFoundError, match="Required setting 'model_id'"):
OllamaChatClient(
host="http://localhost:12345",
model_id=None,