Skip to content

Commit 5254e80

Browse files
committed
fix: preserve workflow environment loading with lazy agent factory
1 parent ab430be commit 5254e80

3 files changed

Lines changed: 34 additions & 8 deletions

File tree

‎python/packages/declarative/README.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,11 @@ This package ships at two different stability levels:
2525
`WorkflowFactory` creates its default `AgentFactory` lazily when loading an
2626
agent definition from the workflow's `agents` section, including references to
2727
agent YAML files. That path uses the experimental declarative-agent APIs and
28-
emits the corresponding warning. The `env_file` passed to `WorkflowFactory` is
29-
loaded at that point.
28+
emits the corresponding warning. When no custom `agent_factory` is supplied,
29+
`WorkflowFactory` loads `env_file` during initialization, independently of agent
30+
creation. Workflow expressions such as `=Env.NAME` can read those variables when
31+
`restrict_env_to_configuration=False`; explicit `configuration` values still
32+
take precedence.
3033

3134
Workflows containing only workflow actions use the stable workflow APIs. To use
3235
agents through that surface, create them with the appropriate client and pass

‎python/packages/declarative/agent_framework_declarative/_workflows/_factory.py‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
Workflow,
2626
)
2727
from agent_framework._telemetry import mark_feature_used
28+
from dotenv import load_dotenv
2829

2930
from .._feature_usage import FeatureIndex
3031
from .._loader import AgentFactory
@@ -107,8 +108,9 @@ def __init__(
107108
agents: Optional pre-created agents by name. These are looked up when processing
108109
InvokeAzureAgent actions in the workflow YAML.
109110
bindings: Optional function bindings for tool calls within workflow actions.
110-
env_file: Optional path to .env file for environment variables used in agent creation.
111-
Loaded when the default agent factory is first needed.
111+
env_file: Optional path to .env file for environment variables used in agent creation
112+
and workflow expressions. Loaded during initialization when no agent_factory is supplied.
113+
Workflow expressions require restrict_env_to_configuration=False to read these variables.
112114
checkpoint_storage: Optional checkpoint storage enabling pause/resume functionality.
113115
max_iterations: Optional maximum runner supersteps. Overrides the YAML ``maxTurns``
114116
field and the core default (100). Workflows with ``GotoAction`` loops (e.g.
@@ -190,6 +192,8 @@ def __init__(
190192
"""
191193
self._agent_factory = agent_factory
192194
self._env_file = env_file
195+
if agent_factory is None:
196+
load_dotenv(dotenv_path=env_file, encoding=None)
193197
self._agents: dict[str, SupportsAgentRun | AgentExecutor] = dict(agents) if agents else {}
194198
self._bindings: dict[str, Any] = dict(bindings) if bindings else {}
195199
self._tools: dict[str, Any] = {} # Tool registry for InvokeFunctionTool actions

‎python/packages/declarative/tests/test_workflow_factory.py‎

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1337,23 +1337,41 @@ class TestWorkflowFactoryAgentCreation:
13371337

13381338
@pytest.mark.usefixtures("fresh_feature_warnings")
13391339
@pytest.mark.parametrize("registration", ["none", "constructor", "register_agent"])
1340-
async def test_workflow_without_agent_loading_emits_no_experimental_warning(self, registration: str) -> None:
1340+
@pytest.mark.parametrize("use_env_file", [False, pytest.param(True, marks=_requires_powerfx)])
1341+
async def test_workflow_without_agent_loading_emits_no_experimental_warning(
1342+
self, registration: str, use_env_file: bool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
1343+
) -> None:
1344+
env_file = None
1345+
if use_env_file:
1346+
monkeypatch.setenv("DECLARATIVE_TEST_ENV", "original")
1347+
monkeypatch.delenv("DECLARATIVE_TEST_ENV")
1348+
env_file = tmp_path / ".env"
1349+
env_file.write_text("DECLARATIVE_TEST_ENV=loaded\n")
13411350
agent = MagicMock()
13421351
with warnings.catch_warnings():
13431352
warnings.simplefilter("error", ExperimentalWarning)
1344-
factory = WorkflowFactory(agents={"TestAgent": agent} if registration == "constructor" else None)
1353+
factory = WorkflowFactory(
1354+
agents={"TestAgent": agent} if registration == "constructor" else None,
1355+
env_file=str(env_file) if env_file else None,
1356+
restrict_env_to_configuration=False,
1357+
)
13451358
if registration == "register_agent":
13461359
factory.register_agent("TestAgent", agent)
13471360
definition: dict[str, Any] = {
13481361
"name": "hello-workflow",
1349-
"actions": [{"kind": "SendActivity", "activity": {"text": "Hello"}}],
1362+
"actions": [
1363+
{
1364+
"kind": "SendActivity",
1365+
"activity": {"text": "=Env.DECLARATIVE_TEST_ENV" if use_env_file else "Hello"},
1366+
}
1367+
],
13501368
}
13511369
if registration != "none":
13521370
definition["agents"] = {"TestAgent": {"kind": "Prompt", "name": "OverrideAttempt"}}
13531371
workflow = factory.create_workflow_from_yaml(yaml.safe_dump(definition))
13541372
result = await workflow.run({})
13551373

1356-
assert any("Hello" in str(output) for output in result.get_outputs())
1374+
assert result.get_outputs() == ["loaded" if use_env_file else "Hello"]
13571375
if registration != "none":
13581376
assert cast(Any, workflow)._declarative_agents["TestAgent"] is agent
13591377

@@ -1378,6 +1396,7 @@ def test_agent_loading_warns_and_reuses_factory(
13781396
with warnings.catch_warnings():
13791397
warnings.simplefilter("error", ExperimentalWarning)
13801398
factory = WorkflowFactory(env_file=str(env_file))
1399+
assert os.environ["DECLARATIVE_TEST_ENV"] == "loaded"
13811400

13821401
with patch.object(AgentFactory, "_get_client", return_value=MagicMock()):
13831402
with pytest.warns(ExperimentalWarning, match=r"\[DECLARATIVE_AGENTS\] AgentFactory"):

0 commit comments

Comments
 (0)