Skip to content

Comments

Python: Add load_dotenv() to samples for .env file support#4043

Merged
eavanvalkenburg merged 33 commits intomainfrom
copilot/fix-env-variable-loading
Feb 19, 2026
Merged

Python: Add load_dotenv() to samples for .env file support#4043
eavanvalkenburg merged 33 commits intomainfrom
copilot/fix-env-variable-loading

Conversation

Copy link
Contributor

Copilot AI commented Feb 18, 2026

Motivation and Context

Samples failed with missing API key errors even when credentials were present in .env files. The python-dotenv package is already a dependency but samples weren't calling load_dotenv().

Description

Added environment variable loading to 292 Python sample files that require API keys, endpoints, or other configuration:

  • Sample code changes: Added from dotenv import load_dotenv and load_dotenv() call to 292 sample files following SAMPLE_GUIDELINES.md ordering:
    • Before module docstrings (per SAMPLE_GUIDELINES.md lines 11-13: imports, then load_dotenv(), then docstring)
    • Before code-specific comments to keep comments adjacent to the code they describe
    • Outside XML snippet tags used for documentation extraction
    • Module-level placement in all samples (never inside if __name__ == "__main__" blocks)
    • Uses string literals for role values ("user", "assistant") consistent with current API where Role is NewType("Role", str) not an enum
  • Documentation:
    • Updated SAMPLE_GUIDELINES.md ordering guidance (lines 11-13) and example code (lines 53-70) to be consistent - both show load_dotenv() before module docstring
    • Updated samples/README.md with comprehensive environment variable setup instructions:
      • Clarified that load_dotenv() is for local development convenience
      • Added guidance that production environments should use platform-native environment variable management (Azure App Settings, Kubernetes ConfigMaps/Secrets, etc.)
      • Documented three options for environment variable configuration: global .env file with load_dotenv(), direct shell exports, and per-client env_file_path parameter
    • Updated python/packages/redis/README.md to reference renamed sample file
  • Code formatting: Ran ruff format on all changed files (102 files reformatted with proper spacing and quote style)
  • Cleanup and refactoring:
    • Removed deprecated getting_started/sessions/ folder (17 files) as it contained outdated samples
    • Renamed conversation samples for clarity: redis_chat_message_store_session.pyredis_history_provider.py, custom_chat_message_store_session.pycustom_history_provider.py
    • Enhanced redis_conversation.py to use sessions and document both RedisContextProvider and RedisHistoryProvider
    • Removed obsolete NOTE comment from checkpoint_with_human_in_the_loop.py
  • Merge with main: Successfully merged latest main branch, incorporating bug fixes from recent PRs for 19 sample files while preserving load_dotenv() additions. All merge conflicts resolved.

Correct pattern applied (per SAMPLE_GUIDELINES.md):

# Copyright (c) Microsoft. All rights reserved.

from agent_framework.openai import OpenAIChatClient
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

"""
Sample docstring explaining what the sample does.
"""

# Code-specific comments stay with their code
SOME_CODE = ...

Key principles:

  • load_dotenv() call appears before module docstrings (per SAMPLE_GUIDELINES.md ordering)
  • Code-specific comments appear after load_dotenv() call and stay adjacent to their code
  • load_dotenv() is always placed at module-level, never inside if __name__ == "__main__" blocks
  • Snippet tags exclude environment setup code
  • Role values use string literals (e.g., "user", "assistant") as Role is a NewType alias, not an enum

Alternative configuration methods:

  • Per-client .env files using env_file_path parameter:
    client = OpenAIChatClient(env_file_path="path/to/custom.env")
  • Direct shell environment variable exports

Handles multi-line imports correctly. Samples without environment variable usage unchanged.

Note: The load_dotenv() call has no effect when a .env file is not present, making it safe for production deployments where environment variables are set through the platform.

Contribution Checklist

  • The code builds clean without any errors or warnings
  • The PR follows the Contribution Guidelines
  • All unit tests pass, and I have added new tests where possible
  • Is this a breaking change? If yes, add "[BREAKING]" prefix to the title of the PR.
Original prompt

