mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
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:
committed by
GitHub
Unverified
parent
b488158abe
commit
8457533c69
@@ -21,9 +21,10 @@ from agent_framework import (
|
||||
ResponseStream,
|
||||
normalize_messages,
|
||||
)
|
||||
from agent_framework._settings import load_settings
|
||||
from agent_framework._tools import FunctionTool
|
||||
from agent_framework._types import normalize_tools
|
||||
from agent_framework.exceptions import ServiceException, ServiceInitializationError
|
||||
from agent_framework.exceptions import ServiceException
|
||||
from copilot import CopilotClient, CopilotSession
|
||||
from copilot.generated.session_events import SessionEvent, SessionEventType
|
||||
from copilot.types import (
|
||||
@@ -38,7 +39,6 @@ from copilot.types import (
|
||||
ToolResult,
|
||||
)
|
||||
from copilot.types import Tool as CopilotTool
|
||||
from pydantic import ValidationError
|
||||
|
||||
from ._settings import GitHubCopilotSettings
|
||||
|
||||
@@ -207,17 +207,16 @@ class GitHubCopilotAgent(BaseAgent, Generic[OptionsT]):
|
||||
on_permission_request: PermissionHandlerType | None = opts.pop("on_permission_request", None)
|
||||
mcp_servers: dict[str, MCPServerConfig] | None = opts.pop("mcp_servers", None)
|
||||
|
||||
try:
|
||||
self._settings = GitHubCopilotSettings(
|
||||
cli_path=cli_path,
|
||||
model=model,
|
||||
timeout=timeout,
|
||||
log_level=log_level,
|
||||
env_file_path=env_file_path,
|
||||
env_file_encoding=env_file_encoding,
|
||||
)
|
||||
except ValidationError as ex:
|
||||
raise ServiceInitializationError("Failed to create GitHub Copilot settings.", ex) from ex
|
||||
self._settings = load_settings(
|
||||
GitHubCopilotSettings,
|
||||
env_prefix="GITHUB_COPILOT_",
|
||||
cli_path=cli_path,
|
||||
model=model,
|
||||
timeout=timeout,
|
||||
log_level=log_level,
|
||||
env_file_path=env_file_path,
|
||||
env_file_encoding=env_file_encoding,
|
||||
)
|
||||
|
||||
self._tools = normalize_tools(tools)
|
||||
self._permission_handler = on_permission_request
|
||||
@@ -249,10 +248,10 @@ class GitHubCopilotAgent(BaseAgent, Generic[OptionsT]):
|
||||
|
||||
if self._client is None:
|
||||
client_options: CopilotClientOptions = {}
|
||||
if self._settings.cli_path:
|
||||
client_options["cli_path"] = self._settings.cli_path
|
||||
if self._settings.log_level:
|
||||
client_options["log_level"] = self._settings.log_level # type: ignore[typeddict-item]
|
||||
if self._settings["cli_path"]:
|
||||
client_options["cli_path"] = self._settings["cli_path"]
|
||||
if self._settings["log_level"]:
|
||||
client_options["log_level"] = self._settings["log_level"] # type: ignore[typeddict-item]
|
||||
|
||||
self._client = CopilotClient(client_options if client_options else None)
|
||||
|
||||
@@ -355,7 +354,7 @@ class GitHubCopilotAgent(BaseAgent, Generic[OptionsT]):
|
||||
thread = self.get_new_thread()
|
||||
|
||||
opts: dict[str, Any] = dict(options) if options else {}
|
||||
timeout = opts.pop("timeout", None) or self._settings.timeout or DEFAULT_TIMEOUT_SECONDS
|
||||
timeout = opts.pop("timeout", None) or self._settings["timeout"] or DEFAULT_TIMEOUT_SECONDS
|
||||
|
||||
session = await self._get_or_create_session(thread, streaming=False, runtime_options=opts)
|
||||
input_messages = normalize_messages(messages)
|
||||
@@ -578,7 +577,7 @@ class GitHubCopilotAgent(BaseAgent, Generic[OptionsT]):
|
||||
opts = runtime_options or {}
|
||||
config: SessionConfig = {"streaming": streaming}
|
||||
|
||||
model = opts.get("model") or self._settings.model
|
||||
model = opts.get("model") or self._settings["model"]
|
||||
if model:
|
||||
config["model"] = model # type: ignore[typeddict-item]
|
||||
|
||||
|
||||
@@ -1,19 +1,16 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
from typing import ClassVar
|
||||
|
||||
from agent_framework._pydantic import AFBaseSettings
|
||||
from typing import TypedDict
|
||||
|
||||
|
||||
class GitHubCopilotSettings(AFBaseSettings):
|
||||
class GitHubCopilotSettings(TypedDict, total=False):
|
||||
"""GitHub Copilot model settings.
|
||||
|
||||
The settings are first loaded from environment variables with the prefix 'GITHUB_COPILOT_'.
|
||||
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'.
|
||||
|
||||
Keyword Args:
|
||||
Keys:
|
||||
cli_path: Path to the Copilot CLI executable.
|
||||
Can be set via environment variable GITHUB_COPILOT_CLI_PATH.
|
||||
model: Model to use (e.g., "gpt-5", "claude-sonnet-4").
|
||||
@@ -22,28 +19,9 @@ class GitHubCopilotSettings(AFBaseSettings):
|
||||
Can be set via environment variable GITHUB_COPILOT_TIMEOUT.
|
||||
log_level: CLI log level.
|
||||
Can be set via environment variable GITHUB_COPILOT_LOG_LEVEL.
|
||||
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'.
|
||||
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
from agent_framework_github_copilot import GitHubCopilotSettings
|
||||
|
||||
# Using environment variables
|
||||
# Set GITHUB_COPILOT_MODEL=gpt-5
|
||||
settings = GitHubCopilotSettings()
|
||||
|
||||
# Or passing parameters directly
|
||||
settings = GitHubCopilotSettings(model="claude-sonnet-4", timeout=120)
|
||||
|
||||
# Or loading from a .env file
|
||||
settings = GitHubCopilotSettings(env_file_path="path/to/.env")
|
||||
"""
|
||||
|
||||
env_prefix: ClassVar[str] = "GITHUB_COPILOT_"
|
||||
|
||||
cli_path: str | None = None
|
||||
model: str | None = None
|
||||
timeout: float | None = None
|
||||
log_level: str | None = None
|
||||
cli_path: str | None
|
||||
model: str | None
|
||||
timeout: float | None
|
||||
log_level: str | None
|
||||
|
||||
@@ -122,8 +122,8 @@ class TestGitHubCopilotAgentInit:
|
||||
agent: GitHubCopilotAgent[GitHubCopilotOptions] = GitHubCopilotAgent(
|
||||
default_options={"model": "claude-sonnet-4", "timeout": 120}
|
||||
)
|
||||
assert agent._settings.model == "claude-sonnet-4" # type: ignore
|
||||
assert agent._settings.timeout == 120 # type: ignore
|
||||
assert agent._settings["model"] == "claude-sonnet-4" # type: ignore
|
||||
assert agent._settings["timeout"] == 120 # type: ignore
|
||||
|
||||
def test_init_with_tools(self) -> None:
|
||||
"""Test initialization with function tools."""
|
||||
|
||||
Reference in New Issue
Block a user