This section details on the original issue you should resolve

<issue_title>Python: [Bug]: Samples do not load environment variables correctly</issue_title>
<issue_description>### Description

The samples no longer load environment variables correctly from a .env file in the project.
For example, running python .\samples\02-agents\providers\openai\openai_chat_client_basic.py gives agent_framework.exceptions.ServiceInitializationError: OpenAI API key is required. Set via 'api_key' parameter or 'OPENAI_API_KEY' environment variable. even if the key is already in a .env file under the root agent_framework/python.

Code Sample

Error Messages / Stack Traces

agent_framework.exceptions.ServiceInitializationError: OpenAI API key is required. Set via 'api_key' parameter or 'OPENAI_API_KEY' environment variable.

Package Versions

agent_framework

Python Version

No response

Additional Context

All samples should correctly load environment variables from a .env file if present, by running load_dotenv.</issue_description>

Comments on the Issue (you are @copilot in this section)


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

Copilot AI and others added 3 commits February 18, 2026 18:28
Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com>
Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com>
Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com>
Copilot AI force-pushed the copilot/fix-env-variable-loading branch from abed4ea to cd1b8ae Compare February 18, 2026 18:32
Copilot AI changed the title [WIP] Fix samples not loading environment variables correctly Python: Add load_dotenv() to samples for .env file support Feb 18, 2026
Copilot AI requested a review from TaoChenOSU February 18, 2026 18:33
@TaoChenOSU
Copy link
Contributor

@copilot run formatting on all changed files

Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com>
Copy link
Contributor Author

Copilot AI commented Feb 18, 2026

@copilot run formatting on all changed files

Done. Ran ruff format on all changed files. 102 files were reformatted with proper spacing and docstring quote style corrections. Changes committed in 17b5890.

@markwallace-microsoft markwallace-microsoft added documentation Improvements or additions to documentation python labels Feb 18, 2026
Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com>
Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com>
Co-authored-by: TaoChenOSU <12570346+TaoChenOSU@users.noreply.github.com>
@TaoChenOSU
Copy link
Contributor

@copilot There is a conflict with main. Fix it

eavanvalkenburg and others added 2 commits February 19, 2026 10:13
…uidance

Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
Copy link
Member

@eavanvalkenburg eavanvalkenburg left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot just looking at the first few samples, it is not consistently following the sample guidelines, make sure that the load_dotenv() call is in the right place in all samples!

…INES ordering

Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
Copy link
Contributor Author

Copilot AI commented Feb 19, 2026

@copilot just looking at the first few samples, it is not consistently following the sample guidelines, make sure that the load_dotenv() call is in the right place in all samples!

Fixed in d9513cc. Moved load_dotenv() to before module docstrings in all 193 affected samples to match SAMPLE_GUIDELINES.md ordering (imports → load_dotenv() → docstring).

@eavanvalkenburg
Copy link
Member

@copilot just reviewed again, left a couple of comments, please address

…move note

Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
Copy link
Contributor Author

Copilot AI commented Feb 19, 2026

@copilot just reviewed again, left a couple of comments, please address

All comments addressed in c49ce53:

  • Renamed two conversation sample files
  • Fixed load_dotenv() placement in 3 files
  • Added session usage to redis_conversation.py with provider documentation
  • Removed obsolete NOTE comment

@eavanvalkenburg
Copy link
Member

@copilot when you renamed some sample in one of the last commits, you forgot to update the README that refers to it, please do that now

Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
Copy link
Contributor Author

Copilot AI commented Feb 19, 2026

@copilot when you renamed some sample in one of the last commits, you forgot to update the README that refers to it, please do that now

Updated python/packages/redis/README.md to reference the renamed file redis_history_provider.py. Changes in cc12c5b.

@eavanvalkenburg eavanvalkenburg added this pull request to the merge queue Feb 19, 2026
Merged via the queue into main with commit b05fc9e Feb 19, 2026
26 checks passed
@crickman crickman deleted the copilot/fix-env-variable-loading branch February 19, 2026 17:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation python workflows Related to Workflows in agent-framework

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Python: [Bug]: Samples do not load environment variables correctly

5 participants