diff --git a/python/packages/redis/README.md b/python/packages/redis/README.md index 02ba6f7548..3517f460de 100644 --- a/python/packages/redis/README.md +++ b/python/packages/redis/README.md @@ -30,7 +30,7 @@ The `RedisChatMessageStore` provides persistent conversation storage using Redis #### Basic Usage Examples -See the complete [Redis history provider examples](../../samples/02-agents/conversations/redis_chat_message_store_session.py) including: +See the complete [Redis history provider examples](../../samples/02-agents/conversations/redis_history_provider.py) including: - User session management - Conversation persistence across restarts - Session serialization and deserialization diff --git a/python/samples/01-get-started/01_hello_agent.py b/python/samples/01-get-started/01_hello_agent.py index 45b0cf410a..167aa8065c 100644 --- a/python/samples/01-get-started/01_hello_agent.py +++ b/python/samples/01-get-started/01_hello_agent.py @@ -5,6 +5,10 @@ from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Hello Agent — Simplest possible agent diff --git a/python/samples/01-get-started/02_add_tools.py b/python/samples/01-get-started/02_add_tools.py index 04045de16c..06108bb388 100644 --- a/python/samples/01-get-started/02_add_tools.py +++ b/python/samples/01-get-started/02_add_tools.py @@ -8,8 +8,12 @@ from agent_framework import tool from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Add Tools — Give your agent a function tool diff --git a/python/samples/01-get-started/03_multi_turn.py b/python/samples/01-get-started/03_multi_turn.py index 266764c395..16a0f0060a 100644 --- a/python/samples/01-get-started/03_multi_turn.py +++ b/python/samples/01-get-started/03_multi_turn.py @@ -5,6 +5,10 @@ from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Multi-Turn Conversations — Use AgentSession to maintain context diff --git a/python/samples/01-get-started/04_memory.py b/python/samples/01-get-started/04_memory.py index 03ef75257c..a81c81a252 100644 --- a/python/samples/01-get-started/04_memory.py +++ b/python/samples/01-get-started/04_memory.py @@ -7,6 +7,10 @@ from agent_framework._sessions import AgentSession, BaseContextProvider, SessionContext from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Agent Memory with Context Providers diff --git a/python/samples/01-get-started/05_first_workflow.py b/python/samples/01-get-started/05_first_workflow.py index ffce2e97d8..89b4f608b2 100644 --- a/python/samples/01-get-started/05_first_workflow.py +++ b/python/samples/01-get-started/05_first_workflow.py @@ -44,11 +44,7 @@ async def reverse_text(text: str, ctx: WorkflowContext[Never, str]) -> None: def create_workflow(): """Build the workflow: UpperCase → reverse_text.""" upper = UpperCase(id="upper_case") - return ( - WorkflowBuilder(start_executor=upper) - .add_edge(upper, reverse_text) - .build() - ) + return WorkflowBuilder(start_executor=upper).add_edge(upper, reverse_text).build() # diff --git a/python/samples/01-get-started/06_host_your_agent.py b/python/samples/01-get-started/06_host_your_agent.py index 7f80607dde..d5577af1e8 100644 --- a/python/samples/01-get-started/06_host_your_agent.py +++ b/python/samples/01-get-started/06_host_your_agent.py @@ -1,5 +1,14 @@ # Copyright (c) Microsoft. All rights reserved. +from typing import Any + +from agent_framework.azure import AgentFunctionApp, AzureOpenAIChatClient +from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() + """Host your agent with Azure Functions. This sample shows the Python hosting pattern used in docs: @@ -15,11 +24,6 @@ AZURE_OPENAI_CHAT_DEPLOYMENT_NAME """ -from typing import Any - -from agent_framework.azure import AgentFunctionApp, AzureOpenAIChatClient -from azure.identity import AzureCliCredential - # def _create_agent() -> Any: @@ -28,8 +32,6 @@ def _create_agent() -> Any: name="HostedAgent", instructions="You are a helpful assistant hosted in Azure Functions.", ) - - # # diff --git a/python/samples/02-agents/background_responses.py b/python/samples/02-agents/background_responses.py index 9c04a59f27..777c348b0a 100644 --- a/python/samples/02-agents/background_responses.py +++ b/python/samples/02-agents/background_responses.py @@ -4,6 +4,10 @@ from agent_framework import Agent from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """Background Responses Sample. diff --git a/python/samples/02-agents/chat_client/built_in_chat_clients.py b/python/samples/02-agents/chat_client/built_in_chat_clients.py index 06be683781..8560afcf4f 100644 --- a/python/samples/02-agents/chat_client/built_in_chat_clients.py +++ b/python/samples/02-agents/chat_client/built_in_chat_clients.py @@ -13,8 +13,12 @@ from agent_framework.openai import OpenAIAssistantsClient from azure.identity import AzureCliCredential from azure.identity.aio import AzureCliCredential as AsyncAzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Built-in Chat Clients Example diff --git a/python/samples/02-agents/chat_client/chat_response_cancellation.py b/python/samples/02-agents/chat_client/chat_response_cancellation.py index 3435363512..db292786ce 100644 --- a/python/samples/02-agents/chat_client/chat_response_cancellation.py +++ b/python/samples/02-agents/chat_client/chat_response_cancellation.py @@ -3,6 +3,10 @@ import asyncio from agent_framework.openai import OpenAIChatClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Chat Response Cancellation Example diff --git a/python/samples/02-agents/context_providers/mem0/mem0_basic.py b/python/samples/02-agents/context_providers/mem0/mem0_basic.py index 773443f2be..e5bbf478cf 100644 --- a/python/samples/02-agents/context_providers/mem0/mem0_basic.py +++ b/python/samples/02-agents/context_providers/mem0/mem0_basic.py @@ -7,9 +7,15 @@ from agent_framework.azure import AzureAIAgentClient from agent_framework.mem0 import Mem0ContextProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv +# Load environment variables from .env file +load_dotenv() -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. + +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def retrieve_company_report(company_code: str, detailed: bool) -> str: if company_code != "CNTS": @@ -24,6 +30,7 @@ def retrieve_company_report(company_code: str, detailed: bool) -> str: async def main() -> None: """Example of memory usage with Mem0 context provider.""" + print("=== Mem0 Context Provider Example ===") # Each record in Mem0 should be associated with agent_id or user_id or application_id or thread_id. diff --git a/python/samples/02-agents/context_providers/mem0/mem0_oss.py b/python/samples/02-agents/context_providers/mem0/mem0_oss.py index 8bcedc5214..ca8e907da9 100644 --- a/python/samples/02-agents/context_providers/mem0/mem0_oss.py +++ b/python/samples/02-agents/context_providers/mem0/mem0_oss.py @@ -7,11 +7,15 @@ from agent_framework.azure import AzureAIAgentClient from agent_framework.mem0 import Mem0ContextProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv from mem0 import AsyncMemory +# Load environment variables from .env file +load_dotenv() -# NOTE: approval_mode="never_require" is for sample brevity. -# Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py + +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py # and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def retrieve_company_report(company_code: str, detailed: bool) -> str: @@ -27,6 +31,7 @@ def retrieve_company_report(company_code: str, detailed: bool) -> str: async def main() -> None: """Example of memory usage with local Mem0 OSS context provider.""" + print("=== Mem0 Context Provider Example ===") # Each record in Mem0 should be associated with agent_id or user_id or application_id or thread_id. diff --git a/python/samples/02-agents/context_providers/mem0/mem0_sessions.py b/python/samples/02-agents/context_providers/mem0/mem0_sessions.py index c2f1ddd69b..8bda4a575e 100644 --- a/python/samples/02-agents/context_providers/mem0/mem0_sessions.py +++ b/python/samples/02-agents/context_providers/mem0/mem0_sessions.py @@ -7,12 +7,19 @@ from agent_framework.azure import AzureAIAgentClient from agent_framework.mem0 import Mem0ContextProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv +# Load environment variables from .env file +load_dotenv() -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. + +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def get_user_preferences(user_id: str) -> str: """Mock function to get user preferences.""" + preferences = { "user123": "Prefers concise responses and technical details", "user456": "Likes detailed explanations with examples", diff --git a/python/samples/02-agents/context_providers/redis/azure_redis_conversation.py b/python/samples/02-agents/context_providers/redis/azure_redis_conversation.py index d5e3bd6f8e..6408fd4be4 100644 --- a/python/samples/02-agents/context_providers/redis/azure_redis_conversation.py +++ b/python/samples/02-agents/context_providers/redis/azure_redis_conversation.py @@ -25,8 +25,12 @@ from agent_framework.redis import RedisHistoryProvider from azure.identity import AzureCliCredential from azure.identity.aio import AzureCliCredential as AsyncAzureCliCredential +from dotenv import load_dotenv from redis.credentials import CredentialProvider +# Load environment variables from .env file +load_dotenv() + class AzureCredentialProvider(CredentialProvider): """Credential provider for Azure AD authentication with Redis Enterprise.""" diff --git a/python/samples/02-agents/context_providers/redis/redis_basics.py b/python/samples/02-agents/context_providers/redis/redis_basics.py index b2f9bb23c2..662ed5e971 100644 --- a/python/samples/02-agents/context_providers/redis/redis_basics.py +++ b/python/samples/02-agents/context_providers/redis/redis_basics.py @@ -34,9 +34,13 @@ from agent_framework.azure import AzureOpenAIResponsesClient from agent_framework.redis import RedisContextProvider from azure.identity import AzureCliCredential +from dotenv import load_dotenv from redisvl.extensions.cache.embeddings import EmbeddingsCache from redisvl.utils.vectorize import OpenAITextVectorizer +# Load environment variables from .env file +load_dotenv() + # Default Redis URL for local Redis Stack. # Override via the REDIS_URL environment variable for remote or authenticated instances. REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379") diff --git a/python/samples/02-agents/context_providers/redis/redis_conversation.py b/python/samples/02-agents/context_providers/redis/redis_conversation.py index 59168ca3c2..72192767e8 100644 --- a/python/samples/02-agents/context_providers/redis/redis_conversation.py +++ b/python/samples/02-agents/context_providers/redis/redis_conversation.py @@ -5,6 +5,10 @@ This example demonstrates how to use the Redis context provider to persist conversational details. Pass it as a constructor argument to create_agent. +Note: For session history persistence, see RedisHistoryProvider in the +conversations/redis_history_provider.py sample. RedisContextProvider is for +AI context (RAG, memories), while RedisHistoryProvider stores message history. + Requirements: - A Redis instance with RediSearch enabled (e.g., Redis Stack) - agent-framework with the Redis extra installed: pip install "agent-framework-redis" @@ -17,12 +21,17 @@ import asyncio import os +from agent_framework import AgentSession from agent_framework.azure import AzureOpenAIResponsesClient from agent_framework.redis import RedisContextProvider from azure.identity import AzureCliCredential +from dotenv import load_dotenv from redisvl.extensions.cache.embeddings import EmbeddingsCache from redisvl.utils.vectorize import OpenAITextVectorizer +# Load environment variables from .env file +load_dotenv() + # Default Redis URL for local Redis Stack. # Override via the REDIS_URL environment variable for remote or authenticated instances. REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379") @@ -73,35 +82,38 @@ async def main() -> None: context_providers=[provider], ) + # Create a session to manage conversation state + session = agent.create_session() + # Teach a user preference; the agent writes this to the provider's memory query = "Remember that I enjoy gumbo" - result = await agent.run(query) + result = await agent.run(query, session=session) print("User: ", query) print("Agent: ", result) # Ask the agent to recall the stored preference; it should retrieve from memory query = "What do I enjoy?" - result = await agent.run(query) + result = await agent.run(query, session=session) print("User: ", query) print("Agent: ", result) query = "What did I say to you just now?" - result = await agent.run(query) + result = await agent.run(query, session=session) print("User: ", query) print("Agent: ", result) query = "Remember that I have a meeting at 3pm tomorro" - result = await agent.run(query) + result = await agent.run(query, session=session) print("User: ", query) print("Agent: ", result) query = "Tulips are red" - result = await agent.run(query) + result = await agent.run(query, session=session) print("User: ", query) print("Agent: ", result) query = "What was the first thing I said to you this conversation?" - result = await agent.run(query) + result = await agent.run(query, session=session) print("User: ", query) print("Agent: ", result) # Drop / delete the provider index in Redis diff --git a/python/samples/02-agents/context_providers/redis/redis_sessions.py b/python/samples/02-agents/context_providers/redis/redis_sessions.py index f0be055e5e..48cf0e596b 100644 --- a/python/samples/02-agents/context_providers/redis/redis_sessions.py +++ b/python/samples/02-agents/context_providers/redis/redis_sessions.py @@ -32,17 +32,20 @@ from agent_framework.azure import AzureOpenAIResponsesClient from agent_framework.redis import RedisContextProvider from azure.identity import AzureCliCredential +from dotenv import load_dotenv from redisvl.extensions.cache.embeddings import EmbeddingsCache from redisvl.utils.vectorize import OpenAITextVectorizer +# Load environment variables from .env file +load_dotenv() + # Default Redis URL for local Redis Stack. # Override via the REDIS_URL environment variable for remote or authenticated instances. REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379") + # Please set OPENAI_API_KEY to use the OpenAI vectorizer. # For chat responses, also set AZURE_AI_PROJECT_ENDPOINT and AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME. - - def create_chat_client() -> AzureOpenAIResponsesClient: """Create an Azure OpenAI Responses client using a Foundry project endpoint.""" return AzureOpenAIResponsesClient( diff --git a/python/samples/02-agents/context_providers/simple_context_provider.py b/python/samples/02-agents/context_providers/simple_context_provider.py index cc9f3e460a..87bf1a5a16 100644 --- a/python/samples/02-agents/context_providers/simple_context_provider.py +++ b/python/samples/02-agents/context_providers/simple_context_provider.py @@ -8,8 +8,12 @@ from agent_framework import Agent, AgentSession, BaseContextProvider, SessionContext, SupportsChatGetResponse from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import BaseModel +# Load environment variables from .env file +load_dotenv() + class UserInfo(BaseModel): name: str | None = None diff --git a/python/samples/02-agents/conversations/custom_chat_message_store_session.py b/python/samples/02-agents/conversations/custom_history_provider.py similarity index 97% rename from python/samples/02-agents/conversations/custom_chat_message_store_session.py rename to python/samples/02-agents/conversations/custom_history_provider.py index e3ce5c5905..a8fc3974a0 100644 --- a/python/samples/02-agents/conversations/custom_chat_message_store_session.py +++ b/python/samples/02-agents/conversations/custom_history_provider.py @@ -6,6 +6,10 @@ from agent_framework import AgentSession, BaseHistoryProvider, Message from agent_framework.openai import OpenAIChatClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Custom History Provider Example diff --git a/python/samples/02-agents/conversations/redis_chat_message_store_session.py b/python/samples/02-agents/conversations/redis_history_provider.py similarity index 98% rename from python/samples/02-agents/conversations/redis_chat_message_store_session.py rename to python/samples/02-agents/conversations/redis_history_provider.py index 221ef158e2..10b5265c41 100644 --- a/python/samples/02-agents/conversations/redis_chat_message_store_session.py +++ b/python/samples/02-agents/conversations/redis_history_provider.py @@ -7,6 +7,10 @@ from agent_framework import AgentSession from agent_framework.openai import OpenAIChatClient from agent_framework.redis import RedisHistoryProvider +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Redis History Provider Session Example @@ -16,6 +20,7 @@ with Redis as the backend data store. """ + # Default Redis URL for local Redis Stack. # Override via the REDIS_URL environment variable for remote or authenticated instances. REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379") diff --git a/python/samples/02-agents/conversations/suspend_resume_session.py b/python/samples/02-agents/conversations/suspend_resume_session.py index dcbb00d06a..24c641d06a 100644 --- a/python/samples/02-agents/conversations/suspend_resume_session.py +++ b/python/samples/02-agents/conversations/suspend_resume_session.py @@ -6,6 +6,10 @@ from agent_framework.azure import AzureAIAgentClient from agent_framework.openai import OpenAIChatClient from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Session Suspend and Resume Example diff --git a/python/samples/02-agents/declarative/azure_openai_responses_agent.py b/python/samples/02-agents/declarative/azure_openai_responses_agent.py index edcf0f0805..cda02a4e90 100644 --- a/python/samples/02-agents/declarative/azure_openai_responses_agent.py +++ b/python/samples/02-agents/declarative/azure_openai_responses_agent.py @@ -4,6 +4,10 @@ from agent_framework.declarative import AgentFactory from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() async def main(): diff --git a/python/samples/02-agents/declarative/get_weather_agent.py b/python/samples/02-agents/declarative/get_weather_agent.py index 49995851fc..75d62bc1a9 100644 --- a/python/samples/02-agents/declarative/get_weather_agent.py +++ b/python/samples/02-agents/declarative/get_weather_agent.py @@ -9,11 +9,13 @@ from azure.identity import AzureCliCredential from dotenv import load_dotenv +# Load environment variables from .env file load_dotenv() def get_weather(location: str, unit: Literal["celsius", "fahrenheit"] = "celsius") -> str: """A simple function tool to get weather information.""" + return f"The weather in {location} is {randint(-10, 30) if unit == 'celsius' else randint(30, 100)} degrees {unit}." diff --git a/python/samples/02-agents/declarative/inline_yaml.py b/python/samples/02-agents/declarative/inline_yaml.py index 2e8561086b..1c7b052e4f 100644 --- a/python/samples/02-agents/declarative/inline_yaml.py +++ b/python/samples/02-agents/declarative/inline_yaml.py @@ -5,6 +5,7 @@ from azure.identity.aio import AzureCliCredential from dotenv import load_dotenv +# Load environment variables from .env file load_dotenv() """ @@ -37,7 +38,9 @@ async def main(): # create the agent from the yaml async with ( AzureCliCredential() as credential, - AgentFactory(client_kwargs={"credential": credential}, safe_mode=False).create_agent_from_yaml(yaml_definition) as agent, + AgentFactory(client_kwargs={"credential": credential}, safe_mode=False).create_agent_from_yaml( + yaml_definition + ) as agent, ): response = await agent.run("What can you do for me?") print("Agent response:", response.text) diff --git a/python/samples/02-agents/declarative/mcp_tool_yaml.py b/python/samples/02-agents/declarative/mcp_tool_yaml.py index 27128b499a..366771b903 100644 --- a/python/samples/02-agents/declarative/mcp_tool_yaml.py +++ b/python/samples/02-agents/declarative/mcp_tool_yaml.py @@ -28,6 +28,7 @@ from agent_framework.declarative import AgentFactory from dotenv import load_dotenv +# Load environment variables from .env file load_dotenv() # Example 1: OpenAI.Responses with API key authentication diff --git a/python/samples/02-agents/declarative/microsoft_learn_agent.py b/python/samples/02-agents/declarative/microsoft_learn_agent.py index affd1563cb..a42806eb92 100644 --- a/python/samples/02-agents/declarative/microsoft_learn_agent.py +++ b/python/samples/02-agents/declarative/microsoft_learn_agent.py @@ -6,11 +6,13 @@ from azure.identity.aio import AzureCliCredential from dotenv import load_dotenv +# Load environment variables from .env file load_dotenv() async def main(): """Create an agent from a declarative yaml specification and run it.""" + # get the path current_path = Path(__file__).parent yaml_path = current_path.parent.parent.parent.parent / "agent-samples" / "foundry" / "MicrosoftLearnAgent.yaml" @@ -18,7 +20,9 @@ async def main(): # create the agent from the yaml async with ( AzureCliCredential() as credential, - AgentFactory(client_kwargs={"credential": credential}, safe_mode=False).create_agent_from_yaml_path(yaml_path) as agent, + AgentFactory(client_kwargs={"credential": credential}, safe_mode=False).create_agent_from_yaml_path( + yaml_path + ) as agent, ): response = await agent.run("How do I create a storage account with private endpoint using bicep?") print("Agent response:", response.text) diff --git a/python/samples/02-agents/declarative/openai_responses_agent.py b/python/samples/02-agents/declarative/openai_responses_agent.py index 3c8c0861fa..cc4c8fb92a 100644 --- a/python/samples/02-agents/declarative/openai_responses_agent.py +++ b/python/samples/02-agents/declarative/openai_responses_agent.py @@ -5,11 +5,13 @@ from agent_framework.declarative import AgentFactory from dotenv import load_dotenv +# Load environment variables from .env file load_dotenv() async def main(): """Create an agent from a declarative yaml specification and run it.""" + # get the path current_path = Path(__file__).parent yaml_path = current_path.parent.parent.parent.parent / "agent-samples" / "openai" / "OpenAIResponses.yaml" diff --git a/python/samples/02-agents/devui/azure_responses_agent/agent.py b/python/samples/02-agents/devui/azure_responses_agent/agent.py index bb7de3d54d..2d952d729a 100644 --- a/python/samples/02-agents/devui/azure_responses_agent/agent.py +++ b/python/samples/02-agents/devui/azure_responses_agent/agent.py @@ -23,6 +23,10 @@ from agent_framework import Agent, tool from agent_framework.azure import AzureOpenAIResponsesClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() logger = logging.getLogger(__name__) diff --git a/python/samples/02-agents/devui/foundry_agent/agent.py b/python/samples/02-agents/devui/foundry_agent/agent.py index 59599bce54..62e335646b 100644 --- a/python/samples/02-agents/devui/foundry_agent/agent.py +++ b/python/samples/02-agents/devui/foundry_agent/agent.py @@ -11,10 +11,16 @@ from agent_framework import Agent, tool from agent_framework.azure import AzureAIAgentClient from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. + +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def get_weather( location: Annotated[str, Field(description="The location to get the weather for.")], diff --git a/python/samples/02-agents/devui/in_memory_mode.py b/python/samples/02-agents/devui/in_memory_mode.py index 78e0ae18ed..62a2800315 100644 --- a/python/samples/02-agents/devui/in_memory_mode.py +++ b/python/samples/02-agents/devui/in_memory_mode.py @@ -13,12 +13,16 @@ from agent_framework import Agent, Executor, WorkflowBuilder, WorkflowContext, handler, tool from agent_framework.azure import AzureOpenAIChatClient from agent_framework.devui import serve +from dotenv import load_dotenv from typing_extensions import Never +# Load environment variables from .env file +load_dotenv() -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. -@tool(approval_mode="never_require") -# Tool functions for the agent + +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def get_weather( location: Annotated[str, "The location to get the weather for."], diff --git a/python/samples/02-agents/devui/weather_agent_azure/agent.py b/python/samples/02-agents/devui/weather_agent_azure/agent.py index 38e7e11ce3..527f32a21d 100644 --- a/python/samples/02-agents/devui/weather_agent_azure/agent.py +++ b/python/samples/02-agents/devui/weather_agent_azure/agent.py @@ -16,19 +16,23 @@ Message, MiddlewareTermination, ResponseStream, - Role, chat_middleware, function_middleware, tool, ) from agent_framework.azure import AzureOpenAIChatClient from agent_framework_devui import register_cleanup +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() logger = logging.getLogger(__name__) def cleanup_resources(): """Cleanup function that runs when DevUI shuts down.""" + logger.info("=" * 60) logger.info(" Cleaning up resources...") logger.info(" (In production, this would close credentials, sessions, etc.)") @@ -45,7 +49,7 @@ async def security_filter_middleware( # Check only the last message (most recent user input) last_message = context.messages[-1] if context.messages else None - if last_message and last_message.role == Role.USER and last_message.text: + if last_message and last_message.role == "user" and last_message.text: message_lower = last_message.text.lower() for term in blocked_terms: if term in message_lower: @@ -60,19 +64,17 @@ async def security_filter_middleware( async def blocked_stream(msg: str = error_message) -> AsyncIterable[ChatResponseUpdate]: yield ChatResponseUpdate( contents=[Content.from_text(text=msg)], - role=Role.ASSISTANT, + role="assistant", ) - response = ChatResponse( - messages=[Message(role=Role.ASSISTANT, text=error_message)] - ) + response = ChatResponse(messages=[Message(role="assistant", text=error_message)]) context.result = ResponseStream(blocked_stream(), finalizer=lambda _, r=response: r) else: # Non-streaming mode: return complete response context.result = ChatResponse( messages=[ Message( - role=Role.ASSISTANT, + role="assistant", text=error_message, ) ] @@ -101,7 +103,9 @@ async def atlantis_location_filter_middleware( await call_next() -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def get_weather( location: Annotated[str, "The location to get the weather for."], diff --git a/python/samples/02-agents/devui/workflow_agents/workflow.py b/python/samples/02-agents/devui/workflow_agents/workflow.py index 4331650bf1..a8a6293e35 100644 --- a/python/samples/02-agents/devui/workflow_agents/workflow.py +++ b/python/samples/02-agents/devui/workflow_agents/workflow.py @@ -19,8 +19,12 @@ from agent_framework import AgentExecutorResponse, WorkflowBuilder from agent_framework.azure import AzureOpenAIChatClient +from dotenv import load_dotenv from pydantic import BaseModel +# Load environment variables from .env file +load_dotenv() + # Define structured output for review results class ReviewResult(BaseModel): diff --git a/python/samples/02-agents/mcp/agent_as_mcp_server.py b/python/samples/02-agents/mcp/agent_as_mcp_server.py index 7d9a6ffe91..2769a95931 100644 --- a/python/samples/02-agents/mcp/agent_as_mcp_server.py +++ b/python/samples/02-agents/mcp/agent_as_mcp_server.py @@ -5,6 +5,10 @@ import anyio from agent_framework import tool from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ This sample demonstrates how to expose an Agent as an MCP server. diff --git a/python/samples/02-agents/mcp/mcp_api_key_auth.py b/python/samples/02-agents/mcp/mcp_api_key_auth.py index 1836c73b57..16748a593c 100644 --- a/python/samples/02-agents/mcp/mcp_api_key_auth.py +++ b/python/samples/02-agents/mcp/mcp_api_key_auth.py @@ -5,8 +5,12 @@ from agent_framework import Agent, MCPStreamableHTTPTool from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv from httpx import AsyncClient +# Load environment variables from .env file +load_dotenv() + """ MCP Authentication Example diff --git a/python/samples/02-agents/middleware/agent_and_run_level_middleware.py b/python/samples/02-agents/middleware/agent_and_run_level_middleware.py index cf1d97a586..55ccce3507 100644 --- a/python/samples/02-agents/middleware/agent_and_run_level_middleware.py +++ b/python/samples/02-agents/middleware/agent_and_run_level_middleware.py @@ -15,8 +15,12 @@ ) from agent_framework.azure import AzureAIAgentClient from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Agent-Level and Run-Level MiddlewareTypes Example @@ -54,7 +58,9 @@ """ -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def get_weather( location: Annotated[str, Field(description="The location to get the weather for.")], diff --git a/python/samples/02-agents/middleware/chat_middleware.py b/python/samples/02-agents/middleware/chat_middleware.py index f139f11a9e..48caf9369b 100644 --- a/python/samples/02-agents/middleware/chat_middleware.py +++ b/python/samples/02-agents/middleware/chat_middleware.py @@ -16,8 +16,12 @@ ) from agent_framework.azure import AzureAIAgentClient from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Chat MiddlewareTypes Example @@ -37,7 +41,9 @@ """ -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def get_weather( location: Annotated[str, Field(description="The location to get the weather for.")], diff --git a/python/samples/02-agents/middleware/class_based_middleware.py b/python/samples/02-agents/middleware/class_based_middleware.py index 7bdb02cc69..bce31315ee 100644 --- a/python/samples/02-agents/middleware/class_based_middleware.py +++ b/python/samples/02-agents/middleware/class_based_middleware.py @@ -17,8 +17,12 @@ ) from agent_framework.azure import AzureAIAgentClient from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Class-based MiddlewareTypes Example @@ -34,7 +38,9 @@ """ -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def get_weather( location: Annotated[str, Field(description="The location to get the weather for.")], diff --git a/python/samples/02-agents/middleware/decorator_middleware.py b/python/samples/02-agents/middleware/decorator_middleware.py index 5b22b80cc0..e02e47e252 100644 --- a/python/samples/02-agents/middleware/decorator_middleware.py +++ b/python/samples/02-agents/middleware/decorator_middleware.py @@ -10,6 +10,10 @@ ) from agent_framework.azure import AzureAIAgentClient from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Decorator MiddlewareTypes Example @@ -42,7 +46,9 @@ """ -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def get_current_time() -> str: """Get the current time.""" diff --git a/python/samples/02-agents/middleware/exception_handling_with_middleware.py b/python/samples/02-agents/middleware/exception_handling_with_middleware.py index 83f604c25c..22bd374567 100644 --- a/python/samples/02-agents/middleware/exception_handling_with_middleware.py +++ b/python/samples/02-agents/middleware/exception_handling_with_middleware.py @@ -7,8 +7,12 @@ from agent_framework import FunctionInvocationContext, tool from agent_framework.azure import AzureAIAgentClient from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Exception Handling with MiddlewareTypes @@ -24,7 +28,9 @@ """ -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def unstable_data_service( query: Annotated[str, Field(description="The data query to execute.")], diff --git a/python/samples/02-agents/middleware/function_based_middleware.py b/python/samples/02-agents/middleware/function_based_middleware.py index ad0679219a..f0ea0f2f26 100644 --- a/python/samples/02-agents/middleware/function_based_middleware.py +++ b/python/samples/02-agents/middleware/function_based_middleware.py @@ -13,8 +13,12 @@ ) from agent_framework.azure import AzureAIAgentClient from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Function-based MiddlewareTypes Example @@ -31,7 +35,9 @@ """ -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def get_weather( location: Annotated[str, Field(description="The location to get the weather for.")], diff --git a/python/samples/02-agents/middleware/middleware_termination.py b/python/samples/02-agents/middleware/middleware_termination.py index 47be212dda..89acce1b6f 100644 --- a/python/samples/02-agents/middleware/middleware_termination.py +++ b/python/samples/02-agents/middleware/middleware_termination.py @@ -15,8 +15,12 @@ ) from agent_framework.azure import AzureAIAgentClient from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ MiddlewareTypes Termination Example @@ -30,7 +34,9 @@ """ -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def get_weather( location: Annotated[str, Field(description="The location to get the weather for.")], diff --git a/python/samples/02-agents/middleware/override_result_with_middleware.py b/python/samples/02-agents/middleware/override_result_with_middleware.py index a72aeb7fc9..5ed4d2a937 100644 --- a/python/samples/02-agents/middleware/override_result_with_middleware.py +++ b/python/samples/02-agents/middleware/override_result_with_middleware.py @@ -19,8 +19,12 @@ tool, ) from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Result Override with MiddlewareTypes (Regular and Streaming) @@ -39,7 +43,9 @@ """ -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def get_weather( location: Annotated[str, Field(description="The location to get the weather for.")], diff --git a/python/samples/02-agents/middleware/runtime_context_delegation.py b/python/samples/02-agents/middleware/runtime_context_delegation.py index a27e945a8a..7aa19b3437 100644 --- a/python/samples/02-agents/middleware/runtime_context_delegation.py +++ b/python/samples/02-agents/middleware/runtime_context_delegation.py @@ -6,8 +6,12 @@ from agent_framework import FunctionInvocationContext, function_middleware, tool from agent_framework.openai import OpenAIChatClient +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Runtime Context Delegation Patterns @@ -285,9 +289,7 @@ async def email_kwargs_tracker( await call_next() @function_middleware - async def sms_kwargs_tracker( - context: FunctionInvocationContext, call_next: Callable[[], Awaitable[None]] - ) -> None: + async def sms_kwargs_tracker(context: FunctionInvocationContext, call_next: Callable[[], Awaitable[None]]) -> None: sms_agent_kwargs.update(context.kwargs) print(f"[SMSAgent] Received runtime context: {list(context.kwargs.keys())}") await call_next() diff --git a/python/samples/02-agents/middleware/session_behavior_middleware.py b/python/samples/02-agents/middleware/session_behavior_middleware.py index 464a137d07..2efe896fae 100644 --- a/python/samples/02-agents/middleware/session_behavior_middleware.py +++ b/python/samples/02-agents/middleware/session_behavior_middleware.py @@ -11,8 +11,12 @@ ) from agent_framework.azure import AzureOpenAIChatClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Thread Behavior MiddlewareTypes Example @@ -32,7 +36,9 @@ """ -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def get_weather( location: Annotated[str, Field(description="The location to get the weather for.")], diff --git a/python/samples/02-agents/middleware/shared_state_middleware.py b/python/samples/02-agents/middleware/shared_state_middleware.py index 3fe80f47a4..fbe9f54c92 100644 --- a/python/samples/02-agents/middleware/shared_state_middleware.py +++ b/python/samples/02-agents/middleware/shared_state_middleware.py @@ -11,8 +11,12 @@ ) from agent_framework.azure import AzureAIAgentClient from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Shared State Function-based MiddlewareTypes Example @@ -27,7 +31,9 @@ """ -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def get_weather( location: Annotated[str, Field(description="The location to get the weather for.")], diff --git a/python/samples/02-agents/multimodal_input/azure_chat_multimodal.py b/python/samples/02-agents/multimodal_input/azure_chat_multimodal.py index 969f3b4640..5883f184cf 100644 --- a/python/samples/02-agents/multimodal_input/azure_chat_multimodal.py +++ b/python/samples/02-agents/multimodal_input/azure_chat_multimodal.py @@ -5,6 +5,10 @@ from agent_framework import Content, Message from agent_framework.azure import AzureOpenAIChatClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() def create_sample_image() -> str: diff --git a/python/samples/02-agents/multimodal_input/azure_responses_multimodal.py b/python/samples/02-agents/multimodal_input/azure_responses_multimodal.py index c020add6f6..8c7dd76f7e 100644 --- a/python/samples/02-agents/multimodal_input/azure_responses_multimodal.py +++ b/python/samples/02-agents/multimodal_input/azure_responses_multimodal.py @@ -6,6 +6,10 @@ from agent_framework import Content, Message from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() ASSETS_DIR = Path(__file__).resolve().parents[2] / "shared" / "sample_assets" diff --git a/python/samples/02-agents/multimodal_input/openai_chat_multimodal.py b/python/samples/02-agents/multimodal_input/openai_chat_multimodal.py index 22029c8c33..1e0849d8d6 100644 --- a/python/samples/02-agents/multimodal_input/openai_chat_multimodal.py +++ b/python/samples/02-agents/multimodal_input/openai_chat_multimodal.py @@ -7,6 +7,10 @@ from agent_framework import Content, Message from agent_framework.openai import OpenAIChatClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() ASSETS_DIR = Path(__file__).resolve().parents[2] / "shared" / "sample_assets" diff --git a/python/samples/02-agents/observability/advanced_manual_setup_console_output.py b/python/samples/02-agents/observability/advanced_manual_setup_console_output.py index 8f02c003cb..7afd359264 100644 --- a/python/samples/02-agents/observability/advanced_manual_setup_console_output.py +++ b/python/samples/02-agents/observability/advanced_manual_setup_console_output.py @@ -8,6 +8,7 @@ from agent_framework import Message, tool from agent_framework.observability import enable_instrumentation from agent_framework.openai import OpenAIChatClient +from dotenv import load_dotenv from opentelemetry._logs import set_logger_provider from opentelemetry.metrics import set_meter_provider from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler @@ -21,6 +22,9 @@ from opentelemetry.trace import set_tracer_provider from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ This sample shows how to manually configure to send traces, logs, and metrics to the console, without using the `configure_otel_providers` helper function. diff --git a/python/samples/02-agents/observability/advanced_zero_code.py b/python/samples/02-agents/observability/advanced_zero_code.py index 9ee0b922c5..477a5b4d9b 100644 --- a/python/samples/02-agents/observability/advanced_zero_code.py +++ b/python/samples/02-agents/observability/advanced_zero_code.py @@ -7,6 +7,7 @@ from agent_framework import Message, tool from agent_framework.observability import get_tracer from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv from opentelemetry.trace import SpanKind from opentelemetry.trace.span import format_trace_id from pydantic import Field @@ -40,6 +41,9 @@ """ +# Load environment variables from .env file +load_dotenv() + # NOTE: approval_mode="never_require" is for sample brevity. # Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py diff --git a/python/samples/02-agents/observability/agent_observability.py b/python/samples/02-agents/observability/agent_observability.py index 772a7d6c7f..ae4057d2f0 100644 --- a/python/samples/02-agents/observability/agent_observability.py +++ b/python/samples/02-agents/observability/agent_observability.py @@ -7,10 +7,14 @@ from agent_framework import Agent, tool from agent_framework.observability import configure_otel_providers, get_tracer from agent_framework.openai import OpenAIChatClient +from dotenv import load_dotenv from opentelemetry.trace import SpanKind from opentelemetry.trace.span import format_trace_id from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ This sample shows how you can observe an agent in Agent Framework by using the same observability setup function. diff --git a/python/samples/02-agents/observability/configure_otel_providers_with_env_var.py b/python/samples/02-agents/observability/configure_otel_providers_with_env_var.py index 9c848f1bf8..0e20c0a6f5 100644 --- a/python/samples/02-agents/observability/configure_otel_providers_with_env_var.py +++ b/python/samples/02-agents/observability/configure_otel_providers_with_env_var.py @@ -9,6 +9,7 @@ from agent_framework import Message, tool from agent_framework.observability import configure_otel_providers, get_tracer from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv from opentelemetry import trace from opentelemetry.trace.span import format_trace_id from pydantic import Field @@ -27,6 +28,9 @@ output traces, logs, and metrics to the console. """ +# Load environment variables from .env file +load_dotenv() + # Define the scenarios that can be run to show the telemetry data collected by the SDK SCENARIOS = ["client", "client_stream", "tool", "all"] diff --git a/python/samples/02-agents/observability/configure_otel_providers_with_parameters.py b/python/samples/02-agents/observability/configure_otel_providers_with_parameters.py index e325864996..c811fd55ae 100644 --- a/python/samples/02-agents/observability/configure_otel_providers_with_parameters.py +++ b/python/samples/02-agents/observability/configure_otel_providers_with_parameters.py @@ -10,6 +10,7 @@ from agent_framework import Message, tool from agent_framework.observability import configure_otel_providers, get_tracer from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv from opentelemetry import trace from opentelemetry.trace.span import format_trace_id from pydantic import Field @@ -28,6 +29,9 @@ Use this approach when you need custom exporter configuration beyond what environment variables provide. """ +# Load environment variables from .env file +load_dotenv() + # Define the scenarios that can be run to show the telemetry data collected by the SDK SCENARIOS = ["client", "client_stream", "tool", "all"] diff --git a/python/samples/02-agents/observability/workflow_observability.py b/python/samples/02-agents/observability/workflow_observability.py index 1a45069c59..f7893b2c98 100644 --- a/python/samples/02-agents/observability/workflow_observability.py +++ b/python/samples/02-agents/observability/workflow_observability.py @@ -80,9 +80,7 @@ async def run_sequential_workflow() -> None: # Step 2: Build the workflow with the defined edges. workflow = ( - WorkflowBuilder(start_executor=upper_case_executor) - .add_edge(upper_case_executor, reverse_text_executor) - .build() + WorkflowBuilder(start_executor=upper_case_executor).add_edge(upper_case_executor, reverse_text_executor).build() ) # Step 3: Run the workflow with an initial message. diff --git a/python/samples/02-agents/providers/amazon/bedrock_chat_client.py b/python/samples/02-agents/providers/amazon/bedrock_chat_client.py index 1913d55dea..a61944bcbd 100644 --- a/python/samples/02-agents/providers/amazon/bedrock_chat_client.py +++ b/python/samples/02-agents/providers/amazon/bedrock_chat_client.py @@ -5,8 +5,12 @@ from agent_framework import Agent, tool from agent_framework.amazon import BedrockChatClient +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Bedrock Chat Client Example diff --git a/python/samples/02-agents/providers/anthropic/anthropic_advanced.py b/python/samples/02-agents/providers/anthropic/anthropic_advanced.py index 0ae241c8a4..9fac03a645 100644 --- a/python/samples/02-agents/providers/anthropic/anthropic_advanced.py +++ b/python/samples/02-agents/providers/anthropic/anthropic_advanced.py @@ -3,6 +3,10 @@ import asyncio from agent_framework.anthropic import AnthropicChatOptions, AnthropicClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Anthropic Chat Agent Example diff --git a/python/samples/02-agents/providers/anthropic/anthropic_basic.py b/python/samples/02-agents/providers/anthropic/anthropic_basic.py index 408e129a43..4a97571456 100644 --- a/python/samples/02-agents/providers/anthropic/anthropic_basic.py +++ b/python/samples/02-agents/providers/anthropic/anthropic_basic.py @@ -6,6 +6,10 @@ from agent_framework import tool from agent_framework.anthropic import AnthropicClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Anthropic Chat Agent Example @@ -14,7 +18,9 @@ """ -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def get_weather( location: Annotated[str, "The location to get the weather for."], @@ -28,8 +34,7 @@ async def non_streaming_example() -> None: """Example of non-streaming response (get the complete result at once).""" print("=== Non-streaming Response Example ===") - agent = AnthropicClient( - ).as_agent( + agent = AnthropicClient().as_agent( name="WeatherAgent", instructions="You are a helpful weather agent.", tools=get_weather, @@ -45,8 +50,7 @@ async def streaming_example() -> None: """Example of streaming response (get results as they are generated).""" print("=== Streaming Response Example ===") - agent = AnthropicClient( - ).as_agent( + agent = AnthropicClient().as_agent( name="WeatherAgent", instructions="You are a helpful weather agent.", tools=get_weather, diff --git a/python/samples/02-agents/providers/anthropic/anthropic_claude_basic.py b/python/samples/02-agents/providers/anthropic/anthropic_claude_basic.py index b040bbd299..ec72cc5f65 100644 --- a/python/samples/02-agents/providers/anthropic/anthropic_claude_basic.py +++ b/python/samples/02-agents/providers/anthropic/anthropic_claude_basic.py @@ -20,6 +20,10 @@ from agent_framework import tool from agent_framework.anthropic import ClaudeAgent +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() @tool diff --git a/python/samples/02-agents/providers/anthropic/anthropic_claude_with_mcp.py b/python/samples/02-agents/providers/anthropic/anthropic_claude_with_mcp.py index 455f4fd190..991481487c 100644 --- a/python/samples/02-agents/providers/anthropic/anthropic_claude_with_mcp.py +++ b/python/samples/02-agents/providers/anthropic/anthropic_claude_with_mcp.py @@ -21,6 +21,10 @@ from agent_framework.anthropic import ClaudeAgent from claude_agent_sdk import PermissionResultAllow, PermissionResultDeny +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() async def prompt_permission( diff --git a/python/samples/02-agents/providers/anthropic/anthropic_foundry.py b/python/samples/02-agents/providers/anthropic/anthropic_foundry.py index 00f5c5f2e0..481f3bb6b4 100644 --- a/python/samples/02-agents/providers/anthropic/anthropic_foundry.py +++ b/python/samples/02-agents/providers/anthropic/anthropic_foundry.py @@ -4,6 +4,10 @@ from agent_framework.anthropic import AnthropicClient from anthropic import AsyncAnthropicFoundry +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Anthropic Foundry Chat Agent Example diff --git a/python/samples/02-agents/providers/anthropic/anthropic_skills.py b/python/samples/02-agents/providers/anthropic/anthropic_skills.py index 417feabb50..9296b1d9a2 100644 --- a/python/samples/02-agents/providers/anthropic/anthropic_skills.py +++ b/python/samples/02-agents/providers/anthropic/anthropic_skills.py @@ -6,6 +6,10 @@ from agent_framework import Content from agent_framework.anthropic import AnthropicChatOptions, AnthropicClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() logger = logging.getLogger(__name__) """ diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_basic.py b/python/samples/02-agents/providers/azure_ai/azure_ai_basic.py index 3661aa71a4..2f4df77f17 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_basic.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_basic.py @@ -7,8 +7,12 @@ from agent_framework import tool from agent_framework.azure import AzureAIProjectAgentProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure AI Agent Basic Example diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_provider_methods.py b/python/samples/02-agents/providers/azure_ai/azure_ai_provider_methods.py index 0e72530f7d..e08dfcc1bc 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_provider_methods.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_provider_methods.py @@ -10,8 +10,12 @@ from azure.ai.projects.aio import AIProjectClient from azure.ai.projects.models import AgentReference, PromptAgentDefinition from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure AI Project Agent Provider Methods Example diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_use_latest_version.py b/python/samples/02-agents/providers/azure_ai/azure_ai_use_latest_version.py index 4cad79c5cb..2647742d38 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_use_latest_version.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_use_latest_version.py @@ -7,8 +7,12 @@ from agent_framework import tool from agent_framework.azure import AzureAIProjectAgentProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure AI Agent Latest Version Example diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_agent_as_tool.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_agent_as_tool.py index 2d873f2930..c217242df7 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_agent_as_tool.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_agent_as_tool.py @@ -6,6 +6,10 @@ from agent_framework import FunctionInvocationContext from agent_framework.azure import AzureAIProjectAgentProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent-as-Tool Example diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_agent_to_agent.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_agent_to_agent.py index d1dce0b220..881b4a38f1 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_agent_to_agent.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_agent_to_agent.py @@ -4,6 +4,10 @@ from agent_framework.azure import AzureAIProjectAgentProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent with Agent-to-Agent (A2A) Example diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_application_endpoint.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_application_endpoint.py index 8bfb72883b..8183d2850a 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_application_endpoint.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_application_endpoint.py @@ -7,6 +7,10 @@ from agent_framework.azure import AzureAIClient from azure.ai.projects.aio import AIProjectClient from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent with Application Endpoint Example diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_azure_ai_search.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_azure_ai_search.py index c4ee686d87..25648751d8 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_azure_ai_search.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_azure_ai_search.py @@ -4,6 +4,10 @@ from agent_framework.azure import AzureAIProjectAgentProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent with Azure AI Search Example diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_bing_custom_search.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_bing_custom_search.py index 2a2db762f4..123ee82431 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_bing_custom_search.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_bing_custom_search.py @@ -4,6 +4,10 @@ from agent_framework.azure import AzureAIProjectAgentProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent with Bing Custom Search Example diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_bing_grounding.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_bing_grounding.py index 92c00dddc9..e3a3e8330c 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_bing_grounding.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_bing_grounding.py @@ -4,6 +4,10 @@ from agent_framework.azure import AzureAIProjectAgentProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent with Bing Grounding Example diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_browser_automation.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_browser_automation.py index 21a180530c..33cd302485 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_browser_automation.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_browser_automation.py @@ -4,6 +4,10 @@ from agent_framework.azure import AzureAIProjectAgentProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent with Browser Automation Example diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_code_interpreter.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_code_interpreter.py index f91ddc01c1..d196e9dd73 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_code_interpreter.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_code_interpreter.py @@ -5,9 +5,13 @@ from agent_framework import ChatResponse from agent_framework.azure import AzureAIClient, AzureAIProjectAgentProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv from openai.types.responses.response import Response as OpenAIResponse from openai.types.responses.response_code_interpreter_tool_call import ResponseCodeInterpreterToolCall +# Load environment variables from .env file +load_dotenv() + """ Azure AI Agent Code Interpreter Example diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_code_interpreter_file_download.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_code_interpreter_file_download.py index cb5087b3f6..686c395f74 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_code_interpreter_file_download.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_code_interpreter_file_download.py @@ -12,6 +12,10 @@ ) from agent_framework.azure import AzureAIClient, AzureAIProjectAgentProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI V2 Code Interpreter File Download Sample diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_code_interpreter_file_generation.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_code_interpreter_file_generation.py index 72386aa418..38e3e7eada 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_code_interpreter_file_generation.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_code_interpreter_file_generation.py @@ -7,6 +7,10 @@ ) from agent_framework.azure import AzureAIClient, AzureAIProjectAgentProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI V2 Code Interpreter File Generation Sample diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_content_filtering.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_content_filtering.py index 72597b1cd8..3af4ef4854 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_content_filtering.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_content_filtering.py @@ -5,6 +5,10 @@ from agent_framework.azure import AzureAIProjectAgentProvider from azure.ai.projects.models import RaiConfig from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent with Content Filtering (RAI Policy) Example diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_existing_agent.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_existing_agent.py index 0549c642c2..84c6cc54de 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_existing_agent.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_existing_agent.py @@ -7,6 +7,10 @@ from azure.ai.projects.aio import AIProjectClient from azure.ai.projects.models import PromptAgentDefinition from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent with Existing Agent Example diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_existing_conversation.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_existing_conversation.py index 92a31b2835..d19997b98a 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_existing_conversation.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_existing_conversation.py @@ -8,8 +8,12 @@ from agent_framework.azure import AzureAIProjectAgentProvider from azure.ai.projects.aio import AIProjectClient from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure AI Agent Existing Conversation Example diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_explicit_settings.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_explicit_settings.py index c61d5bbb76..9ee83478a3 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_explicit_settings.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_explicit_settings.py @@ -8,8 +8,12 @@ from agent_framework import tool from agent_framework.azure import AzureAIProjectAgentProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure AI Agent with Explicit Settings Example diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_file_search.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_file_search.py index 025f17b5a3..c15edd95dd 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_file_search.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_file_search.py @@ -8,6 +8,10 @@ from agent_framework.azure import AzureAIClient, AzureAIProjectAgentProvider from azure.ai.projects.aio import AIProjectClient from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ The following sample demonstrates how to create a simple, Azure AI agent that diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_hosted_mcp.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_hosted_mcp.py index 02216a3014..d892834afc 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_hosted_mcp.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_hosted_mcp.py @@ -6,6 +6,10 @@ from agent_framework import AgentResponse, AgentSession, Message, SupportsAgentRun from agent_framework.azure import AzureAIClient, AzureAIProjectAgentProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent with Hosted MCP Example @@ -35,7 +39,9 @@ async def handle_approvals_without_session(query: str, agent: "SupportsAgentRun" return result -async def handle_approvals_with_session(query: str, agent: "SupportsAgentRun", session: "AgentSession") -> AgentResponse: +async def handle_approvals_with_session( + query: str, agent: "SupportsAgentRun", session: "AgentSession" +) -> AgentResponse: """Here we let the session deal with the previous responses, and we just rerun with the approval.""" result = await agent.run(query, session=session) diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_image_generation.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_image_generation.py index 48e54ef2e2..e9d783d080 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_image_generation.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_image_generation.py @@ -7,6 +7,10 @@ from agent_framework.azure import AzureAIClient, AzureAIProjectAgentProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent with Image Generation Example diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_local_mcp.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_local_mcp.py index a3ce3be5ea..77dd0cdad3 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_local_mcp.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_local_mcp.py @@ -5,6 +5,10 @@ from agent_framework import MCPStreamableHTTPTool from agent_framework.azure import AzureAIProjectAgentProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent with Local MCP Example diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_memory_search.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_memory_search.py index 72b9ea1a01..2d1cb43c30 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_memory_search.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_memory_search.py @@ -7,6 +7,10 @@ from azure.ai.projects.aio import AIProjectClient from azure.ai.projects.models import MemoryStoreDefaultDefinition, MemoryStoreDefaultOptions from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent with Memory Search Example diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_microsoft_fabric.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_microsoft_fabric.py index 0f3b39d192..531a18cb69 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_microsoft_fabric.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_microsoft_fabric.py @@ -4,6 +4,10 @@ from agent_framework.azure import AzureAIProjectAgentProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent with Microsoft Fabric Example diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_openapi.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_openapi.py index 55e9ecb602..2565c6ea23 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_openapi.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_openapi.py @@ -5,6 +5,10 @@ from agent_framework.azure import AzureAIProjectAgentProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent with OpenAPI Tool Example diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_reasoning.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_reasoning.py index 06da57ea60..60e6635fdd 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_reasoning.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_reasoning.py @@ -5,6 +5,10 @@ from agent_framework.azure import AzureAIProjectAgentProvider from azure.ai.projects.models import Reasoning from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent with Reasoning Example diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_response_format.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_response_format.py index 39ea0b722c..e1285b1d17 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_response_format.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_response_format.py @@ -4,8 +4,12 @@ from agent_framework.azure import AzureAIProjectAgentProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv from pydantic import BaseModel, ConfigDict +# Load environment variables from .env file +load_dotenv() + """ Azure AI Agent Response Format Example diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_runtime_json_schema.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_runtime_json_schema.py index 21f67a0984..ae74566023 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_runtime_json_schema.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_runtime_json_schema.py @@ -4,6 +4,10 @@ from agent_framework.azure import AzureAIProjectAgentProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent Response Format Example with Runtime JSON Schema diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_session.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_session.py index 1350f3faa9..209c6e2695 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_session.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_session.py @@ -7,8 +7,12 @@ from agent_framework import tool from agent_framework.azure import AzureAIProjectAgentProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure AI Agent with Session Management Example diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_sharepoint.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_sharepoint.py index cd7765741e..ce6bf85837 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_sharepoint.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_sharepoint.py @@ -4,6 +4,10 @@ from agent_framework.azure import AzureAIProjectAgentProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent with SharePoint Example diff --git a/python/samples/02-agents/providers/azure_ai/azure_ai_with_web_search.py b/python/samples/02-agents/providers/azure_ai/azure_ai_with_web_search.py index 39274c42d6..5134b275d4 100644 --- a/python/samples/02-agents/providers/azure_ai/azure_ai_with_web_search.py +++ b/python/samples/02-agents/providers/azure_ai/azure_ai_with_web_search.py @@ -4,6 +4,10 @@ from agent_framework.azure import AzureAIClient, AzureAIProjectAgentProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent With Web Search diff --git a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_basic.py b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_basic.py index 0d10337e86..640653df26 100644 --- a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_basic.py +++ b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_basic.py @@ -7,8 +7,12 @@ from agent_framework import tool from agent_framework.azure import AzureAIAgentsProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure AI Agent Basic Example diff --git a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_provider_methods.py b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_provider_methods.py index e8e19b068b..571f737315 100644 --- a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_provider_methods.py +++ b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_provider_methods.py @@ -9,8 +9,12 @@ from agent_framework.azure import AzureAIAgentsProvider from azure.ai.agents.aio import AgentsClient from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure AI Agent Provider Methods Example diff --git a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_azure_ai_search.py b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_azure_ai_search.py index 20ccfe8de6..67833d2dd0 100644 --- a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_azure_ai_search.py +++ b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_azure_ai_search.py @@ -9,6 +9,10 @@ from azure.ai.projects.aio import AIProjectClient from azure.ai.projects.models import ConnectionType from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent with Azure AI Search Example diff --git a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_bing_custom_search.py b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_bing_custom_search.py index d4d718a868..4268568f85 100644 --- a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_bing_custom_search.py +++ b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_bing_custom_search.py @@ -4,6 +4,10 @@ from agent_framework.azure import AzureAIAgentClient, AzureAIAgentsProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ The following sample demonstrates how to create an Azure AI agent that diff --git a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_bing_grounding.py b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_bing_grounding.py index 9724f91591..7fb83b378d 100644 --- a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_bing_grounding.py +++ b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_bing_grounding.py @@ -4,6 +4,10 @@ from agent_framework.azure import AzureAIAgentClient, AzureAIAgentsProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ The following sample demonstrates how to create an Azure AI agent that diff --git a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_bing_grounding_citations.py b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_bing_grounding_citations.py index 10d594514c..1b240f9812 100644 --- a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_bing_grounding_citations.py +++ b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_bing_grounding_citations.py @@ -5,6 +5,10 @@ from agent_framework import Annotation from agent_framework.azure import AzureAIAgentClient, AzureAIAgentsProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ This sample demonstrates how to create an Azure AI agent that uses Bing Grounding diff --git a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_code_interpreter.py b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_code_interpreter.py index 16da21bbe0..353a10f6a0 100644 --- a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_code_interpreter.py +++ b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_code_interpreter.py @@ -8,6 +8,10 @@ RunStepDeltaCodeInterpreterDetailItemObject, ) from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent with Code Interpreter Example diff --git a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_code_interpreter_file_generation.py b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_code_interpreter_file_generation.py index 3cbf9c5855..e96b439b92 100644 --- a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_code_interpreter_file_generation.py +++ b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_code_interpreter_file_generation.py @@ -6,6 +6,10 @@ from agent_framework.azure import AzureAIAgentClient, AzureAIAgentsProvider from azure.ai.agents.aio import AgentsClient from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent Code Interpreter File Generation Example diff --git a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_existing_agent.py b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_existing_agent.py index 9518498098..95a93303f1 100644 --- a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_existing_agent.py +++ b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_existing_agent.py @@ -6,6 +6,10 @@ from agent_framework.azure import AzureAIAgentsProvider from azure.ai.agents.aio import AgentsClient from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent with Existing Agent Example diff --git a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_existing_session.py b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_existing_session.py index 66451483ac..76f08b37ea 100644 --- a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_existing_session.py +++ b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_existing_session.py @@ -9,8 +9,12 @@ from agent_framework.azure import AzureAIAgentsProvider from azure.ai.agents.aio import AgentsClient from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure AI Agent with Existing Session Example diff --git a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_explicit_settings.py b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_explicit_settings.py index ea088106d0..f34d9e41e9 100644 --- a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_explicit_settings.py +++ b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_explicit_settings.py @@ -8,8 +8,12 @@ from agent_framework import tool from agent_framework.azure import AzureAIAgentsProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure AI Agent with Explicit Settings Example diff --git a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_file_search.py b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_file_search.py index 1f06a6c89d..7721152e6e 100644 --- a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_file_search.py +++ b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_file_search.py @@ -8,6 +8,10 @@ from azure.ai.agents.aio import AgentsClient from azure.ai.agents.models import FileInfo, VectorStore from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ The following sample demonstrates how to create a simple, Azure AI agent that diff --git a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_function_tools.py b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_function_tools.py index 2b252af9c5..3366af58ce 100644 --- a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_function_tools.py +++ b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_function_tools.py @@ -8,8 +8,12 @@ from agent_framework import tool from agent_framework.azure import AzureAIAgentsProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure AI Agent with Function Tools Example diff --git a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_hosted_mcp.py b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_hosted_mcp.py index 9a64bae9a1..2401ee9331 100644 --- a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_hosted_mcp.py +++ b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_hosted_mcp.py @@ -6,6 +6,10 @@ from agent_framework import AgentResponse, AgentSession, SupportsAgentRun from agent_framework.azure import AzureAIAgentClient, AzureAIAgentsProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent with Hosted MCP Example @@ -15,7 +19,9 @@ """ -async def handle_approvals_with_session(query: str, agent: "SupportsAgentRun", session: "AgentSession") -> AgentResponse: +async def handle_approvals_with_session( + query: str, agent: "SupportsAgentRun", session: "AgentSession" +) -> AgentResponse: """Here we let the session deal with the previous responses, and we just rerun with the approval.""" from agent_framework import Message diff --git a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_local_mcp.py b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_local_mcp.py index 8e26edfccc..f7165e4c8d 100644 --- a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_local_mcp.py +++ b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_local_mcp.py @@ -5,6 +5,10 @@ from agent_framework import MCPStreamableHTTPTool from agent_framework.azure import AzureAIAgentsProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent with Local MCP Example diff --git a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_multiple_tools.py b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_multiple_tools.py index 4e2112f0a5..c7e8056219 100644 --- a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_multiple_tools.py +++ b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_multiple_tools.py @@ -11,6 +11,10 @@ ) from agent_framework.azure import AzureAIAgentClient, AzureAIAgentsProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure AI Agent with Multiple Tools Example diff --git a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_openapi_tools.py b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_openapi_tools.py index aff0c649d8..6eb032ae2c 100644 --- a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_openapi_tools.py +++ b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_openapi_tools.py @@ -8,6 +8,10 @@ from agent_framework.azure import AzureAIAgentsProvider from azure.ai.agents.models import OpenApiAnonymousAuthDetails, OpenApiTool from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ The following sample demonstrates how to create a simple, Azure AI agent that diff --git a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_response_format.py b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_response_format.py index a607304724..8fd4a7d365 100644 --- a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_response_format.py +++ b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_response_format.py @@ -4,8 +4,12 @@ from agent_framework.azure import AzureAIAgentsProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv from pydantic import BaseModel, ConfigDict +# Load environment variables from .env file +load_dotenv() + """ Azure AI Agent Provider Response Format Example diff --git a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_session.py b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_session.py index 3025aff851..7ea7e4b5db 100644 --- a/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_session.py +++ b/python/samples/02-agents/providers/azure_ai_agent/azure_ai_with_session.py @@ -7,8 +7,12 @@ from agent_framework import AgentSession, tool from agent_framework.azure import AzureAIAgentsProvider from azure.identity.aio import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure AI Agent with Session Management Example diff --git a/python/samples/02-agents/providers/azure_openai/azure_assistants_basic.py b/python/samples/02-agents/providers/azure_openai/azure_assistants_basic.py index 71fbdcbe9d..a1e61be0e8 100644 --- a/python/samples/02-agents/providers/azure_openai/azure_assistants_basic.py +++ b/python/samples/02-agents/providers/azure_openai/azure_assistants_basic.py @@ -7,8 +7,12 @@ from agent_framework import tool from agent_framework.azure import AzureOpenAIAssistantsClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure OpenAI Assistants Basic Example diff --git a/python/samples/02-agents/providers/azure_openai/azure_assistants_with_code_interpreter.py b/python/samples/02-agents/providers/azure_openai/azure_assistants_with_code_interpreter.py index 7a0eb2645d..c1bbd54e20 100644 --- a/python/samples/02-agents/providers/azure_openai/azure_assistants_with_code_interpreter.py +++ b/python/samples/02-agents/providers/azure_openai/azure_assistants_with_code_interpreter.py @@ -4,6 +4,7 @@ from agent_framework import Agent, AgentResponseUpdate, ChatResponseUpdate from agent_framework.azure import AzureOpenAIAssistantsClient +from dotenv import load_dotenv from openai.types.beta.threads.runs import ( CodeInterpreterToolCallDelta, RunStepDelta, @@ -12,6 +13,9 @@ ) from openai.types.beta.threads.runs.code_interpreter_tool_call_delta import CodeInterpreter +# Load environment variables from .env file +load_dotenv() + """ Azure OpenAI Assistants with Code Interpreter Example diff --git a/python/samples/02-agents/providers/azure_openai/azure_assistants_with_existing_assistant.py b/python/samples/02-agents/providers/azure_openai/azure_assistants_with_existing_assistant.py index 195e9fc26e..e110d52cb8 100644 --- a/python/samples/02-agents/providers/azure_openai/azure_assistants_with_existing_assistant.py +++ b/python/samples/02-agents/providers/azure_openai/azure_assistants_with_existing_assistant.py @@ -8,9 +8,13 @@ from agent_framework import Agent, tool from agent_framework.azure import AzureOpenAIAssistantsClient from azure.identity import AzureCliCredential, get_bearer_token_provider +from dotenv import load_dotenv from openai import AsyncAzureOpenAI from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure OpenAI Assistants with Existing Assistant Example diff --git a/python/samples/02-agents/providers/azure_openai/azure_assistants_with_explicit_settings.py b/python/samples/02-agents/providers/azure_openai/azure_assistants_with_explicit_settings.py index c9c4cee118..8d4ca0bc7f 100644 --- a/python/samples/02-agents/providers/azure_openai/azure_assistants_with_explicit_settings.py +++ b/python/samples/02-agents/providers/azure_openai/azure_assistants_with_explicit_settings.py @@ -8,8 +8,12 @@ from agent_framework import tool from agent_framework.azure import AzureOpenAIAssistantsClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure OpenAI Assistants with Explicit Settings Example diff --git a/python/samples/02-agents/providers/azure_openai/azure_assistants_with_function_tools.py b/python/samples/02-agents/providers/azure_openai/azure_assistants_with_function_tools.py index 913332e953..1543a25f42 100644 --- a/python/samples/02-agents/providers/azure_openai/azure_assistants_with_function_tools.py +++ b/python/samples/02-agents/providers/azure_openai/azure_assistants_with_function_tools.py @@ -8,8 +8,12 @@ from agent_framework import Agent, tool from agent_framework.azure import AzureOpenAIAssistantsClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure OpenAI Assistants with Function Tools Example diff --git a/python/samples/02-agents/providers/azure_openai/azure_assistants_with_session.py b/python/samples/02-agents/providers/azure_openai/azure_assistants_with_session.py index 9c4bd6e235..4f3e952d86 100644 --- a/python/samples/02-agents/providers/azure_openai/azure_assistants_with_session.py +++ b/python/samples/02-agents/providers/azure_openai/azure_assistants_with_session.py @@ -7,8 +7,12 @@ from agent_framework import Agent, AgentSession, tool from agent_framework.azure import AzureOpenAIAssistantsClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure OpenAI Assistants with Session Management Example diff --git a/python/samples/02-agents/providers/azure_openai/azure_chat_client_basic.py b/python/samples/02-agents/providers/azure_openai/azure_chat_client_basic.py index c55e8682aa..6d9a4d8e01 100644 --- a/python/samples/02-agents/providers/azure_openai/azure_chat_client_basic.py +++ b/python/samples/02-agents/providers/azure_openai/azure_chat_client_basic.py @@ -7,8 +7,12 @@ from agent_framework import tool from agent_framework.azure import AzureOpenAIChatClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure OpenAI Chat Client Basic Example diff --git a/python/samples/02-agents/providers/azure_openai/azure_chat_client_with_explicit_settings.py b/python/samples/02-agents/providers/azure_openai/azure_chat_client_with_explicit_settings.py index ac0a1af782..ea00a80d6d 100644 --- a/python/samples/02-agents/providers/azure_openai/azure_chat_client_with_explicit_settings.py +++ b/python/samples/02-agents/providers/azure_openai/azure_chat_client_with_explicit_settings.py @@ -8,8 +8,12 @@ from agent_framework import tool from agent_framework.azure import AzureOpenAIChatClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure OpenAI Chat Client with Explicit Settings Example diff --git a/python/samples/02-agents/providers/azure_openai/azure_chat_client_with_function_tools.py b/python/samples/02-agents/providers/azure_openai/azure_chat_client_with_function_tools.py index 4b42ebecef..7458aea2e6 100644 --- a/python/samples/02-agents/providers/azure_openai/azure_chat_client_with_function_tools.py +++ b/python/samples/02-agents/providers/azure_openai/azure_chat_client_with_function_tools.py @@ -8,8 +8,12 @@ from agent_framework import Agent, tool from agent_framework.azure import AzureOpenAIChatClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure OpenAI Chat Client with Function Tools Example diff --git a/python/samples/02-agents/providers/azure_openai/azure_chat_client_with_session.py b/python/samples/02-agents/providers/azure_openai/azure_chat_client_with_session.py index f2d7df8ed3..0592aba2c7 100644 --- a/python/samples/02-agents/providers/azure_openai/azure_chat_client_with_session.py +++ b/python/samples/02-agents/providers/azure_openai/azure_chat_client_with_session.py @@ -7,8 +7,12 @@ from agent_framework import Agent, AgentSession, InMemoryHistoryProvider, tool from agent_framework.azure import AzureOpenAIChatClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure OpenAI Chat Client with Session Management Example diff --git a/python/samples/02-agents/providers/azure_openai/azure_responses_client_basic.py b/python/samples/02-agents/providers/azure_openai/azure_responses_client_basic.py index c638426e4d..73820443f3 100644 --- a/python/samples/02-agents/providers/azure_openai/azure_responses_client_basic.py +++ b/python/samples/02-agents/providers/azure_openai/azure_responses_client_basic.py @@ -7,8 +7,12 @@ from agent_framework import tool from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure OpenAI Responses Client Basic Example diff --git a/python/samples/02-agents/providers/azure_openai/azure_responses_client_code_interpreter_files.py b/python/samples/02-agents/providers/azure_openai/azure_responses_client_code_interpreter_files.py index 33154a7c47..eb81f941b8 100644 --- a/python/samples/02-agents/providers/azure_openai/azure_responses_client_code_interpreter_files.py +++ b/python/samples/02-agents/providers/azure_openai/azure_responses_client_code_interpreter_files.py @@ -7,8 +7,12 @@ from agent_framework import Agent from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv from openai import AsyncAzureOpenAI +# Load environment variables from .env file +load_dotenv() + """ Azure OpenAI Responses Client with Code Interpreter and Files Example diff --git a/python/samples/02-agents/providers/azure_openai/azure_responses_client_image_analysis.py b/python/samples/02-agents/providers/azure_openai/azure_responses_client_image_analysis.py index f23222b018..5066c6c832 100644 --- a/python/samples/02-agents/providers/azure_openai/azure_responses_client_image_analysis.py +++ b/python/samples/02-agents/providers/azure_openai/azure_responses_client_image_analysis.py @@ -5,6 +5,10 @@ from agent_framework import Content from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure OpenAI Responses Client with Image Analysis Example diff --git a/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_code_interpreter.py b/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_code_interpreter.py index 544e4c49e6..8862f81741 100644 --- a/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_code_interpreter.py +++ b/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_code_interpreter.py @@ -5,9 +5,13 @@ from agent_framework import Agent, ChatResponse from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv from openai.types.responses.response import Response as OpenAIResponse from openai.types.responses.response_code_interpreter_tool_call import ResponseCodeInterpreterToolCall +# Load environment variables from .env file +load_dotenv() + """ Azure OpenAI Responses Client with Code Interpreter Example diff --git a/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_explicit_settings.py b/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_explicit_settings.py index 57498b9e1f..f31efaa611 100644 --- a/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_explicit_settings.py +++ b/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_explicit_settings.py @@ -8,8 +8,12 @@ from agent_framework import tool from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure OpenAI Responses Client with Explicit Settings Example diff --git a/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_file_search.py b/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_file_search.py index 31c70b3237..f3fc3c852c 100644 --- a/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_file_search.py +++ b/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_file_search.py @@ -6,6 +6,10 @@ from agent_framework import Agent from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure OpenAI Responses Client with File Search Example diff --git a/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_foundry.py b/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_foundry.py index 36b6572427..f7d78683f1 100644 --- a/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_foundry.py +++ b/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_foundry.py @@ -11,6 +11,9 @@ from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure OpenAI Responses Client with Foundry Project Example @@ -23,9 +26,7 @@ - The `azure-ai-projects` package to be installed. - The `AZURE_AI_PROJECT_ENDPOINT` environment variable set to your Foundry project endpoint. - The `AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME` environment variable set to the model deployment name. -""" - -load_dotenv() # Load environment variables from .env file if present +""" # Load environment variables from .env file if present # NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. diff --git a/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_function_tools.py b/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_function_tools.py index 32fc56ed97..1ebda9ce37 100644 --- a/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_function_tools.py +++ b/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_function_tools.py @@ -8,8 +8,12 @@ from agent_framework import Agent, tool from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure OpenAI Responses Client with Function Tools Example diff --git a/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_hosted_mcp.py b/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_hosted_mcp.py index 343b3a61b1..f81bfc83c7 100644 --- a/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_hosted_mcp.py +++ b/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_hosted_mcp.py @@ -6,6 +6,10 @@ from agent_framework import Agent from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure OpenAI Responses Client with Hosted MCP Example diff --git a/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_local_mcp.py b/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_local_mcp.py index 7d8f2466b6..e470d9bfe9 100644 --- a/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_local_mcp.py +++ b/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_local_mcp.py @@ -6,6 +6,10 @@ from agent_framework import Agent, MCPStreamableHTTPTool from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Azure OpenAI Responses Client with local Model Context Protocol (MCP) Example diff --git a/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_session.py b/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_session.py index a406b9969d..b7ed1d4011 100644 --- a/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_session.py +++ b/python/samples/02-agents/providers/azure_openai/azure_responses_client_with_session.py @@ -7,8 +7,12 @@ from agent_framework import Agent, AgentSession, tool from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Azure OpenAI Responses Client with Session Management Example diff --git a/python/samples/02-agents/providers/copilotstudio/copilotstudio_basic.py b/python/samples/02-agents/providers/copilotstudio/copilotstudio_basic.py index 760ed4d127..b5daf2d269 100644 --- a/python/samples/02-agents/providers/copilotstudio/copilotstudio_basic.py +++ b/python/samples/02-agents/providers/copilotstudio/copilotstudio_basic.py @@ -3,6 +3,7 @@ import asyncio from agent_framework.microsoft import CopilotStudioAgent +from dotenv import load_dotenv """ Copilot Studio Agent Basic Example @@ -11,12 +12,16 @@ from environment variables, showing both streaming and non-streaming responses. """ + # Environment variables needed: # COPILOTSTUDIOAGENT__ENVIRONMENTID - Environment ID where your copilot is deployed # COPILOTSTUDIOAGENT__SCHEMANAME - Agent identifier/schema name of your copilot # COPILOTSTUDIOAGENT__AGENTAPPID - Client ID for authentication # COPILOTSTUDIOAGENT__TENANTID - Tenant ID for authentication +# Load environment variables from .env file +load_dotenv() + async def non_streaming_example() -> None: """Example of non-streaming response (get the complete result at once).""" diff --git a/python/samples/02-agents/providers/copilotstudio/copilotstudio_with_explicit_settings.py b/python/samples/02-agents/providers/copilotstudio/copilotstudio_with_explicit_settings.py index 80a260681f..1ad79a19ad 100644 --- a/python/samples/02-agents/providers/copilotstudio/copilotstudio_with_explicit_settings.py +++ b/python/samples/02-agents/providers/copilotstudio/copilotstudio_with_explicit_settings.py @@ -13,6 +13,7 @@ import os from agent_framework.microsoft import CopilotStudioAgent, acquire_token +from dotenv import load_dotenv from microsoft_agents.copilotstudio.client import AgentType, ConnectionSettings, CopilotClient, PowerPlatformCloud """ @@ -22,12 +23,16 @@ token management and custom ConnectionSettings for production environments. """ + # Environment variables needed: # COPILOTSTUDIOAGENT__ENVIRONMENTID - Environment ID where your copilot is deployed # COPILOTSTUDIOAGENT__SCHEMANAME - Agent identifier/schema name of your copilot # COPILOTSTUDIOAGENT__AGENTAPPID - Client ID for authentication # COPILOTSTUDIOAGENT__TENANTID - Tenant ID for authentication +# Load environment variables from .env file +load_dotenv() + async def example_with_connection_settings() -> None: """Example using explicit ConnectionSettings and CopilotClient.""" diff --git a/python/samples/02-agents/providers/github_copilot/github_copilot_basic.py b/python/samples/02-agents/providers/github_copilot/github_copilot_basic.py index 6faacea67c..3a2c4c8eec 100644 --- a/python/samples/02-agents/providers/github_copilot/github_copilot_basic.py +++ b/python/samples/02-agents/providers/github_copilot/github_copilot_basic.py @@ -19,10 +19,16 @@ from agent_framework import tool from agent_framework.github import GitHubCopilotAgent +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. + +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def get_weather( location: Annotated[str, Field(description="The location to get the weather for.")], diff --git a/python/samples/02-agents/providers/github_copilot/github_copilot_with_mcp.py b/python/samples/02-agents/providers/github_copilot/github_copilot_with_mcp.py index 61e9959793..aea9ff1734 100644 --- a/python/samples/02-agents/providers/github_copilot/github_copilot_with_mcp.py +++ b/python/samples/02-agents/providers/github_copilot/github_copilot_with_mcp.py @@ -16,6 +16,10 @@ from agent_framework.github import GitHubCopilotAgent from copilot.types import MCPServerConfig, PermissionRequest, PermissionRequestResult +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() def prompt_permission(request: PermissionRequest, context: dict[str, str]) -> PermissionRequestResult: diff --git a/python/samples/02-agents/providers/github_copilot/github_copilot_with_session.py b/python/samples/02-agents/providers/github_copilot/github_copilot_with_session.py index 4f15aeee34..644104dc35 100644 --- a/python/samples/02-agents/providers/github_copilot/github_copilot_with_session.py +++ b/python/samples/02-agents/providers/github_copilot/github_copilot_with_session.py @@ -17,7 +17,9 @@ from pydantic import Field -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def get_weather( location: Annotated[str, Field(description="The location to get the weather for.")], diff --git a/python/samples/02-agents/providers/ollama/ollama_agent_basic.py b/python/samples/02-agents/providers/ollama/ollama_agent_basic.py index 92b7f47156..28cad484c1 100644 --- a/python/samples/02-agents/providers/ollama/ollama_agent_basic.py +++ b/python/samples/02-agents/providers/ollama/ollama_agent_basic.py @@ -5,6 +5,10 @@ from agent_framework import tool from agent_framework.ollama import OllamaChatClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Ollama Agent Basic Example @@ -19,7 +23,9 @@ """ -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def get_time(location: str) -> str: """Get the current time.""" diff --git a/python/samples/02-agents/providers/ollama/ollama_agent_reasoning.py b/python/samples/02-agents/providers/ollama/ollama_agent_reasoning.py index ee22f5775b..97c24086a0 100644 --- a/python/samples/02-agents/providers/ollama/ollama_agent_reasoning.py +++ b/python/samples/02-agents/providers/ollama/ollama_agent_reasoning.py @@ -3,6 +3,10 @@ import asyncio from agent_framework.ollama import OllamaChatClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Ollama Agent Reasoning Example diff --git a/python/samples/02-agents/providers/ollama/ollama_chat_client.py b/python/samples/02-agents/providers/ollama/ollama_chat_client.py index 2c46831ba0..c92eaa0f55 100644 --- a/python/samples/02-agents/providers/ollama/ollama_chat_client.py +++ b/python/samples/02-agents/providers/ollama/ollama_chat_client.py @@ -5,6 +5,10 @@ from agent_framework import Message, tool from agent_framework.ollama import OllamaChatClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Ollama Chat Client Example @@ -19,7 +23,9 @@ """ -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def get_time(): """Get the current time.""" diff --git a/python/samples/02-agents/providers/ollama/ollama_chat_multimodal.py b/python/samples/02-agents/providers/ollama/ollama_chat_multimodal.py index fb299cc146..bfeb7824fa 100644 --- a/python/samples/02-agents/providers/ollama/ollama_chat_multimodal.py +++ b/python/samples/02-agents/providers/ollama/ollama_chat_multimodal.py @@ -4,6 +4,10 @@ from agent_framework import Content, Message from agent_framework.ollama import OllamaChatClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Ollama Agent Multimodal Example diff --git a/python/samples/02-agents/providers/ollama/ollama_with_openai_chat_client.py b/python/samples/02-agents/providers/ollama/ollama_with_openai_chat_client.py index 140c338192..4069128346 100644 --- a/python/samples/02-agents/providers/ollama/ollama_with_openai_chat_client.py +++ b/python/samples/02-agents/providers/ollama/ollama_with_openai_chat_client.py @@ -7,6 +7,10 @@ from agent_framework import tool from agent_framework.openai import OpenAIChatClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Ollama with OpenAI Chat Client Example @@ -21,7 +25,9 @@ """ -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def get_weather( location: Annotated[str, "The location to get the weather for."], diff --git a/python/samples/02-agents/providers/openai/openai_assistants_basic.py b/python/samples/02-agents/providers/openai/openai_assistants_basic.py index 573b3c260c..3631691474 100644 --- a/python/samples/02-agents/providers/openai/openai_assistants_basic.py +++ b/python/samples/02-agents/providers/openai/openai_assistants_basic.py @@ -7,9 +7,13 @@ from agent_framework import tool from agent_framework.openai import OpenAIAssistantProvider +from dotenv import load_dotenv from openai import AsyncOpenAI from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ OpenAI Assistants Basic Example diff --git a/python/samples/02-agents/providers/openai/openai_assistants_provider_methods.py b/python/samples/02-agents/providers/openai/openai_assistants_provider_methods.py index f74e064002..f479177928 100644 --- a/python/samples/02-agents/providers/openai/openai_assistants_provider_methods.py +++ b/python/samples/02-agents/providers/openai/openai_assistants_provider_methods.py @@ -7,9 +7,13 @@ from agent_framework import tool from agent_framework.openai import OpenAIAssistantProvider +from dotenv import load_dotenv from openai import AsyncOpenAI from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ OpenAI Assistant Provider Methods Example diff --git a/python/samples/02-agents/providers/openai/openai_assistants_with_code_interpreter.py b/python/samples/02-agents/providers/openai/openai_assistants_with_code_interpreter.py index f05264423e..9f43996fc4 100644 --- a/python/samples/02-agents/providers/openai/openai_assistants_with_code_interpreter.py +++ b/python/samples/02-agents/providers/openai/openai_assistants_with_code_interpreter.py @@ -5,6 +5,7 @@ from agent_framework import AgentResponseUpdate, ChatResponseUpdate from agent_framework.openai import OpenAIAssistantProvider, OpenAIAssistantsClient +from dotenv import load_dotenv from openai import AsyncOpenAI from openai.types.beta.threads.runs import ( CodeInterpreterToolCallDelta, @@ -14,6 +15,9 @@ ) from openai.types.beta.threads.runs.code_interpreter_tool_call_delta import CodeInterpreter +# Load environment variables from .env file +load_dotenv() + """ OpenAI Assistants with Code Interpreter Example diff --git a/python/samples/02-agents/providers/openai/openai_assistants_with_existing_assistant.py b/python/samples/02-agents/providers/openai/openai_assistants_with_existing_assistant.py index 4e432f88b2..5716779558 100644 --- a/python/samples/02-agents/providers/openai/openai_assistants_with_existing_assistant.py +++ b/python/samples/02-agents/providers/openai/openai_assistants_with_existing_assistant.py @@ -7,9 +7,13 @@ from agent_framework import tool from agent_framework.openai import OpenAIAssistantProvider +from dotenv import load_dotenv from openai import AsyncOpenAI from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ OpenAI Assistants with Existing Assistant Example @@ -18,7 +22,9 @@ """ -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def get_weather( location: Annotated[str, Field(description="The location to get the weather for.")], diff --git a/python/samples/02-agents/providers/openai/openai_assistants_with_explicit_settings.py b/python/samples/02-agents/providers/openai/openai_assistants_with_explicit_settings.py index aa7b5db6f6..24dfa0e827 100644 --- a/python/samples/02-agents/providers/openai/openai_assistants_with_explicit_settings.py +++ b/python/samples/02-agents/providers/openai/openai_assistants_with_explicit_settings.py @@ -7,9 +7,13 @@ from agent_framework import tool from agent_framework.openai import OpenAIAssistantProvider +from dotenv import load_dotenv from openai import AsyncOpenAI from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ OpenAI Assistants with Explicit Settings Example diff --git a/python/samples/02-agents/providers/openai/openai_assistants_with_file_search.py b/python/samples/02-agents/providers/openai/openai_assistants_with_file_search.py index 505a3a3957..ba6de333c5 100644 --- a/python/samples/02-agents/providers/openai/openai_assistants_with_file_search.py +++ b/python/samples/02-agents/providers/openai/openai_assistants_with_file_search.py @@ -5,8 +5,12 @@ from agent_framework import Content from agent_framework.openai import OpenAIAssistantProvider, OpenAIAssistantsClient +from dotenv import load_dotenv from openai import AsyncOpenAI +# Load environment variables from .env file +load_dotenv() + """ OpenAI Assistants with File Search Example diff --git a/python/samples/02-agents/providers/openai/openai_assistants_with_function_tools.py b/python/samples/02-agents/providers/openai/openai_assistants_with_function_tools.py index 2b406170a6..eebbb07b87 100644 --- a/python/samples/02-agents/providers/openai/openai_assistants_with_function_tools.py +++ b/python/samples/02-agents/providers/openai/openai_assistants_with_function_tools.py @@ -8,9 +8,13 @@ from agent_framework import tool from agent_framework.openai import OpenAIAssistantProvider +from dotenv import load_dotenv from openai import AsyncOpenAI from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ OpenAI Assistants with Function Tools Example @@ -19,7 +23,9 @@ """ -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def get_weather( location: Annotated[str, Field(description="The location to get the weather for.")], diff --git a/python/samples/02-agents/providers/openai/openai_assistants_with_response_format.py b/python/samples/02-agents/providers/openai/openai_assistants_with_response_format.py index 0719ecc7de..79dad58afe 100644 --- a/python/samples/02-agents/providers/openai/openai_assistants_with_response_format.py +++ b/python/samples/02-agents/providers/openai/openai_assistants_with_response_format.py @@ -4,9 +4,13 @@ import os from agent_framework.openai import OpenAIAssistantProvider +from dotenv import load_dotenv from openai import AsyncOpenAI from pydantic import BaseModel, ConfigDict +# Load environment variables from .env file +load_dotenv() + """ OpenAI Assistant Provider Response Format Example diff --git a/python/samples/02-agents/providers/openai/openai_assistants_with_session.py b/python/samples/02-agents/providers/openai/openai_assistants_with_session.py index 39e13745a2..ba55904315 100644 --- a/python/samples/02-agents/providers/openai/openai_assistants_with_session.py +++ b/python/samples/02-agents/providers/openai/openai_assistants_with_session.py @@ -7,9 +7,13 @@ from agent_framework import AgentSession, tool from agent_framework.openai import OpenAIAssistantProvider +from dotenv import load_dotenv from openai import AsyncOpenAI from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ OpenAI Assistants with Session Management Example diff --git a/python/samples/02-agents/providers/openai/openai_chat_client_basic.py b/python/samples/02-agents/providers/openai/openai_chat_client_basic.py index fb7bd42613..5b36460427 100644 --- a/python/samples/02-agents/providers/openai/openai_chat_client_basic.py +++ b/python/samples/02-agents/providers/openai/openai_chat_client_basic.py @@ -6,6 +6,10 @@ from agent_framework import tool from agent_framework.openai import OpenAIChatClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ OpenAI Chat Client Basic Example diff --git a/python/samples/02-agents/providers/openai/openai_chat_client_with_explicit_settings.py b/python/samples/02-agents/providers/openai/openai_chat_client_with_explicit_settings.py index e5b85c31fa..4601557d40 100644 --- a/python/samples/02-agents/providers/openai/openai_chat_client_with_explicit_settings.py +++ b/python/samples/02-agents/providers/openai/openai_chat_client_with_explicit_settings.py @@ -7,8 +7,12 @@ from agent_framework import tool from agent_framework.openai import OpenAIChatClient +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ OpenAI Chat Client with Explicit Settings Example diff --git a/python/samples/02-agents/providers/openai/openai_chat_client_with_function_tools.py b/python/samples/02-agents/providers/openai/openai_chat_client_with_function_tools.py index d66a5cf778..2cdd541d81 100644 --- a/python/samples/02-agents/providers/openai/openai_chat_client_with_function_tools.py +++ b/python/samples/02-agents/providers/openai/openai_chat_client_with_function_tools.py @@ -7,8 +7,12 @@ from agent_framework import Agent, tool from agent_framework.openai import OpenAIChatClient +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ OpenAI Chat Client with Function Tools Example diff --git a/python/samples/02-agents/providers/openai/openai_chat_client_with_local_mcp.py b/python/samples/02-agents/providers/openai/openai_chat_client_with_local_mcp.py index d741a1f6b8..bb06046fa3 100644 --- a/python/samples/02-agents/providers/openai/openai_chat_client_with_local_mcp.py +++ b/python/samples/02-agents/providers/openai/openai_chat_client_with_local_mcp.py @@ -4,6 +4,10 @@ from agent_framework import Agent, MCPStreamableHTTPTool from agent_framework.openai import OpenAIChatClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ OpenAI Chat Client with Local MCP Example diff --git a/python/samples/02-agents/providers/openai/openai_chat_client_with_runtime_json_schema.py b/python/samples/02-agents/providers/openai/openai_chat_client_with_runtime_json_schema.py index f1f39db38a..8045da9e81 100644 --- a/python/samples/02-agents/providers/openai/openai_chat_client_with_runtime_json_schema.py +++ b/python/samples/02-agents/providers/openai/openai_chat_client_with_runtime_json_schema.py @@ -4,6 +4,10 @@ import json from agent_framework.openai import OpenAIChatClient, OpenAIChatOptions +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ OpenAI Chat Client Runtime JSON Schema Example diff --git a/python/samples/02-agents/providers/openai/openai_chat_client_with_session.py b/python/samples/02-agents/providers/openai/openai_chat_client_with_session.py index 6804d18b59..773b18b3cc 100644 --- a/python/samples/02-agents/providers/openai/openai_chat_client_with_session.py +++ b/python/samples/02-agents/providers/openai/openai_chat_client_with_session.py @@ -6,8 +6,12 @@ from agent_framework import Agent, AgentSession, InMemoryHistoryProvider, tool from agent_framework.openai import OpenAIChatClient +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ OpenAI Chat Client with Session Management Example diff --git a/python/samples/02-agents/providers/openai/openai_chat_client_with_web_search.py b/python/samples/02-agents/providers/openai/openai_chat_client_with_web_search.py index bb4ebda143..384bce5aa8 100644 --- a/python/samples/02-agents/providers/openai/openai_chat_client_with_web_search.py +++ b/python/samples/02-agents/providers/openai/openai_chat_client_with_web_search.py @@ -4,6 +4,10 @@ from agent_framework import Agent from agent_framework.openai import OpenAIChatClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ OpenAI Chat Client with Web Search Example diff --git a/python/samples/02-agents/providers/openai/openai_responses_client_basic.py b/python/samples/02-agents/providers/openai/openai_responses_client_basic.py index fa4766e575..c615cf3252 100644 --- a/python/samples/02-agents/providers/openai/openai_responses_client_basic.py +++ b/python/samples/02-agents/providers/openai/openai_responses_client_basic.py @@ -16,8 +16,12 @@ tool, ) from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ OpenAI Responses Client Basic Example diff --git a/python/samples/02-agents/providers/openai/openai_responses_client_image_analysis.py b/python/samples/02-agents/providers/openai/openai_responses_client_image_analysis.py index 7e297524d1..572a487563 100644 --- a/python/samples/02-agents/providers/openai/openai_responses_client_image_analysis.py +++ b/python/samples/02-agents/providers/openai/openai_responses_client_image_analysis.py @@ -4,6 +4,10 @@ from agent_framework import Content from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ OpenAI Responses Client Image Analysis Example diff --git a/python/samples/02-agents/providers/openai/openai_responses_client_image_generation.py b/python/samples/02-agents/providers/openai/openai_responses_client_image_generation.py index e6f54677e4..6ed7a48fd0 100644 --- a/python/samples/02-agents/providers/openai/openai_responses_client_image_generation.py +++ b/python/samples/02-agents/providers/openai/openai_responses_client_image_generation.py @@ -8,6 +8,10 @@ from agent_framework import Content from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ OpenAI Responses Client Image Generation Example diff --git a/python/samples/02-agents/providers/openai/openai_responses_client_reasoning.py b/python/samples/02-agents/providers/openai/openai_responses_client_reasoning.py index d920ba32c6..4e83347fab 100644 --- a/python/samples/02-agents/providers/openai/openai_responses_client_reasoning.py +++ b/python/samples/02-agents/providers/openai/openai_responses_client_reasoning.py @@ -3,6 +3,10 @@ import asyncio from agent_framework.openai import OpenAIResponsesClient, OpenAIResponsesOptions +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ OpenAI Responses Client Reasoning Example diff --git a/python/samples/02-agents/providers/openai/openai_responses_client_streaming_image_generation.py b/python/samples/02-agents/providers/openai/openai_responses_client_streaming_image_generation.py index 6b4c49735d..d256445328 100644 --- a/python/samples/02-agents/providers/openai/openai_responses_client_streaming_image_generation.py +++ b/python/samples/02-agents/providers/openai/openai_responses_client_streaming_image_generation.py @@ -8,6 +8,10 @@ import anyio from agent_framework import Content from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """OpenAI Responses Client Streaming Image Generation Example @@ -75,10 +79,7 @@ async def main(): # represents a progressive refinement, with the last one being the finished result. if content.type == "image_generation_tool_result" and isinstance(content.outputs, Content): image_output: Content = content.outputs - if ( - image_output.type == "data" - and image_output.additional_properties.get("is_partial_image") - ): + if image_output.type == "data" and image_output.additional_properties.get("is_partial_image"): print(f" Image {image_count} received") # Extract file extension from media_type (e.g., "image/png" -> "png") diff --git a/python/samples/02-agents/providers/openai/openai_responses_client_with_agent_as_tool.py b/python/samples/02-agents/providers/openai/openai_responses_client_with_agent_as_tool.py index 774231d0d6..8c858b417f 100644 --- a/python/samples/02-agents/providers/openai/openai_responses_client_with_agent_as_tool.py +++ b/python/samples/02-agents/providers/openai/openai_responses_client_with_agent_as_tool.py @@ -5,6 +5,10 @@ from agent_framework import FunctionInvocationContext from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ OpenAI Responses Client Agent-as-Tool Example diff --git a/python/samples/02-agents/providers/openai/openai_responses_client_with_code_interpreter.py b/python/samples/02-agents/providers/openai/openai_responses_client_with_code_interpreter.py index 915915bc90..c3a8eba82a 100644 --- a/python/samples/02-agents/providers/openai/openai_responses_client_with_code_interpreter.py +++ b/python/samples/02-agents/providers/openai/openai_responses_client_with_code_interpreter.py @@ -7,6 +7,10 @@ Content, ) from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ OpenAI Responses Client with Code Interpreter Example diff --git a/python/samples/02-agents/providers/openai/openai_responses_client_with_code_interpreter_files.py b/python/samples/02-agents/providers/openai/openai_responses_client_with_code_interpreter_files.py index 195c162c5c..1636a22912 100644 --- a/python/samples/02-agents/providers/openai/openai_responses_client_with_code_interpreter_files.py +++ b/python/samples/02-agents/providers/openai/openai_responses_client_with_code_interpreter_files.py @@ -6,8 +6,12 @@ from agent_framework import Agent from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv from openai import AsyncOpenAI +# Load environment variables from .env file +load_dotenv() + """ OpenAI Responses Client with Code Interpreter and Files Example diff --git a/python/samples/02-agents/providers/openai/openai_responses_client_with_explicit_settings.py b/python/samples/02-agents/providers/openai/openai_responses_client_with_explicit_settings.py index 9aeba0f009..f45b5b8778 100644 --- a/python/samples/02-agents/providers/openai/openai_responses_client_with_explicit_settings.py +++ b/python/samples/02-agents/providers/openai/openai_responses_client_with_explicit_settings.py @@ -7,8 +7,12 @@ from agent_framework import tool from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ OpenAI Responses Client with Explicit Settings Example diff --git a/python/samples/02-agents/providers/openai/openai_responses_client_with_file_search.py b/python/samples/02-agents/providers/openai/openai_responses_client_with_file_search.py index 7c1f2fe0ef..b6c9ac352f 100644 --- a/python/samples/02-agents/providers/openai/openai_responses_client_with_file_search.py +++ b/python/samples/02-agents/providers/openai/openai_responses_client_with_file_search.py @@ -4,6 +4,10 @@ from agent_framework import Agent from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ OpenAI Responses Client with File Search Example diff --git a/python/samples/02-agents/providers/openai/openai_responses_client_with_function_tools.py b/python/samples/02-agents/providers/openai/openai_responses_client_with_function_tools.py index 5884467650..55f0ed9e19 100644 --- a/python/samples/02-agents/providers/openai/openai_responses_client_with_function_tools.py +++ b/python/samples/02-agents/providers/openai/openai_responses_client_with_function_tools.py @@ -7,8 +7,12 @@ from agent_framework import Agent, tool from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ OpenAI Responses Client with Function Tools Example diff --git a/python/samples/02-agents/providers/openai/openai_responses_client_with_hosted_mcp.py b/python/samples/02-agents/providers/openai/openai_responses_client_with_hosted_mcp.py index 3b772ebf28..45e7ae736a 100644 --- a/python/samples/02-agents/providers/openai/openai_responses_client_with_hosted_mcp.py +++ b/python/samples/02-agents/providers/openai/openai_responses_client_with_hosted_mcp.py @@ -7,15 +7,18 @@ from agent_framework.openai import OpenAIResponsesClient from dotenv import load_dotenv +if TYPE_CHECKING: + from agent_framework import AgentSession, SupportsAgentRun + +# Load environment variables from .env file +load_dotenv() + """ OpenAI Responses Client with Hosted MCP Example This sample demonstrates integrating hosted Model Context Protocol (MCP) tools with OpenAI Responses Client, including user approval workflows for function call security. """ -load_dotenv() # Load environment variables from .env file if present -if TYPE_CHECKING: - from agent_framework import AgentSession, SupportsAgentRun async def handle_approvals_without_session(query: str, agent: "SupportsAgentRun"): diff --git a/python/samples/02-agents/providers/openai/openai_responses_client_with_local_mcp.py b/python/samples/02-agents/providers/openai/openai_responses_client_with_local_mcp.py index 1b1e55c28d..8f136021bb 100644 --- a/python/samples/02-agents/providers/openai/openai_responses_client_with_local_mcp.py +++ b/python/samples/02-agents/providers/openai/openai_responses_client_with_local_mcp.py @@ -4,6 +4,10 @@ from agent_framework import Agent, MCPStreamableHTTPTool from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ OpenAI Responses Client with Local MCP Example diff --git a/python/samples/02-agents/providers/openai/openai_responses_client_with_runtime_json_schema.py b/python/samples/02-agents/providers/openai/openai_responses_client_with_runtime_json_schema.py index 106a721e0f..8a08e50a31 100644 --- a/python/samples/02-agents/providers/openai/openai_responses_client_with_runtime_json_schema.py +++ b/python/samples/02-agents/providers/openai/openai_responses_client_with_runtime_json_schema.py @@ -4,6 +4,10 @@ import json from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ OpenAI Chat Client Runtime JSON Schema Example diff --git a/python/samples/02-agents/providers/openai/openai_responses_client_with_session.py b/python/samples/02-agents/providers/openai/openai_responses_client_with_session.py index 30866cc5da..e62c3bdaea 100644 --- a/python/samples/02-agents/providers/openai/openai_responses_client_with_session.py +++ b/python/samples/02-agents/providers/openai/openai_responses_client_with_session.py @@ -6,8 +6,12 @@ from agent_framework import Agent, AgentSession, tool from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ OpenAI Responses Client with Session Management Example diff --git a/python/samples/02-agents/providers/openai/openai_responses_client_with_structured_output.py b/python/samples/02-agents/providers/openai/openai_responses_client_with_structured_output.py index a0b9a01a20..429786245d 100644 --- a/python/samples/02-agents/providers/openai/openai_responses_client_with_structured_output.py +++ b/python/samples/02-agents/providers/openai/openai_responses_client_with_structured_output.py @@ -4,8 +4,12 @@ from agent_framework import AgentResponse from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv from pydantic import BaseModel +# Load environment variables from .env file +load_dotenv() + """ OpenAI Responses Client with Structured Output Example diff --git a/python/samples/02-agents/providers/openai/openai_responses_client_with_web_search.py b/python/samples/02-agents/providers/openai/openai_responses_client_with_web_search.py index 26d148901c..9f22807ba9 100644 --- a/python/samples/02-agents/providers/openai/openai_responses_client_with_web_search.py +++ b/python/samples/02-agents/providers/openai/openai_responses_client_with_web_search.py @@ -4,6 +4,10 @@ from agent_framework import Agent from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ OpenAI Responses Client with Web Search Example diff --git a/python/samples/02-agents/tools/function_invocation_configuration.py b/python/samples/02-agents/tools/function_invocation_configuration.py index 81318484e6..3c3479c87a 100644 --- a/python/samples/02-agents/tools/function_invocation_configuration.py +++ b/python/samples/02-agents/tools/function_invocation_configuration.py @@ -5,6 +5,10 @@ from agent_framework import tool from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ This sample demonstrates how to configure function invocation settings diff --git a/python/samples/02-agents/tools/function_tool_declaration_only.py b/python/samples/02-agents/tools/function_tool_declaration_only.py index f081e0823e..2d7c54c791 100644 --- a/python/samples/02-agents/tools/function_tool_declaration_only.py +++ b/python/samples/02-agents/tools/function_tool_declaration_only.py @@ -4,6 +4,10 @@ from agent_framework import FunctionTool from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Example of how to create a function that only consists of a declaration without an implementation. @@ -72,5 +76,4 @@ async def main(): if __name__ == "__main__": - asyncio.run(main()) diff --git a/python/samples/02-agents/tools/function_tool_from_dict_with_dependency_injection.py b/python/samples/02-agents/tools/function_tool_from_dict_with_dependency_injection.py index 126d937f43..39eef147be 100644 --- a/python/samples/02-agents/tools/function_tool_from_dict_with_dependency_injection.py +++ b/python/samples/02-agents/tools/function_tool_from_dict_with_dependency_injection.py @@ -23,6 +23,10 @@ from agent_framework import FunctionTool from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() definition = { "type": "function_tool", diff --git a/python/samples/02-agents/tools/function_tool_recover_from_failures.py b/python/samples/02-agents/tools/function_tool_recover_from_failures.py index 8f1cde5d14..527a35c79a 100644 --- a/python/samples/02-agents/tools/function_tool_recover_from_failures.py +++ b/python/samples/02-agents/tools/function_tool_recover_from_failures.py @@ -5,6 +5,10 @@ from agent_framework import tool from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Tool exceptions handled by returning the error for the agent to recover from. @@ -14,7 +18,9 @@ """ -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def greet(name: Annotated[str, "Name to greet"]) -> str: """Greet someone.""" diff --git a/python/samples/02-agents/tools/function_tool_with_approval.py b/python/samples/02-agents/tools/function_tool_with_approval.py index e87b3da462..3a2a565ed4 100644 --- a/python/samples/02-agents/tools/function_tool_with_approval.py +++ b/python/samples/02-agents/tools/function_tool_with_approval.py @@ -6,6 +6,7 @@ from agent_framework import Agent, AgentResponse, Message, tool from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv if TYPE_CHECKING: from agent_framework import SupportsAgentRun @@ -17,10 +18,15 @@ It shows how to handle function call approvals without using threads. """ +# Load environment variables from .env file +load_dotenv() + conditions = ["sunny", "cloudy", "raining", "snowing", "clear"] -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def get_weather(location: Annotated[str, "The city and state, e.g. San Francisco, CA"]) -> str: """Get the current weather for a given location.""" diff --git a/python/samples/02-agents/tools/function_tool_with_approval_and_sessions.py b/python/samples/02-agents/tools/function_tool_with_approval_and_sessions.py index 6acb3383d6..089eb7dbdd 100644 --- a/python/samples/02-agents/tools/function_tool_with_approval_and_sessions.py +++ b/python/samples/02-agents/tools/function_tool_with_approval_and_sessions.py @@ -6,6 +6,10 @@ from agent_framework import Agent, Message, tool from agent_framework.azure import AzureOpenAIChatClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Tool Approvals with Sessions @@ -17,9 +21,7 @@ @tool(approval_mode="always_require") -def add_to_calendar( - event_name: Annotated[str, "Name of the event"], date: Annotated[str, "Date of the event"] -) -> str: +def add_to_calendar(event_name: Annotated[str, "Name of the event"], date: Annotated[str, "Date of the event"]) -> str: """Add an event to the calendar (requires approval).""" print(f">>> EXECUTING: add_to_calendar(event_name='{event_name}', date='{date}')") return f"Added '{event_name}' to calendar on {date}" diff --git a/python/samples/02-agents/tools/function_tool_with_explicit_schema.py b/python/samples/02-agents/tools/function_tool_with_explicit_schema.py index 6b0a812660..10fbde187f 100644 --- a/python/samples/02-agents/tools/function_tool_with_explicit_schema.py +++ b/python/samples/02-agents/tools/function_tool_with_explicit_schema.py @@ -19,8 +19,12 @@ from agent_framework import tool from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv from pydantic import BaseModel, Field +# Load environment variables from .env file +load_dotenv() + # Approach 1: Pydantic model as explicit schema class WeatherInput(BaseModel): diff --git a/python/samples/02-agents/tools/function_tool_with_kwargs.py b/python/samples/02-agents/tools/function_tool_with_kwargs.py index 15dd597354..249ebc4a33 100644 --- a/python/samples/02-agents/tools/function_tool_with_kwargs.py +++ b/python/samples/02-agents/tools/function_tool_with_kwargs.py @@ -5,8 +5,12 @@ from agent_framework import tool from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ AI Function with kwargs Example @@ -20,7 +24,9 @@ # Define the function tool with **kwargs to accept injected arguments -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def get_weather( location: Annotated[str, Field(description="The location to get the weather for.")], diff --git a/python/samples/02-agents/tools/function_tool_with_max_exceptions.py b/python/samples/02-agents/tools/function_tool_with_max_exceptions.py index 4c7d2c5b47..7830b53794 100644 --- a/python/samples/02-agents/tools/function_tool_with_max_exceptions.py +++ b/python/samples/02-agents/tools/function_tool_with_max_exceptions.py @@ -5,6 +5,10 @@ from agent_framework import tool from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Some tools are very expensive to run, so you may want to limit the number of times diff --git a/python/samples/02-agents/tools/function_tool_with_max_invocations.py b/python/samples/02-agents/tools/function_tool_with_max_invocations.py index eedefefd82..1619cb4046 100644 --- a/python/samples/02-agents/tools/function_tool_with_max_invocations.py +++ b/python/samples/02-agents/tools/function_tool_with_max_invocations.py @@ -5,6 +5,10 @@ from agent_framework import tool from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ For tools you can specify if there is a maximum number of invocations allowed. diff --git a/python/samples/02-agents/tools/function_tool_with_session_injection.py b/python/samples/02-agents/tools/function_tool_with_session_injection.py index e12f97cec5..2689ff5f9c 100644 --- a/python/samples/02-agents/tools/function_tool_with_session_injection.py +++ b/python/samples/02-agents/tools/function_tool_with_session_injection.py @@ -5,8 +5,12 @@ from agent_framework import AgentSession, tool from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ AI Function with Session Injection Example @@ -16,7 +20,9 @@ # Define the function tool with **kwargs -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") async def get_weather( location: Annotated[str, Field(description="The location to get the weather for.")], diff --git a/python/samples/02-agents/tools/tool_in_class.py b/python/samples/02-agents/tools/tool_in_class.py index 757acbe1a3..61f3230148 100644 --- a/python/samples/02-agents/tools/tool_in_class.py +++ b/python/samples/02-agents/tools/tool_in_class.py @@ -5,6 +5,10 @@ from agent_framework import tool from agent_framework.openai import OpenAIResponsesClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ This sample demonstrates using tool within a class, diff --git a/python/samples/02-agents/typed_options.py b/python/samples/02-agents/typed_options.py index 58bb116055..65e59ec3d4 100644 --- a/python/samples/02-agents/typed_options.py +++ b/python/samples/02-agents/typed_options.py @@ -6,6 +6,10 @@ from agent_framework import Agent from agent_framework.anthropic import AnthropicClient from agent_framework.openai import OpenAIChatClient, OpenAIChatOptions +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """TypedDict-based Chat Options. diff --git a/python/samples/03-workflows/_start-here/step2_agents_in_a_workflow.py b/python/samples/03-workflows/_start-here/step2_agents_in_a_workflow.py index 5330cf4973..6ace56da55 100644 --- a/python/samples/03-workflows/_start-here/step2_agents_in_a_workflow.py +++ b/python/samples/03-workflows/_start-here/step2_agents_in_a_workflow.py @@ -7,6 +7,10 @@ from agent_framework import AgentResponse, WorkflowBuilder from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Step 2: Agents in a Workflow non-streaming diff --git a/python/samples/03-workflows/_start-here/step3_streaming.py b/python/samples/03-workflows/_start-here/step3_streaming.py index 15e3512c02..1850cfc4a4 100644 --- a/python/samples/03-workflows/_start-here/step3_streaming.py +++ b/python/samples/03-workflows/_start-here/step3_streaming.py @@ -6,6 +6,10 @@ from agent_framework import AgentResponseUpdate, Message, WorkflowBuilder from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Step 3: Agents in a workflow with streaming diff --git a/python/samples/03-workflows/agents/azure_ai_agents_streaming.py b/python/samples/03-workflows/agents/azure_ai_agents_streaming.py index ccca56cf36..bac2506468 100644 --- a/python/samples/03-workflows/agents/azure_ai_agents_streaming.py +++ b/python/samples/03-workflows/agents/azure_ai_agents_streaming.py @@ -6,6 +6,10 @@ from agent_framework import AgentResponseUpdate, WorkflowBuilder from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Sample: Azure AI Agents in a Workflow with Streaming diff --git a/python/samples/03-workflows/agents/azure_ai_agents_with_shared_session.py b/python/samples/03-workflows/agents/azure_ai_agents_with_shared_session.py index be91a5345a..7a69892a77 100644 --- a/python/samples/03-workflows/agents/azure_ai_agents_with_shared_session.py +++ b/python/samples/03-workflows/agents/azure_ai_agents_with_shared_session.py @@ -15,6 +15,10 @@ ) from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Sample: Agents with a shared thread in a workflow diff --git a/python/samples/03-workflows/agents/azure_chat_agents_and_executor.py b/python/samples/03-workflows/agents/azure_chat_agents_and_executor.py index ed724332b9..76436a0ce1 100644 --- a/python/samples/03-workflows/agents/azure_chat_agents_and_executor.py +++ b/python/samples/03-workflows/agents/azure_chat_agents_and_executor.py @@ -15,6 +15,10 @@ ) from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Sample: AzureOpenAI Chat Agents and an Executor in a Workflow with Streaming diff --git a/python/samples/03-workflows/agents/azure_chat_agents_streaming.py b/python/samples/03-workflows/agents/azure_chat_agents_streaming.py index a18a6e7086..13c20a0a57 100644 --- a/python/samples/03-workflows/agents/azure_chat_agents_streaming.py +++ b/python/samples/03-workflows/agents/azure_chat_agents_streaming.py @@ -6,6 +6,10 @@ from agent_framework import AgentResponseUpdate, WorkflowBuilder from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Sample: AzureOpenAI Chat Agents in a Workflow with Streaming diff --git a/python/samples/03-workflows/agents/azure_chat_agents_tool_calls_with_feedback.py b/python/samples/03-workflows/agents/azure_chat_agents_tool_calls_with_feedback.py index fb50e26491..fdcc626099 100644 --- a/python/samples/03-workflows/agents/azure_chat_agents_tool_calls_with_feedback.py +++ b/python/samples/03-workflows/agents/azure_chat_agents_tool_calls_with_feedback.py @@ -24,9 +24,13 @@ ) from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field from typing_extensions import Never +# Load environment variables from .env file +load_dotenv() + """ Sample: Tool-enabled agents with human feedback diff --git a/python/samples/03-workflows/agents/concurrent_workflow_as_agent.py b/python/samples/03-workflows/agents/concurrent_workflow_as_agent.py index de465eba15..48c3155edd 100644 --- a/python/samples/03-workflows/agents/concurrent_workflow_as_agent.py +++ b/python/samples/03-workflows/agents/concurrent_workflow_as_agent.py @@ -6,6 +6,10 @@ from agent_framework.azure import AzureOpenAIResponsesClient from agent_framework.orchestrations import ConcurrentBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Sample: Build a concurrent workflow orchestration and wrap it as an agent. diff --git a/python/samples/03-workflows/agents/custom_agent_executors.py b/python/samples/03-workflows/agents/custom_agent_executors.py index 3d6b34a2eb..4534ebe39e 100644 --- a/python/samples/03-workflows/agents/custom_agent_executors.py +++ b/python/samples/03-workflows/agents/custom_agent_executors.py @@ -13,6 +13,10 @@ ) from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Sample: Custom Agent Executors in a Workflow diff --git a/python/samples/03-workflows/agents/group_chat_workflow_as_agent.py b/python/samples/03-workflows/agents/group_chat_workflow_as_agent.py index f5da892d6d..05994723cb 100644 --- a/python/samples/03-workflows/agents/group_chat_workflow_as_agent.py +++ b/python/samples/03-workflows/agents/group_chat_workflow_as_agent.py @@ -7,6 +7,10 @@ from agent_framework.azure import AzureOpenAIResponsesClient from agent_framework.orchestrations import GroupChatBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Sample: Group Chat Orchestration diff --git a/python/samples/03-workflows/agents/handoff_workflow_as_agent.py b/python/samples/03-workflows/agents/handoff_workflow_as_agent.py index 9eaa0549ec..f059009a8e 100644 --- a/python/samples/03-workflows/agents/handoff_workflow_as_agent.py +++ b/python/samples/03-workflows/agents/handoff_workflow_as_agent.py @@ -15,6 +15,10 @@ from agent_framework.azure import AzureOpenAIResponsesClient from agent_framework.orchestrations import HandoffAgentUserRequest, HandoffBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """Sample: Handoff Workflow as Agent with Human-in-the-Loop. diff --git a/python/samples/03-workflows/agents/magentic_workflow_as_agent.py b/python/samples/03-workflows/agents/magentic_workflow_as_agent.py index ecceeeacd4..833d89cd19 100644 --- a/python/samples/03-workflows/agents/magentic_workflow_as_agent.py +++ b/python/samples/03-workflows/agents/magentic_workflow_as_agent.py @@ -9,6 +9,10 @@ from agent_framework.azure import AzureOpenAIResponsesClient from agent_framework.orchestrations import MagenticBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Sample: Build a Magentic orchestration and wrap it as an agent. diff --git a/python/samples/03-workflows/agents/sequential_workflow_as_agent.py b/python/samples/03-workflows/agents/sequential_workflow_as_agent.py index 1b2a6c6af4..74f4fc568b 100644 --- a/python/samples/03-workflows/agents/sequential_workflow_as_agent.py +++ b/python/samples/03-workflows/agents/sequential_workflow_as_agent.py @@ -6,6 +6,10 @@ from agent_framework.azure import AzureOpenAIResponsesClient from agent_framework.orchestrations import SequentialBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Sample: Build a sequential workflow orchestration and wrap it as an agent. diff --git a/python/samples/03-workflows/agents/workflow_as_agent_human_in_the_loop.py b/python/samples/03-workflows/agents/workflow_as_agent_human_in_the_loop.py index 30b80b2adf..fc6bd2c0de 100644 --- a/python/samples/03-workflows/agents/workflow_as_agent_human_in_the_loop.py +++ b/python/samples/03-workflows/agents/workflow_as_agent_human_in_the_loop.py @@ -10,6 +10,7 @@ from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv # Ensure local package can be imported when running as a script. _SAMPLES_ROOT = Path(__file__).resolve().parents[3] @@ -55,6 +56,9 @@ workflow_as_agent_reflection.py. """ +# Load environment variables from .env file +load_dotenv() + @dataclass class HumanReviewRequest: diff --git a/python/samples/03-workflows/agents/workflow_as_agent_kwargs.py b/python/samples/03-workflows/agents/workflow_as_agent_kwargs.py index 539fdfc540..eb46578b67 100644 --- a/python/samples/03-workflows/agents/workflow_as_agent_kwargs.py +++ b/python/samples/03-workflows/agents/workflow_as_agent_kwargs.py @@ -9,8 +9,12 @@ from agent_framework.azure import AzureOpenAIResponsesClient from agent_framework.orchestrations import SequentialBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Sample: Workflow as Agent with kwargs Propagation to @tool Tools diff --git a/python/samples/03-workflows/agents/workflow_as_agent_reflection_pattern.py b/python/samples/03-workflows/agents/workflow_as_agent_reflection_pattern.py index e0dde3eacf..4611ac45fa 100644 --- a/python/samples/03-workflows/agents/workflow_as_agent_reflection_pattern.py +++ b/python/samples/03-workflows/agents/workflow_as_agent_reflection_pattern.py @@ -16,8 +16,12 @@ ) from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import BaseModel +# Load environment variables from .env file +load_dotenv() + """ Sample: Workflow as Agent with Reflection and Retry Pattern diff --git a/python/samples/03-workflows/agents/workflow_as_agent_with_session.py b/python/samples/03-workflows/agents/workflow_as_agent_with_session.py index 9137586993..26fb4cff53 100644 --- a/python/samples/03-workflows/agents/workflow_as_agent_with_session.py +++ b/python/samples/03-workflows/agents/workflow_as_agent_with_session.py @@ -7,6 +7,10 @@ from agent_framework.azure import AzureOpenAIResponsesClient from agent_framework.orchestrations import SequentialBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Sample: Workflow as Agent with Session Conversation History and Checkpointing diff --git a/python/samples/03-workflows/checkpoint/checkpoint_with_human_in_the_loop.py b/python/samples/03-workflows/checkpoint/checkpoint_with_human_in_the_loop.py index b26d4dd8e8..ed0f46ee92 100644 --- a/python/samples/03-workflows/checkpoint/checkpoint_with_human_in_the_loop.py +++ b/python/samples/03-workflows/checkpoint/checkpoint_with_human_in_the_loop.py @@ -8,18 +8,6 @@ from pathlib import Path from typing import Any -from azure.identity import AzureCliCredential - -if sys.version_info >= (3, 12): - from typing import override # type: ignore # pragma: no cover -else: - from typing_extensions import override # type: ignore[import] # pragma: no cover - - -# NOTE: the Azure client imports above are real dependencies. When running this -# sample outside of Azure-enabled environments you may wish to swap in the -# `agent_framework.builtin` chat client or mock the writer executor. We keep the -# concrete import here so readers can see an end-to-end configuration. from agent_framework import ( AgentExecutor, AgentExecutorRequest, @@ -34,6 +22,16 @@ response_handler, ) from agent_framework.azure import AzureOpenAIResponsesClient +from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +if sys.version_info >= (3, 12): + from typing import override # type: ignore # pragma: no cover +else: + from typing_extensions import override # type: ignore[import] # pragma: no cover + +# Load environment variables from .env file +load_dotenv() """ Sample: Checkpoint + human-in-the-loop quickstart. diff --git a/python/samples/03-workflows/checkpoint/workflow_as_agent_checkpoint.py b/python/samples/03-workflows/checkpoint/workflow_as_agent_checkpoint.py index f975b19c0c..82a0fc035e 100644 --- a/python/samples/03-workflows/checkpoint/workflow_as_agent_checkpoint.py +++ b/python/samples/03-workflows/checkpoint/workflow_as_agent_checkpoint.py @@ -34,10 +34,15 @@ from agent_framework.azure import AzureOpenAIResponsesClient from agent_framework.orchestrations import SequentialBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() async def basic_checkpointing() -> None: """Demonstrate basic checkpoint storage with workflow-as-agent.""" + print("=" * 60) print("Basic Checkpointing with Workflow as Agent") print("=" * 60) diff --git a/python/samples/03-workflows/composition/sub_workflow_basics.py b/python/samples/03-workflows/composition/sub_workflow_basics.py index fff4efbc7b..8e6f14b5ec 100644 --- a/python/samples/03-workflows/composition/sub_workflow_basics.py +++ b/python/samples/03-workflows/composition/sub_workflow_basics.py @@ -141,10 +141,7 @@ def create_sub_workflow() -> WorkflowExecutor: print("Setting up sub-workflow...") text_processor = TextProcessor() - processing_workflow = ( - WorkflowBuilder(start_executor=text_processor) - .build() - ) + processing_workflow = WorkflowBuilder(start_executor=text_processor).build() return WorkflowExecutor(processing_workflow, id="text_processor_workflow") diff --git a/python/samples/03-workflows/composition/sub_workflow_kwargs.py b/python/samples/03-workflows/composition/sub_workflow_kwargs.py index 47950ea087..b002db1da1 100644 --- a/python/samples/03-workflows/composition/sub_workflow_kwargs.py +++ b/python/samples/03-workflows/composition/sub_workflow_kwargs.py @@ -13,6 +13,10 @@ from agent_framework.azure import AzureOpenAIResponsesClient from agent_framework.orchestrations import SequentialBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Sample: Sub-Workflow kwargs Propagation diff --git a/python/samples/03-workflows/composition/sub_workflow_request_interception.py b/python/samples/03-workflows/composition/sub_workflow_request_interception.py index 4e475f6c3a..61d3273b19 100644 --- a/python/samples/03-workflows/composition/sub_workflow_request_interception.py +++ b/python/samples/03-workflows/composition/sub_workflow_request_interception.py @@ -271,7 +271,9 @@ async def main() -> None: # Build the main workflow smart_email_orchestrator = SmartEmailOrchestrator(id="smart_email_orchestrator", approved_domains=approved_domains) email_delivery = EmailDelivery(id="email_delivery") - email_validation_workflow = WorkflowExecutor(build_email_address_validation_workflow(), id="email_validation_workflow") + email_validation_workflow = WorkflowExecutor( + build_email_address_validation_workflow(), id="email_validation_workflow" + ) workflow = ( WorkflowBuilder(start_executor=smart_email_orchestrator) diff --git a/python/samples/03-workflows/control-flow/edge_condition.py b/python/samples/03-workflows/control-flow/edge_condition.py index 01fdd9a256..73476c61a8 100644 --- a/python/samples/03-workflows/control-flow/edge_condition.py +++ b/python/samples/03-workflows/control-flow/edge_condition.py @@ -16,9 +16,13 @@ ) from agent_framework.azure import AzureOpenAIResponsesClient # Thin client wrapper for Azure OpenAI chat models from azure.identity import AzureCliCredential # Uses your az CLI login for credentials +from dotenv import load_dotenv from pydantic import BaseModel # Structured outputs for safer parsing from typing_extensions import Never +# Load environment variables from .env file +load_dotenv() + """ Sample: Conditional routing with structured outputs diff --git a/python/samples/03-workflows/control-flow/multi_selection_edge_group.py b/python/samples/03-workflows/control-flow/multi_selection_edge_group.py index 05002a2f0c..0b3d4ae43f 100644 --- a/python/samples/03-workflows/control-flow/multi_selection_edge_group.py +++ b/python/samples/03-workflows/control-flow/multi_selection_edge_group.py @@ -22,9 +22,13 @@ ) from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import BaseModel from typing_extensions import Never +# Load environment variables from .env file +load_dotenv() + """ Sample: Multi-Selection Edge Group for email triage and response. diff --git a/python/samples/03-workflows/control-flow/sequential_executors.py b/python/samples/03-workflows/control-flow/sequential_executors.py index 77b33c5af6..5f1f5497dd 100644 --- a/python/samples/03-workflows/control-flow/sequential_executors.py +++ b/python/samples/03-workflows/control-flow/sequential_executors.py @@ -66,9 +66,7 @@ async def main() -> None: reverse_text_executor = ReverseTextExecutor(id="reverse_text_executor") workflow = ( - WorkflowBuilder(start_executor=upper_case_executor) - .add_edge(upper_case_executor, reverse_text_executor) - .build() + WorkflowBuilder(start_executor=upper_case_executor).add_edge(upper_case_executor, reverse_text_executor).build() ) # Step 2: Stream events for a single input. diff --git a/python/samples/03-workflows/control-flow/sequential_streaming.py b/python/samples/03-workflows/control-flow/sequential_streaming.py index 40244499ed..94b5bec210 100644 --- a/python/samples/03-workflows/control-flow/sequential_streaming.py +++ b/python/samples/03-workflows/control-flow/sequential_streaming.py @@ -55,11 +55,7 @@ async def main(): """Build a two-step sequential workflow and run it with streaming to observe events.""" # Step 1: Build the workflow with the defined edges. # Order matters. upper_case_executor runs first, then reverse_text_executor. - workflow = ( - WorkflowBuilder(start_executor=to_upper_case) - .add_edge(to_upper_case, reverse_text) - .build() - ) + workflow = WorkflowBuilder(start_executor=to_upper_case).add_edge(to_upper_case, reverse_text).build() # Step 2: Run the workflow and stream events in real time. async for event in workflow.run("hello world", stream=True): diff --git a/python/samples/03-workflows/control-flow/simple_loop.py b/python/samples/03-workflows/control-flow/simple_loop.py index 571d90c70b..23bd3f2c70 100644 --- a/python/samples/03-workflows/control-flow/simple_loop.py +++ b/python/samples/03-workflows/control-flow/simple_loop.py @@ -18,6 +18,10 @@ ) from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Sample: Simple Loop (with an Agent Judge) diff --git a/python/samples/03-workflows/control-flow/switch_case_edge_group.py b/python/samples/03-workflows/control-flow/switch_case_edge_group.py index 994796e096..ccc8c57aca 100644 --- a/python/samples/03-workflows/control-flow/switch_case_edge_group.py +++ b/python/samples/03-workflows/control-flow/switch_case_edge_group.py @@ -20,9 +20,13 @@ ) from agent_framework.azure import AzureOpenAIResponsesClient # Thin client for Azure OpenAI chat models from azure.identity import AzureCliCredential # Uses your az CLI login for credentials +from dotenv import load_dotenv from pydantic import BaseModel # Structured outputs with validation from typing_extensions import Never +# Load environment variables from .env file +load_dotenv() + """ Sample: Switch-Case Edge Group with an explicit Uncertain branch. diff --git a/python/samples/03-workflows/declarative/customer_support/main.py b/python/samples/03-workflows/declarative/customer_support/main.py index 8c9940c33c..5d38725040 100644 --- a/python/samples/03-workflows/declarative/customer_support/main.py +++ b/python/samples/03-workflows/declarative/customer_support/main.py @@ -34,11 +34,16 @@ WorkflowFactory, ) from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import BaseModel, Field from ticketing_plugin import TicketingPlugin logging.basicConfig(level=logging.ERROR) +# Load environment variables from .env file +load_dotenv() + + # ANSI color codes for output formatting CYAN = "\033[36m" GREEN = "\033[32m" @@ -118,8 +123,6 @@ # Pydantic models for structured outputs - - class SelfServiceResponse(BaseModel): """Response from self-service agent evaluation.""" diff --git a/python/samples/03-workflows/declarative/deep_research/main.py b/python/samples/03-workflows/declarative/deep_research/main.py index bb3dcc6f0d..ac57e632c3 100644 --- a/python/samples/03-workflows/declarative/deep_research/main.py +++ b/python/samples/03-workflows/declarative/deep_research/main.py @@ -28,10 +28,13 @@ from agent_framework.azure import AzureOpenAIResponsesClient from agent_framework.declarative import WorkflowFactory from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import BaseModel, Field -# Agent Instructions +# Load environment variables from .env file +load_dotenv() +# Agent Instructions RESEARCH_INSTRUCTIONS = """In order to help begin addressing the user request, please answer the following pre-survey to the best of your ability. Keep in mind that you are Ken Jennings-level with trivia, and Mensa-level with puzzles, so there should be a deep well to draw from. @@ -92,8 +95,6 @@ # Pydantic models for structured outputs - - class ReasonedAnswer(BaseModel): """A response with reasoning and answer.""" diff --git a/python/samples/03-workflows/declarative/function_tools/main.py b/python/samples/03-workflows/declarative/function_tools/main.py index 521639b1ad..4606afcefb 100644 --- a/python/samples/03-workflows/declarative/function_tools/main.py +++ b/python/samples/03-workflows/declarative/function_tools/main.py @@ -15,8 +15,12 @@ from agent_framework.azure import AzureOpenAIResponsesClient from agent_framework_declarative import ExternalInputRequest, ExternalInputResponse, WorkflowFactory from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + TEMP_DIR = Path(__file__).with_suffix("").parent / "tmp" / "checkpoints" TEMP_DIR.mkdir(parents=True, exist_ok=True) @@ -39,7 +43,9 @@ class MenuItem: ] -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def get_menu() -> list[dict[str, Any]]: """Get all menu items.""" diff --git a/python/samples/03-workflows/declarative/marketing/main.py b/python/samples/03-workflows/declarative/marketing/main.py index f59b19947e..26fcbd54dd 100644 --- a/python/samples/03-workflows/declarative/marketing/main.py +++ b/python/samples/03-workflows/declarative/marketing/main.py @@ -19,6 +19,10 @@ from agent_framework.azure import AzureOpenAIResponsesClient from agent_framework.declarative import WorkflowFactory from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() ANALYST_INSTRUCTIONS = """You are a product analyst. Analyze the given product and identify: 1. Key features and benefits diff --git a/python/samples/03-workflows/declarative/student_teacher/main.py b/python/samples/03-workflows/declarative/student_teacher/main.py index 1984265aa8..815821d348 100644 --- a/python/samples/03-workflows/declarative/student_teacher/main.py +++ b/python/samples/03-workflows/declarative/student_teacher/main.py @@ -26,6 +26,10 @@ from agent_framework.azure import AzureOpenAIResponsesClient from agent_framework.declarative import WorkflowFactory from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() STUDENT_INSTRUCTIONS = """You are a curious math student working on understanding mathematical concepts. When given a problem: diff --git a/python/samples/03-workflows/human-in-the-loop/agents_with_HITL.py b/python/samples/03-workflows/human-in-the-loop/agents_with_HITL.py index 9330ba470c..ed5fd77ce2 100644 --- a/python/samples/03-workflows/human-in-the-loop/agents_with_HITL.py +++ b/python/samples/03-workflows/human-in-the-loop/agents_with_HITL.py @@ -20,8 +20,12 @@ ) from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv from typing_extensions import Never +# Load environment variables from .env file +load_dotenv() + """ Sample: Azure AI Agents in workflow with human feedback diff --git a/python/samples/03-workflows/human-in-the-loop/agents_with_approval_requests.py b/python/samples/03-workflows/human-in-the-loop/agents_with_approval_requests.py index 7d0c050457..83b0632f88 100644 --- a/python/samples/03-workflows/human-in-the-loop/agents_with_approval_requests.py +++ b/python/samples/03-workflows/human-in-the-loop/agents_with_approval_requests.py @@ -18,8 +18,12 @@ ) from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv from typing_extensions import Never +# Load environment variables from .env file +load_dotenv() + """ Sample: Agents in a workflow with AI functions requiring approval @@ -196,12 +200,7 @@ def __init__(self, special_email_addresses: set[str]) -> None: @handler async def preprocess(self, email: Email, ctx: WorkflowContext[str]) -> None: """Preprocess the incoming email.""" - email_payload = ( - f"Incoming email:\n" - f"From: {email.sender}\n" - f"Subject: {email.subject}\n" - f"Body: {email.body}" - ) + email_payload = f"Incoming email:\nFrom: {email.sender}\nSubject: {email.subject}\nBody: {email.body}" message = email_payload if email.sender in self.special_email_addresses: note = ( diff --git a/python/samples/03-workflows/human-in-the-loop/agents_with_declaration_only_tools.py b/python/samples/03-workflows/human-in-the-loop/agents_with_declaration_only_tools.py index a9a68593be..46cec3977e 100644 --- a/python/samples/03-workflows/human-in-the-loop/agents_with_declaration_only_tools.py +++ b/python/samples/03-workflows/human-in-the-loop/agents_with_declaration_only_tools.py @@ -29,6 +29,10 @@ from agent_framework import Content, FunctionTool, WorkflowBuilder from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() # A declaration-only tool: the schema is sent to the LLM, but the framework # has no implementation to execute. The caller must supply the result. diff --git a/python/samples/03-workflows/human-in-the-loop/concurrent_request_info.py b/python/samples/03-workflows/human-in-the-loop/concurrent_request_info.py index 80a98df1bb..74e059b9f8 100644 --- a/python/samples/03-workflows/human-in-the-loop/concurrent_request_info.py +++ b/python/samples/03-workflows/human-in-the-loop/concurrent_request_info.py @@ -35,6 +35,10 @@ from agent_framework.azure import AzureOpenAIResponsesClient from agent_framework.orchestrations import AgentRequestInfoResponse, ConcurrentBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() # Store chat client at module level for aggregator access _chat_client: AzureOpenAIResponsesClient | None = None diff --git a/python/samples/03-workflows/human-in-the-loop/group_chat_request_info.py b/python/samples/03-workflows/human-in-the-loop/group_chat_request_info.py index 40186ac7fd..8d1e4a0192 100644 --- a/python/samples/03-workflows/human-in-the-loop/group_chat_request_info.py +++ b/python/samples/03-workflows/human-in-the-loop/group_chat_request_info.py @@ -36,11 +36,14 @@ from agent_framework.azure import AzureOpenAIResponsesClient from agent_framework.orchestrations import AgentRequestInfoResponse, GroupChatBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() async def process_event_stream(stream: AsyncIterable[WorkflowEvent]) -> dict[str, AgentRequestInfoResponse] | None: """Process events from the workflow stream to capture human feedback requests.""" - requests: dict[str, AgentExecutorResponse] = {} async for event in stream: if event.type == "request_info" and isinstance(event.data, AgentExecutorResponse): diff --git a/python/samples/03-workflows/human-in-the-loop/guessing_game_with_human_input.py b/python/samples/03-workflows/human-in-the-loop/guessing_game_with_human_input.py index 3ceb284ed6..06e9a738f5 100644 --- a/python/samples/03-workflows/human-in-the-loop/guessing_game_with_human_input.py +++ b/python/samples/03-workflows/human-in-the-loop/guessing_game_with_human_input.py @@ -19,8 +19,12 @@ ) from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import BaseModel +# Load environment variables from .env file +load_dotenv() + """ Sample: Human in the loop guessing game diff --git a/python/samples/03-workflows/human-in-the-loop/sequential_request_info.py b/python/samples/03-workflows/human-in-the-loop/sequential_request_info.py index 633f218632..cfee77276d 100644 --- a/python/samples/03-workflows/human-in-the-loop/sequential_request_info.py +++ b/python/samples/03-workflows/human-in-the-loop/sequential_request_info.py @@ -35,11 +35,14 @@ from agent_framework.azure import AzureOpenAIResponsesClient from agent_framework.orchestrations import AgentRequestInfoResponse, SequentialBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() async def process_event_stream(stream: AsyncIterable[WorkflowEvent]) -> dict[str, AgentRequestInfoResponse] | None: """Process events from the workflow stream to capture human feedback requests.""" - requests: dict[str, AgentExecutorResponse] = {} async for event in stream: if event.type == "request_info" and isinstance(event.data, AgentExecutorResponse): diff --git a/python/samples/03-workflows/orchestrations/concurrent_agents.py b/python/samples/03-workflows/orchestrations/concurrent_agents.py index 2d216a131b..f6aae589a6 100644 --- a/python/samples/03-workflows/orchestrations/concurrent_agents.py +++ b/python/samples/03-workflows/orchestrations/concurrent_agents.py @@ -7,6 +7,10 @@ from agent_framework.azure import AzureOpenAIChatClient from agent_framework.orchestrations import ConcurrentBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Sample: Concurrent fan-out/fan-in (agent-only API) with default aggregator diff --git a/python/samples/03-workflows/orchestrations/concurrent_custom_agent_executors.py b/python/samples/03-workflows/orchestrations/concurrent_custom_agent_executors.py index bd3b8b93a5..82df710435 100644 --- a/python/samples/03-workflows/orchestrations/concurrent_custom_agent_executors.py +++ b/python/samples/03-workflows/orchestrations/concurrent_custom_agent_executors.py @@ -15,6 +15,10 @@ from agent_framework.azure import AzureOpenAIChatClient from agent_framework.orchestrations import ConcurrentBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Sample: Concurrent Orchestration with Custom Agent Executors diff --git a/python/samples/03-workflows/orchestrations/concurrent_custom_aggregator.py b/python/samples/03-workflows/orchestrations/concurrent_custom_aggregator.py index 17b1496e0b..3014a0e3cf 100644 --- a/python/samples/03-workflows/orchestrations/concurrent_custom_aggregator.py +++ b/python/samples/03-workflows/orchestrations/concurrent_custom_aggregator.py @@ -7,6 +7,10 @@ from agent_framework.azure import AzureOpenAIChatClient from agent_framework.orchestrations import ConcurrentBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Sample: Concurrent Orchestration with Custom Aggregator @@ -86,9 +90,7 @@ async def summarize_results(results: list[Any]) -> str: # • Default aggregator -> returns list[Message] (one user + one assistant per agent) # • Custom callback -> return value becomes workflow output (string here) # The callback can be sync or async; it receives list[AgentExecutorResponse]. - workflow = ( - ConcurrentBuilder(participants=[researcher, marketer, legal]).with_aggregator(summarize_results).build() - ) + workflow = ConcurrentBuilder(participants=[researcher, marketer, legal]).with_aggregator(summarize_results).build() events = await workflow.run("We are launching a new budget-friendly electric bike for urban commuters.") outputs = events.get_outputs() diff --git a/python/samples/03-workflows/orchestrations/group_chat_agent_manager.py b/python/samples/03-workflows/orchestrations/group_chat_agent_manager.py index 78eb8535ae..d057756160 100644 --- a/python/samples/03-workflows/orchestrations/group_chat_agent_manager.py +++ b/python/samples/03-workflows/orchestrations/group_chat_agent_manager.py @@ -11,6 +11,10 @@ from agent_framework.azure import AzureOpenAIChatClient from agent_framework.orchestrations import GroupChatBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Sample: Group Chat with Agent-Based Manager diff --git a/python/samples/03-workflows/orchestrations/group_chat_philosophical_debate.py b/python/samples/03-workflows/orchestrations/group_chat_philosophical_debate.py index e4723c01e0..5e55fe9204 100644 --- a/python/samples/03-workflows/orchestrations/group_chat_philosophical_debate.py +++ b/python/samples/03-workflows/orchestrations/group_chat_philosophical_debate.py @@ -12,6 +12,7 @@ from agent_framework.azure import AzureOpenAIChatClient from agent_framework.orchestrations import GroupChatBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv logging.basicConfig(level=logging.WARNING) @@ -40,6 +41,9 @@ - OpenAI environment variables configured for OpenAIChatClient """ +# Load environment variables from .env file +load_dotenv() + def _get_chat_client() -> AzureOpenAIChatClient: return AzureOpenAIChatClient(credential=AzureCliCredential()) diff --git a/python/samples/03-workflows/orchestrations/group_chat_simple_selector.py b/python/samples/03-workflows/orchestrations/group_chat_simple_selector.py index 13cd3d3e5a..cf9b6aa8ec 100644 --- a/python/samples/03-workflows/orchestrations/group_chat_simple_selector.py +++ b/python/samples/03-workflows/orchestrations/group_chat_simple_selector.py @@ -11,6 +11,10 @@ from agent_framework.azure import AzureOpenAIChatClient from agent_framework.orchestrations import GroupChatBuilder, GroupChatState from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Sample: Group Chat with a round-robin speaker selector diff --git a/python/samples/03-workflows/orchestrations/handoff_autonomous.py b/python/samples/03-workflows/orchestrations/handoff_autonomous.py index 997d854ef2..d97006df12 100644 --- a/python/samples/03-workflows/orchestrations/handoff_autonomous.py +++ b/python/samples/03-workflows/orchestrations/handoff_autonomous.py @@ -13,6 +13,7 @@ from agent_framework.azure import AzureOpenAIChatClient from agent_framework.orchestrations import HandoffBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv logging.basicConfig(level=logging.ERROR) @@ -35,6 +36,9 @@ - Turn limits: use `.with_autonomous_mode(turn_limits={agent_name: N})` to cap iterations per agent """ +# Load environment variables from .env file +load_dotenv() + def create_agents( client: AzureOpenAIChatClient, diff --git a/python/samples/03-workflows/orchestrations/handoff_simple.py b/python/samples/03-workflows/orchestrations/handoff_simple.py index 9bfe73491e..5a2319d4d2 100644 --- a/python/samples/03-workflows/orchestrations/handoff_simple.py +++ b/python/samples/03-workflows/orchestrations/handoff_simple.py @@ -14,6 +14,10 @@ from agent_framework.azure import AzureOpenAIChatClient from agent_framework.orchestrations import HandoffAgentUserRequest, HandoffBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """Sample: Simple handoff workflow. diff --git a/python/samples/03-workflows/orchestrations/handoff_with_code_interpreter_file.py b/python/samples/03-workflows/orchestrations/handoff_with_code_interpreter_file.py index 9801d64888..627033e26d 100644 --- a/python/samples/03-workflows/orchestrations/handoff_with_code_interpreter_file.py +++ b/python/samples/03-workflows/orchestrations/handoff_with_code_interpreter_file.py @@ -31,6 +31,10 @@ from agent_framework.azure import AzureOpenAIResponsesClient from agent_framework.orchestrations import HandoffAgentUserRequest, HandoffBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() async def _drain(stream: AsyncIterable[WorkflowEvent]) -> list[WorkflowEvent]: diff --git a/python/samples/03-workflows/orchestrations/handoff_with_tool_approval_checkpoint_resume.py b/python/samples/03-workflows/orchestrations/handoff_with_tool_approval_checkpoint_resume.py index 31ad62f609..1c47b2d1f5 100644 --- a/python/samples/03-workflows/orchestrations/handoff_with_tool_approval_checkpoint_resume.py +++ b/python/samples/03-workflows/orchestrations/handoff_with_tool_approval_checkpoint_resume.py @@ -17,6 +17,10 @@ from agent_framework.azure import AzureOpenAIResponsesClient from agent_framework.orchestrations import HandoffAgentUserRequest, HandoffBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Sample: Handoff Workflow with Tool Approvals + Checkpoint Resume diff --git a/python/samples/03-workflows/orchestrations/magentic.py b/python/samples/03-workflows/orchestrations/magentic.py index e06bcec0f2..2420b74245 100644 --- a/python/samples/03-workflows/orchestrations/magentic.py +++ b/python/samples/03-workflows/orchestrations/magentic.py @@ -13,6 +13,7 @@ ) from agent_framework.openai import OpenAIChatClient, OpenAIResponsesClient from agent_framework.orchestrations import GroupChatRequestSentEvent, MagenticBuilder, MagenticProgressLedger +from dotenv import load_dotenv logging.basicConfig(level=logging.WARNING) logger = logging.getLogger(__name__) @@ -42,6 +43,9 @@ - OpenAI credentials configured for `OpenAIChatClient` and `OpenAIResponsesClient`. """ +# Load environment variables from .env file +load_dotenv() + async def main() -> None: researcher_agent = Agent( diff --git a/python/samples/03-workflows/orchestrations/magentic_checkpoint.py b/python/samples/03-workflows/orchestrations/magentic_checkpoint.py index adce878f0d..940e47759f 100644 --- a/python/samples/03-workflows/orchestrations/magentic_checkpoint.py +++ b/python/samples/03-workflows/orchestrations/magentic_checkpoint.py @@ -17,6 +17,10 @@ from agent_framework.azure import AzureOpenAIChatClient from agent_framework.orchestrations import MagenticBuilder, MagenticPlanReviewRequest from azure.identity._credentials import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Sample: Magentic Orchestration + Checkpointing diff --git a/python/samples/03-workflows/orchestrations/magentic_human_plan_review.py b/python/samples/03-workflows/orchestrations/magentic_human_plan_review.py index 95f8de5f46..d9234026aa 100644 --- a/python/samples/03-workflows/orchestrations/magentic_human_plan_review.py +++ b/python/samples/03-workflows/orchestrations/magentic_human_plan_review.py @@ -13,6 +13,10 @@ ) from agent_framework.openai import OpenAIChatClient from agent_framework.orchestrations import MagenticBuilder, MagenticPlanReviewRequest, MagenticPlanReviewResponse +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Sample: Magentic Orchestration with Human Plan Review diff --git a/python/samples/03-workflows/orchestrations/sequential_agents.py b/python/samples/03-workflows/orchestrations/sequential_agents.py index 7d77ef35c6..6eda11ece9 100644 --- a/python/samples/03-workflows/orchestrations/sequential_agents.py +++ b/python/samples/03-workflows/orchestrations/sequential_agents.py @@ -7,6 +7,10 @@ from agent_framework.azure import AzureOpenAIChatClient from agent_framework.orchestrations import SequentialBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Sample: Sequential workflow (agent-focused API) with shared conversation context diff --git a/python/samples/03-workflows/orchestrations/sequential_custom_executors.py b/python/samples/03-workflows/orchestrations/sequential_custom_executors.py index 7f3e61fe2e..56308d2b5f 100644 --- a/python/samples/03-workflows/orchestrations/sequential_custom_executors.py +++ b/python/samples/03-workflows/orchestrations/sequential_custom_executors.py @@ -13,6 +13,10 @@ from agent_framework.azure import AzureOpenAIChatClient from agent_framework.orchestrations import SequentialBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Sample: Sequential workflow mixing agents and a custom summarizer executor diff --git a/python/samples/03-workflows/parallelism/fan_out_fan_in_edges.py b/python/samples/03-workflows/parallelism/fan_out_fan_in_edges.py index e1722cd9ef..0e45e70ada 100644 --- a/python/samples/03-workflows/parallelism/fan_out_fan_in_edges.py +++ b/python/samples/03-workflows/parallelism/fan_out_fan_in_edges.py @@ -17,8 +17,12 @@ ) from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential # Uses your az CLI login for credentials +from dotenv import load_dotenv from typing_extensions import Never +# Load environment variables from .env file +load_dotenv() + """ Sample: Concurrent fan out and fan in with three domain agents diff --git a/python/samples/03-workflows/state-management/state_with_agents.py b/python/samples/03-workflows/state-management/state_with_agents.py index e09ab23eda..ad2fb7112d 100644 --- a/python/samples/03-workflows/state-management/state_with_agents.py +++ b/python/samples/03-workflows/state-management/state_with_agents.py @@ -18,9 +18,13 @@ ) from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import BaseModel from typing_extensions import Never +# Load environment variables from .env file +load_dotenv() + """ Sample: Workflow state with agents and conditional routing. diff --git a/python/samples/03-workflows/state-management/workflow_kwargs.py b/python/samples/03-workflows/state-management/workflow_kwargs.py index c7f3562fc8..12ed57b628 100644 --- a/python/samples/03-workflows/state-management/workflow_kwargs.py +++ b/python/samples/03-workflows/state-management/workflow_kwargs.py @@ -9,8 +9,12 @@ from agent_framework.azure import AzureOpenAIResponsesClient from agent_framework.orchestrations import SequentialBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Sample: Workflow kwargs Flow to @tool Tools diff --git a/python/samples/03-workflows/tool-approval/concurrent_builder_tool_approval.py b/python/samples/03-workflows/tool-approval/concurrent_builder_tool_approval.py index 94ca3aab88..c6a83c93a6 100644 --- a/python/samples/03-workflows/tool-approval/concurrent_builder_tool_approval.py +++ b/python/samples/03-workflows/tool-approval/concurrent_builder_tool_approval.py @@ -14,6 +14,10 @@ from agent_framework.azure import AzureOpenAIResponsesClient from agent_framework.orchestrations import ConcurrentBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Sample: Concurrent Workflow with Tool Approval Requests diff --git a/python/samples/03-workflows/tool-approval/group_chat_builder_tool_approval.py b/python/samples/03-workflows/tool-approval/group_chat_builder_tool_approval.py index 960a547b10..7f384bb4cd 100644 --- a/python/samples/03-workflows/tool-approval/group_chat_builder_tool_approval.py +++ b/python/samples/03-workflows/tool-approval/group_chat_builder_tool_approval.py @@ -14,6 +14,10 @@ from agent_framework.azure import AzureOpenAIResponsesClient from agent_framework.orchestrations import GroupChatBuilder, GroupChatState from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Sample: Group Chat Workflow with Tool Approval Requests diff --git a/python/samples/03-workflows/tool-approval/sequential_builder_tool_approval.py b/python/samples/03-workflows/tool-approval/sequential_builder_tool_approval.py index d9916801f4..c3ad0cf011 100644 --- a/python/samples/03-workflows/tool-approval/sequential_builder_tool_approval.py +++ b/python/samples/03-workflows/tool-approval/sequential_builder_tool_approval.py @@ -14,6 +14,10 @@ from agent_framework.azure import AzureOpenAIResponsesClient from agent_framework.orchestrations import SequentialBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Sample: Sequential Workflow with Tool Approval Requests diff --git a/python/samples/03-workflows/visualization/concurrent_with_visualization.py b/python/samples/03-workflows/visualization/concurrent_with_visualization.py index c7c2ce2d0c..2786e792a2 100644 --- a/python/samples/03-workflows/visualization/concurrent_with_visualization.py +++ b/python/samples/03-workflows/visualization/concurrent_with_visualization.py @@ -17,8 +17,12 @@ ) from agent_framework.azure import AzureOpenAIResponsesClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv from typing_extensions import Never +# Load environment variables from .env file +load_dotenv() + """ Sample: Concurrent (Fan-out/Fan-in) with Agents + Visualization diff --git a/python/samples/04-hosting/a2a/agent_with_a2a.py b/python/samples/04-hosting/a2a/agent_with_a2a.py index 4250104b9f..89d43e4b0a 100644 --- a/python/samples/04-hosting/a2a/agent_with_a2a.py +++ b/python/samples/04-hosting/a2a/agent_with_a2a.py @@ -6,6 +6,10 @@ import httpx from a2a.client import A2ACardResolver from agent_framework.a2a import A2AAgent +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() """ Agent2Agent (A2A) Protocol Integration Sample diff --git a/python/samples/04-hosting/azure_functions/01_single_agent/function_app.py b/python/samples/04-hosting/azure_functions/01_single_agent/function_app.py index db90c4d1a7..03e4a4d20e 100644 --- a/python/samples/04-hosting/azure_functions/01_single_agent/function_app.py +++ b/python/samples/04-hosting/azure_functions/01_single_agent/function_app.py @@ -12,12 +12,15 @@ from agent_framework.azure import AgentFunctionApp, AzureOpenAIChatClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() # 1. Instantiate the agent with the chosen deployment and instructions. def _create_agent() -> Any: """Create the Joker agent.""" - return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent( name="Joker", instructions="You are good at telling jokes.", diff --git a/python/samples/04-hosting/azure_functions/02_multi_agent/function_app.py b/python/samples/04-hosting/azure_functions/02_multi_agent/function_app.py index 419b91b779..2e805e43b2 100644 --- a/python/samples/04-hosting/azure_functions/02_multi_agent/function_app.py +++ b/python/samples/04-hosting/azure_functions/02_multi_agent/function_app.py @@ -16,15 +16,20 @@ from agent_framework import tool from agent_framework.azure import AgentFunctionApp, AzureOpenAIChatClient from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() logger = logging.getLogger(__name__) -# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. +# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; +# see samples/02-agents/tools/function_tool_with_approval.py +# and samples/02-agents/tools/function_tool_with_approval_and_sessions.py. @tool(approval_mode="never_require") def get_weather(location: str) -> dict[str, Any]: """Get current weather for a location.""" - logger.info(f"🔧 [TOOL CALLED] get_weather(location={location})") result = { "location": location, @@ -40,9 +45,7 @@ def get_weather(location: str) -> dict[str, Any]: def calculate_tip(bill_amount: float, tip_percentage: float = 15.0) -> dict[str, Any]: """Calculate tip amount and total bill.""" - logger.info( - f"🔧 [TOOL CALLED] calculate_tip(bill_amount={bill_amount}, tip_percentage={tip_percentage})" - ) + logger.info(f"🔧 [TOOL CALLED] calculate_tip(bill_amount={bill_amount}, tip_percentage={tip_percentage})") tip = bill_amount * (tip_percentage / 100) total = bill_amount + tip result = { diff --git a/python/samples/04-hosting/azure_functions/03_reliable_streaming/function_app.py b/python/samples/04-hosting/azure_functions/03_reliable_streaming/function_app.py index 1107a78e23..61eda7d6c0 100644 --- a/python/samples/04-hosting/azure_functions/03_reliable_streaming/function_app.py +++ b/python/samples/04-hosting/azure_functions/03_reliable_streaming/function_app.py @@ -29,9 +29,13 @@ AzureOpenAIChatClient, ) from azure.identity import AzureCliCredential +from dotenv import load_dotenv from redis_stream_response_handler import RedisStreamResponseHandler, StreamChunk from tools import get_local_events, get_weather_forecast +# Load environment variables from .env file +load_dotenv() + logger = logging.getLogger(__name__) # Configuration @@ -217,9 +221,7 @@ async def stream(req: func.HttpRequest) -> func.HttpResponse: # Get optional cursor from query string cursor = req.params.get("cursor") - logger.info( - f"Resuming stream for conversation {conversation_id} from cursor: {cursor or '(beginning)'}" - ) + logger.info(f"Resuming stream for conversation {conversation_id} from cursor: {cursor or '(beginning)'}") # Check Accept header to determine response format accept_header = req.headers.get("Accept", "") diff --git a/python/samples/04-hosting/azure_functions/03_reliable_streaming/redis_stream_response_handler.py b/python/samples/04-hosting/azure_functions/03_reliable_streaming/redis_stream_response_handler.py index c17439589e..d4987a827c 100644 --- a/python/samples/04-hosting/azure_functions/03_reliable_streaming/redis_stream_response_handler.py +++ b/python/samples/04-hosting/azure_functions/03_reliable_streaming/redis_stream_response_handler.py @@ -25,6 +25,7 @@ class StreamChunk: is_done: Whether this is the final chunk in the stream. error: Error message if an error occurred, otherwise None. """ + entry_id: str text: str | None = None is_done: bool = False @@ -84,7 +85,7 @@ async def write_chunk( "text": text, "sequence": str(sequence), "timestamp": str(int(time.time() * 1000)), - } + }, ) await self._redis.expire(stream_key, self._stream_ttl) @@ -107,7 +108,7 @@ async def write_completion( "sequence": str(sequence), "timestamp": str(int(time.time() * 1000)), "done": "true", - } + }, ) await self._redis.expire(stream_key, self._stream_ttl) @@ -152,7 +153,7 @@ async def read_stream( timeout_seconds = self.MAX_EMPTY_READS * self.POLL_INTERVAL_MS / 1000 yield StreamChunk( entry_id=start_id, - error=f"Stream not found or timed out after {timeout_seconds} seconds" + error=f"Stream not found or timed out after {timeout_seconds} seconds", ) return diff --git a/python/samples/04-hosting/azure_functions/04_single_agent_orchestration_chaining/function_app.py b/python/samples/04-hosting/azure_functions/04_single_agent_orchestration_chaining/function_app.py index 0b6f97f87a..6418cd7180 100644 --- a/python/samples/04-hosting/azure_functions/04_single_agent_orchestration_chaining/function_app.py +++ b/python/samples/04-hosting/azure_functions/04_single_agent_orchestration_chaining/function_app.py @@ -19,6 +19,10 @@ from agent_framework.azure import AgentFunctionApp, AzureOpenAIChatClient from azure.durable_functions import DurableOrchestrationClient, DurableOrchestrationContext from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() logger = logging.getLogger(__name__) @@ -29,7 +33,6 @@ # 2. Create the writer agent that will be invoked twice within the orchestration. def _create_writer_agent() -> Any: """Create the writer agent with the same persona as the C# sample.""" - instructions = ( "You refine short pieces of text. When given an initial sentence you enhance it;\n" "when given an improved sentence you polish it further." @@ -58,10 +61,7 @@ def single_agent_orchestration(context: DurableOrchestrationContext) -> Generato session=writer_session, ) - improved_prompt = ( - "Improve this further while keeping it under 25 words: " - f"{initial.text}" - ) + improved_prompt = f"Improve this further while keeping it under 25 words: {initial.text}" refined = yield writer.run( messages=improved_prompt, diff --git a/python/samples/04-hosting/azure_functions/05_multi_agent_orchestration_concurrency/function_app.py b/python/samples/04-hosting/azure_functions/05_multi_agent_orchestration_concurrency/function_app.py index 148835033f..3a64fa545a 100644 --- a/python/samples/04-hosting/azure_functions/05_multi_agent_orchestration_concurrency/function_app.py +++ b/python/samples/04-hosting/azure_functions/05_multi_agent_orchestration_concurrency/function_app.py @@ -20,6 +20,10 @@ from agent_framework.azure import AgentFunctionApp, AzureOpenAIChatClient from azure.durable_functions import DurableOrchestrationClient, DurableOrchestrationContext from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() logger = logging.getLogger(__name__) @@ -56,7 +60,6 @@ def _create_agents() -> list[Any]: @app.orchestration_trigger(context_name="context") def multi_agent_concurrent_orchestration(context: DurableOrchestrationContext) -> Generator[Any, Any, dict[str, str]]: """Fan out to two domain-specific agents and aggregate their responses.""" - prompt = context.get_input() if not prompt or not str(prompt).strip(): raise ValueError("Prompt is required") diff --git a/python/samples/04-hosting/azure_functions/06_multi_agent_orchestration_conditionals/function_app.py b/python/samples/04-hosting/azure_functions/06_multi_agent_orchestration_conditionals/function_app.py index 148c6eaad5..64a071ca99 100644 --- a/python/samples/04-hosting/azure_functions/06_multi_agent_orchestration_conditionals/function_app.py +++ b/python/samples/04-hosting/azure_functions/06_multi_agent_orchestration_conditionals/function_app.py @@ -20,8 +20,12 @@ from agent_framework.azure import AgentFunctionApp, AzureOpenAIChatClient from azure.durable_functions import DurableOrchestrationClient, DurableOrchestrationContext from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import BaseModel, ValidationError +# Load environment variables from .env file +load_dotenv() + logger = logging.getLogger(__name__) # 1. Define agent names shared across the orchestration. diff --git a/python/samples/04-hosting/azure_functions/07_single_agent_orchestration_hitl/function_app.py b/python/samples/04-hosting/azure_functions/07_single_agent_orchestration_hitl/function_app.py index 69651e45cf..ecdc5ca1c5 100644 --- a/python/samples/04-hosting/azure_functions/07_single_agent_orchestration_hitl/function_app.py +++ b/python/samples/04-hosting/azure_functions/07_single_agent_orchestration_hitl/function_app.py @@ -20,8 +20,12 @@ from agent_framework.azure import AgentFunctionApp, AzureOpenAIChatClient from azure.durable_functions import DurableOrchestrationClient, DurableOrchestrationContext from azure.identity import AzureCliCredential +from dotenv import load_dotenv from pydantic import BaseModel, ValidationError +# Load environment variables from .env file +load_dotenv() + logger = logging.getLogger(__name__) # 1. Define orchestration constants used throughout the workflow. @@ -136,9 +140,7 @@ def content_generation_hitl_orchestration(context: DurableOrchestrationContext) ) return {"content": content.content} - context.set_custom_status( - "Content rejected by human reviewer. Incorporating feedback and regenerating..." - ) + context.set_custom_status("Content rejected by human reviewer. Incorporating feedback and regenerating...") # Check if we've exhausted attempts if attempt >= payload.max_review_attempts: @@ -162,15 +164,11 @@ def content_generation_hitl_orchestration(context: DurableOrchestrationContext) context.set_custom_status( f"Human approval timed out after {payload.approval_timeout_hours} hour(s). Treating as rejection." ) - raise TimeoutError( - f"Human approval timed out after {payload.approval_timeout_hours} hour(s)." - ) + raise TimeoutError(f"Human approval timed out after {payload.approval_timeout_hours} hour(s).") # If we exit the loop without returning, max attempts were exhausted context.set_custom_status("Max review attempts exhausted.") - raise RuntimeError( - f"Content could not be approved after {payload.max_review_attempts} iteration(s)." - ) + raise RuntimeError(f"Content could not be approved after {payload.max_review_attempts} iteration(s).") # 5. HTTP endpoint that starts the human-in-the-loop orchestration. diff --git a/python/samples/04-hosting/azure_functions/08_mcp_server/function_app.py b/python/samples/04-hosting/azure_functions/08_mcp_server/function_app.py index b34361d10e..a4580fa23c 100644 --- a/python/samples/04-hosting/azure_functions/08_mcp_server/function_app.py +++ b/python/samples/04-hosting/azure_functions/08_mcp_server/function_app.py @@ -25,6 +25,10 @@ """ from agent_framework.azure import AgentFunctionApp, AzureOpenAIChatClient +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() # Create Azure OpenAI Chat Client # This uses AzureCliCredential for authentication (requires 'az login') diff --git a/python/samples/04-hosting/azure_functions/11_workflow_parallel/function_app.py b/python/samples/04-hosting/azure_functions/11_workflow_parallel/function_app.py index 38b3f481a9..d9d3ff6324 100644 --- a/python/samples/04-hosting/azure_functions/11_workflow_parallel/function_app.py +++ b/python/samples/04-hosting/azure_functions/11_workflow_parallel/function_app.py @@ -62,6 +62,7 @@ class SentimentResult(BaseModel): """Result from sentiment analysis.""" + sentiment: str # positive, negative, neutral confidence: float explanation: str @@ -69,18 +70,21 @@ class SentimentResult(BaseModel): class KeywordResult(BaseModel): """Result from keyword extraction.""" + keywords: list[str] categories: list[str] class SummaryResult(BaseModel): """Result from summarization.""" + summary: str key_points: list[str] class RecommendationResult(BaseModel): """Result from recommendation engine.""" + recommendations: list[str] priority: str @@ -88,6 +92,7 @@ class RecommendationResult(BaseModel): @dataclass class DocumentInput: """Input document to be processed.""" + document_id: str content: str @@ -95,6 +100,7 @@ class DocumentInput: @dataclass class ProcessorResult: """Result from a document processor (executor).""" + processor_name: str document_id: str content: str @@ -106,6 +112,7 @@ class ProcessorResult: @dataclass class AggregatedResults: """Aggregated results from parallel processors.""" + document_id: str content: str processor_results: list[ProcessorResult] @@ -114,6 +121,7 @@ class AggregatedResults: @dataclass class AgentAnalysis: """Analysis result from an agent.""" + agent_name: str result: str @@ -121,6 +129,7 @@ class AgentAnalysis: @dataclass class FinalReport: """Final combined report.""" + document_id: str analyses: list[AgentAnalysis] @@ -131,10 +140,7 @@ class FinalReport: @executor(id="input_router") -async def input_router( - doc: str, - ctx: WorkflowContext[DocumentInput] -) -> None: +async def input_router(doc: str, ctx: WorkflowContext[DocumentInput]) -> None: """Route input document to parallel processors. Accepts a JSON string from the HTTP request and converts to DocumentInput. @@ -150,10 +156,7 @@ async def input_router( @executor(id="word_count_processor") -async def word_count_processor( - doc: DocumentInput, - ctx: WorkflowContext[ProcessorResult] -) -> None: +async def word_count_processor(doc: DocumentInput, ctx: WorkflowContext[ProcessorResult]) -> None: """Process document and count words - runs as an activity.""" logger.info("[word_count_processor] Processing document: %s", doc.document_id) @@ -174,10 +177,7 @@ async def word_count_processor( @executor(id="format_analyzer_processor") -async def format_analyzer_processor( - doc: DocumentInput, - ctx: WorkflowContext[ProcessorResult] -) -> None: +async def format_analyzer_processor(doc: DocumentInput, ctx: WorkflowContext[ProcessorResult]) -> None: """Analyze document format - runs as an activity in parallel with word_count.""" logger.info("[format_analyzer_processor] Processing document: %s", doc.document_id) @@ -200,10 +200,7 @@ async def format_analyzer_processor( @executor(id="aggregator") -async def aggregator( - results: list[ProcessorResult], - ctx: WorkflowContext[AggregatedResults] -) -> None: +async def aggregator(results: list[ProcessorResult], ctx: WorkflowContext[AggregatedResults]) -> None: """Aggregate results from parallel processors - receives fan-in input.""" logger.info("[aggregator] Aggregating %d results", len(results)) @@ -221,10 +218,7 @@ async def aggregator( @executor(id="prepare_for_agents") -async def prepare_for_agents( - aggregated: AggregatedResults, - ctx: WorkflowContext[str] -) -> None: +async def prepare_for_agents(aggregated: AggregatedResults, ctx: WorkflowContext[str]) -> None: """Prepare content for agent analysis - broadcasts to multiple agents.""" logger.info("[prepare_for_agents] Preparing content for agents") @@ -233,10 +227,7 @@ async def prepare_for_agents( @executor(id="prepare_for_mixed") -async def prepare_for_mixed( - analyses: list[AgentExecutorResponse], - ctx: WorkflowContext[str] -) -> None: +async def prepare_for_mixed(analyses: list[AgentExecutorResponse], ctx: WorkflowContext[str]) -> None: """Prepare results for mixed agent+executor parallel processing. Combines agent analysis results into a string that can be consumed by @@ -262,10 +253,7 @@ async def prepare_for_mixed( @executor(id="statistics_processor") -async def statistics_processor( - analysis_text: str, - ctx: WorkflowContext[ProcessorResult] -) -> None: +async def statistics_processor(analysis_text: str, ctx: WorkflowContext[ProcessorResult]) -> None: """Calculate statistics from the analysis - runs in parallel with SummaryAgent.""" logger.info("[statistics_processor] Calculating statistics") diff --git a/python/samples/04-hosting/durabletask/01_single_agent/client.py b/python/samples/04-hosting/durabletask/01_single_agent/client.py index 7940d0421c..917a53a74a 100644 --- a/python/samples/04-hosting/durabletask/01_single_agent/client.py +++ b/python/samples/04-hosting/durabletask/01_single_agent/client.py @@ -18,17 +18,19 @@ from agent_framework.azure import DurableAIAgentClient from azure.identity import DefaultAzureCredential +from dotenv import load_dotenv from durabletask.azuremanaged.client import DurableTaskSchedulerClient +# Load environment variables from .env file +load_dotenv() + # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def get_client( - taskhub: str | None = None, - endpoint: str | None = None, - log_handler: logging.Handler | None = None + taskhub: str | None = None, endpoint: str | None = None, log_handler: logging.Handler | None = None ) -> DurableAIAgentClient: """Create a configured DurableAIAgentClient. @@ -53,7 +55,7 @@ def get_client( secure_channel=endpoint_url != "http://localhost:8080", taskhub=taskhub_name, token_credential=credential, - log_handler=log_handler + log_handler=log_handler, ) return DurableAIAgentClient(dts_client) diff --git a/python/samples/04-hosting/durabletask/01_single_agent/worker.py b/python/samples/04-hosting/durabletask/01_single_agent/worker.py index 64023113b4..535b5d6fb2 100644 --- a/python/samples/04-hosting/durabletask/01_single_agent/worker.py +++ b/python/samples/04-hosting/durabletask/01_single_agent/worker.py @@ -18,8 +18,12 @@ from agent_framework import Agent from agent_framework.azure import AzureOpenAIChatClient, DurableAIAgentWorker from azure.identity import AzureCliCredential, DefaultAzureCredential +from dotenv import load_dotenv from durabletask.azuremanaged.worker import DurableTaskSchedulerWorker +# Load environment variables from .env file +load_dotenv() + # Configure logging logging.basicConfig(level=logging.WARNING) logger = logging.getLogger(__name__) @@ -38,9 +42,7 @@ def create_joker_agent() -> Agent: def get_worker( - taskhub: str | None = None, - endpoint: str | None = None, - log_handler: logging.Handler | None = None + taskhub: str | None = None, endpoint: str | None = None, log_handler: logging.Handler | None = None ) -> DurableTaskSchedulerWorker: """Create a configured DurableTaskSchedulerWorker. @@ -65,7 +67,7 @@ def get_worker( secure_channel=endpoint_url != "http://localhost:8080", taskhub=taskhub_name, token_credential=credential, - log_handler=log_handler + log_handler=log_handler, ) diff --git a/python/samples/04-hosting/durabletask/02_multi_agent/client.py b/python/samples/04-hosting/durabletask/02_multi_agent/client.py index ee9f0e7ab6..df8c9c8e1a 100644 --- a/python/samples/04-hosting/durabletask/02_multi_agent/client.py +++ b/python/samples/04-hosting/durabletask/02_multi_agent/client.py @@ -19,17 +19,19 @@ from agent_framework.azure import DurableAIAgentClient from azure.identity import DefaultAzureCredential +from dotenv import load_dotenv from durabletask.azuremanaged.client import DurableTaskSchedulerClient +# Load environment variables from .env file +load_dotenv() + # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def get_client( - taskhub: str | None = None, - endpoint: str | None = None, - log_handler: logging.Handler | None = None + taskhub: str | None = None, endpoint: str | None = None, log_handler: logging.Handler | None = None ) -> DurableAIAgentClient: """Create a configured DurableAIAgentClient. @@ -54,7 +56,7 @@ def get_client( secure_channel=endpoint_url != "http://localhost:8080", taskhub=taskhub_name, token_credential=credential, - log_handler=log_handler + log_handler=log_handler, ) return DurableAIAgentClient(dts_client) diff --git a/python/samples/04-hosting/durabletask/02_multi_agent/worker.py b/python/samples/04-hosting/durabletask/02_multi_agent/worker.py index 3a6db39b7a..1b7dc91c1a 100644 --- a/python/samples/04-hosting/durabletask/02_multi_agent/worker.py +++ b/python/samples/04-hosting/durabletask/02_multi_agent/worker.py @@ -20,8 +20,12 @@ from agent_framework import tool from agent_framework.azure import AzureOpenAIChatClient, DurableAIAgentWorker from azure.identity import AzureCliCredential, DefaultAzureCredential +from dotenv import load_dotenv from durabletask.azuremanaged.worker import DurableTaskSchedulerWorker +# Load environment variables from .env file +load_dotenv() + # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) diff --git a/python/samples/04-hosting/durabletask/03_single_agent_streaming/client.py b/python/samples/04-hosting/durabletask/03_single_agent_streaming/client.py index 9cb6f4cd88..883ebeb483 100644 --- a/python/samples/04-hosting/durabletask/03_single_agent_streaming/client.py +++ b/python/samples/04-hosting/durabletask/03_single_agent_streaming/client.py @@ -22,9 +22,13 @@ import redis.asyncio as aioredis from agent_framework.azure import DurableAIAgentClient from azure.identity import DefaultAzureCredential +from dotenv import load_dotenv from durabletask.azuremanaged.client import DurableTaskSchedulerClient from redis_stream_response_handler import RedisStreamResponseHandler +# Load environment variables from .env file +load_dotenv() + # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) @@ -54,9 +58,7 @@ async def get_stream_handler() -> RedisStreamResponseHandler: def get_client( - taskhub: str | None = None, - endpoint: str | None = None, - log_handler: logging.Handler | None = None + taskhub: str | None = None, endpoint: str | None = None, log_handler: logging.Handler | None = None ) -> DurableAIAgentClient: """Create a configured DurableAIAgentClient. @@ -81,7 +83,7 @@ def get_client( secure_channel=endpoint_url != "http://localhost:8080", taskhub=taskhub_name, token_credential=credential, - log_handler=log_handler + log_handler=log_handler, ) return DurableAIAgentClient(dts_client) @@ -106,7 +108,9 @@ async def stream_from_redis(thread_id: str, cursor: str | None = None) -> None: chunk_count = 0 async for chunk in stream_handler.read_stream(thread_id, cursor): chunk_count += 1 - logger.debug(f"Received chunk #{chunk_count}: error={chunk.error}, is_done={chunk.is_done}, text_len={len(chunk.text) if chunk.text else 0}") + logger.debug( + f"Received chunk #{chunk_count}: error={chunk.error}, is_done={chunk.is_done}, text_len={len(chunk.text) if chunk.text else 0}" + ) if chunk.error: logger.error(f"Stream error: {chunk.error}") @@ -175,9 +179,6 @@ def run_client(agent_client: DurableAIAgentClient) -> None: if __name__ == "__main__": - from dotenv import load_dotenv - load_dotenv() - # Create the client client = get_client() diff --git a/python/samples/04-hosting/durabletask/03_single_agent_streaming/redis_stream_response_handler.py b/python/samples/04-hosting/durabletask/03_single_agent_streaming/redis_stream_response_handler.py index 4a3298df50..eab02145e4 100644 --- a/python/samples/04-hosting/durabletask/03_single_agent_streaming/redis_stream_response_handler.py +++ b/python/samples/04-hosting/durabletask/03_single_agent_streaming/redis_stream_response_handler.py @@ -25,6 +25,7 @@ class StreamChunk: is_done: Whether this is the final chunk in the stream. error: Error message if an error occurred, otherwise None. """ + entry_id: str text: str | None = None is_done: bool = False @@ -60,7 +61,9 @@ async def __aenter__(self): """Enter async context manager.""" return self - async def __aexit__(self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: object) -> None: + async def __aexit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: object + ) -> None: """Exit async context manager and close Redis connection.""" await self._redis.aclose() @@ -84,7 +87,7 @@ async def write_chunk( "text": text, "sequence": str(sequence), "timestamp": str(int(time.time() * 1000)), - } + }, ) await self._redis.expire(stream_key, self._stream_ttl) @@ -107,7 +110,7 @@ async def write_completion( "sequence": str(sequence), "timestamp": str(int(time.time() * 1000)), "done": "true", - } + }, ) await self._redis.expire(stream_key, self._stream_ttl) @@ -152,7 +155,7 @@ async def read_stream( timeout_seconds = self.MAX_EMPTY_READS * self.POLL_INTERVAL_MS / 1000 yield StreamChunk( entry_id=start_id, - error=f"Stream not found or timed out after {timeout_seconds} seconds" + error=f"Stream not found or timed out after {timeout_seconds} seconds", ) return diff --git a/python/samples/04-hosting/durabletask/03_single_agent_streaming/tools.py b/python/samples/04-hosting/durabletask/03_single_agent_streaming/tools.py index be4900860a..dc231752e0 100644 --- a/python/samples/04-hosting/durabletask/03_single_agent_streaming/tools.py +++ b/python/samples/04-hosting/durabletask/03_single_agent_streaming/tools.py @@ -4,6 +4,7 @@ In a real application, these would call actual weather and events APIs. """ + from typing import Annotated from agent_framework import tool diff --git a/python/samples/04-hosting/durabletask/03_single_agent_streaming/worker.py b/python/samples/04-hosting/durabletask/03_single_agent_streaming/worker.py index 320c008cde..983156147a 100644 --- a/python/samples/04-hosting/durabletask/03_single_agent_streaming/worker.py +++ b/python/samples/04-hosting/durabletask/03_single_agent_streaming/worker.py @@ -26,10 +26,14 @@ DurableAIAgentWorker, ) from azure.identity import AzureCliCredential, DefaultAzureCredential +from dotenv import load_dotenv from durabletask.azuremanaged.worker import DurableTaskSchedulerWorker from redis_stream_response_handler import RedisStreamResponseHandler from tools import get_local_events, get_weather_forecast +# Load environment variables from .env file +load_dotenv() + # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) @@ -169,9 +173,7 @@ def create_travel_agent() -> "Agent": def get_worker( - taskhub: str | None = None, - endpoint: str | None = None, - log_handler: logging.Handler | None = None + taskhub: str | None = None, endpoint: str | None = None, log_handler: logging.Handler | None = None ) -> DurableTaskSchedulerWorker: """Create a configured DurableTaskSchedulerWorker. @@ -196,7 +198,7 @@ def get_worker( secure_channel=endpoint_url != "http://localhost:8080", taskhub=taskhub_name, token_credential=credential, - log_handler=log_handler + log_handler=log_handler, ) diff --git a/python/samples/04-hosting/durabletask/04_single_agent_orchestration_chaining/client.py b/python/samples/04-hosting/durabletask/04_single_agent_orchestration_chaining/client.py index b438cd0da3..573683fca1 100644 --- a/python/samples/04-hosting/durabletask/04_single_agent_orchestration_chaining/client.py +++ b/python/samples/04-hosting/durabletask/04_single_agent_orchestration_chaining/client.py @@ -27,9 +27,7 @@ def get_client( - taskhub: str | None = None, - endpoint: str | None = None, - log_handler: logging.Handler | None = None + taskhub: str | None = None, endpoint: str | None = None, log_handler: logging.Handler | None = None ) -> DurableTaskSchedulerClient: """Create a configured DurableTaskSchedulerClient. @@ -54,7 +52,7 @@ def get_client( secure_channel=endpoint_url != "http://localhost:8080", taskhub=taskhub_name, token_credential=credential, - log_handler=log_handler + log_handler=log_handler, ) @@ -67,7 +65,7 @@ def run_client(client: DurableTaskSchedulerClient) -> None: logger.debug("Starting single agent chaining orchestration...") # Start the orchestration - instance_id = client.schedule_new_orchestration( # type: ignore + instance_id = client.schedule_new_orchestration( # type: ignore orchestrator="single_agent_chaining_orchestration", input="", ) @@ -76,10 +74,7 @@ def run_client(client: DurableTaskSchedulerClient) -> None: logger.debug("Waiting for orchestration to complete...") # Retrieve the final state - metadata = client.wait_for_orchestration_completion( - instance_id=instance_id, - timeout=300 - ) + metadata = client.wait_for_orchestration_completion(instance_id=instance_id, timeout=300) if metadata and metadata.runtime_status.name == "COMPLETED": result = metadata.serialized_output diff --git a/python/samples/04-hosting/durabletask/04_single_agent_orchestration_chaining/worker.py b/python/samples/04-hosting/durabletask/04_single_agent_orchestration_chaining/worker.py index ecc44a8959..86a3b259f7 100644 --- a/python/samples/04-hosting/durabletask/04_single_agent_orchestration_chaining/worker.py +++ b/python/samples/04-hosting/durabletask/04_single_agent_orchestration_chaining/worker.py @@ -20,9 +20,13 @@ from agent_framework import Agent, AgentResponse from agent_framework.azure import AzureOpenAIChatClient, DurableAIAgentOrchestrationContext, DurableAIAgentWorker from azure.identity import AzureCliCredential, DefaultAzureCredential +from dotenv import load_dotenv from durabletask.azuremanaged.worker import DurableTaskSchedulerWorker from durabletask.task import OrchestrationContext, Task +# Load environment variables from .env file +load_dotenv() + # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) @@ -102,10 +106,7 @@ def single_agent_chaining_orchestration( logger.info(f"[Orchestration] Initial response: {initial_response.text}") # Second run: Refine the initial response on the same thread - improved_prompt = ( - f"Improve this further while keeping it under 25 words: " - f"{initial_response.text}" - ) + improved_prompt = f"Improve this further while keeping it under 25 words: {initial_response.text}" logger.info("[Orchestration] Second agent run: Refining the sentence: %s", improved_prompt) refined_response = yield writer.run( @@ -120,9 +121,7 @@ def single_agent_chaining_orchestration( def get_worker( - taskhub: str | None = None, - endpoint: str | None = None, - log_handler: logging.Handler | None = None + taskhub: str | None = None, endpoint: str | None = None, log_handler: logging.Handler | None = None ) -> DurableTaskSchedulerWorker: """Create a configured DurableTaskSchedulerWorker. @@ -147,7 +146,7 @@ def get_worker( secure_channel=endpoint_url != "http://localhost:8080", taskhub=taskhub_name, token_credential=credential, - log_handler=log_handler + log_handler=log_handler, ) @@ -172,7 +171,7 @@ def setup_worker(worker: DurableTaskSchedulerWorker) -> DurableAIAgentWorker: # Register the orchestration function logger.debug("Registering orchestration function...") - worker.add_orchestrator(single_agent_chaining_orchestration) # type: ignore + worker.add_orchestrator(single_agent_chaining_orchestration) # type: ignore logger.debug(f"✓ Registered orchestration: {single_agent_chaining_orchestration.__name__}") return agent_worker diff --git a/python/samples/04-hosting/durabletask/05_multi_agent_orchestration_concurrency/client.py b/python/samples/04-hosting/durabletask/05_multi_agent_orchestration_concurrency/client.py index 20f252fe21..473a176def 100644 --- a/python/samples/04-hosting/durabletask/05_multi_agent_orchestration_concurrency/client.py +++ b/python/samples/04-hosting/durabletask/05_multi_agent_orchestration_concurrency/client.py @@ -27,9 +27,7 @@ def get_client( - taskhub: str | None = None, - endpoint: str | None = None, - log_handler: logging.Handler | None = None + taskhub: str | None = None, endpoint: str | None = None, log_handler: logging.Handler | None = None ) -> DurableTaskSchedulerClient: """Create a configured DurableTaskSchedulerClient. @@ -54,7 +52,7 @@ def get_client( secure_channel=endpoint_url != "http://localhost:8080", taskhub=taskhub_name, token_credential=credential, - log_handler=log_handler + log_handler=log_handler, ) @@ -66,7 +64,7 @@ def run_client(client: DurableTaskSchedulerClient, prompt: str = "What is temper prompt: The prompt to send to both agents """ # Start the orchestration with the prompt as input - instance_id = client.schedule_new_orchestration( # type: ignore + instance_id = client.schedule_new_orchestration( # type: ignore orchestrator="multi_agent_concurrent_orchestration", input=prompt, ) diff --git a/python/samples/04-hosting/durabletask/05_multi_agent_orchestration_concurrency/worker.py b/python/samples/04-hosting/durabletask/05_multi_agent_orchestration_concurrency/worker.py index 716355ec8b..18ede13ead 100644 --- a/python/samples/04-hosting/durabletask/05_multi_agent_orchestration_concurrency/worker.py +++ b/python/samples/04-hosting/durabletask/05_multi_agent_orchestration_concurrency/worker.py @@ -21,9 +21,13 @@ from agent_framework import Agent, AgentResponse from agent_framework.azure import AzureOpenAIChatClient, DurableAIAgentOrchestrationContext, DurableAIAgentWorker from azure.identity import AzureCliCredential, DefaultAzureCredential +from dotenv import load_dotenv from durabletask.azuremanaged.worker import DurableTaskSchedulerWorker from durabletask.task import OrchestrationContext, Task, when_all +# Load environment variables from .env file +load_dotenv() + # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) @@ -57,7 +61,9 @@ def create_chemist_agent() -> "Agent": ) -def multi_agent_concurrent_orchestration(context: OrchestrationContext, prompt: str) -> Generator[Task[Any], Any, dict[str, str]]: +def multi_agent_concurrent_orchestration( + context: OrchestrationContext, prompt: str +) -> Generator[Task[Any], Any, dict[str, str]]: """Orchestration that runs both agents in parallel and aggregates results. Uses DurableAIAgentOrchestrationContext to wrap the orchestration context and @@ -84,7 +90,9 @@ def multi_agent_concurrent_orchestration(context: OrchestrationContext, prompt: physicist_session = physicist.create_session() chemist_session = chemist.create_session() - logger.debug(f"[Orchestration] Created sessions - Physicist: {physicist_session.session_id}, Chemist: {chemist_session.session_id}") + logger.debug( + f"[Orchestration] Created sessions - Physicist: {physicist_session.session_id}, Chemist: {chemist_session.session_id}" + ) # Create tasks from agent.run() calls - these return DurableAgentTask instances physicist_task = physicist.run(messages=str(prompt), session=physicist_session) @@ -112,9 +120,7 @@ def multi_agent_concurrent_orchestration(context: OrchestrationContext, prompt: def get_worker( - taskhub: str | None = None, - endpoint: str | None = None, - log_handler: logging.Handler | None = None + taskhub: str | None = None, endpoint: str | None = None, log_handler: logging.Handler | None = None ) -> DurableTaskSchedulerWorker: """Create a configured DurableTaskSchedulerWorker. @@ -139,7 +145,7 @@ def get_worker( secure_channel=endpoint_url != "http://localhost:8080", taskhub=taskhub_name, token_credential=credential, - log_handler=log_handler + log_handler=log_handler, ) @@ -167,7 +173,7 @@ def setup_worker(worker: DurableTaskSchedulerWorker) -> DurableAIAgentWorker: # Register the orchestration function logger.debug("Registering orchestration function...") - worker.add_orchestrator(multi_agent_concurrent_orchestration) # type: ignore + worker.add_orchestrator(multi_agent_concurrent_orchestration) # type: ignore logger.debug(f"✓ Registered orchestration: {multi_agent_concurrent_orchestration.__name__}") return agent_worker diff --git a/python/samples/04-hosting/durabletask/06_multi_agent_orchestration_conditionals/client.py b/python/samples/04-hosting/durabletask/06_multi_agent_orchestration_conditionals/client.py index 5253568a53..0202763e74 100644 --- a/python/samples/04-hosting/durabletask/06_multi_agent_orchestration_conditionals/client.py +++ b/python/samples/04-hosting/durabletask/06_multi_agent_orchestration_conditionals/client.py @@ -25,9 +25,7 @@ def get_client( - taskhub: str | None = None, - endpoint: str | None = None, - log_handler: logging.Handler | None = None + taskhub: str | None = None, endpoint: str | None = None, log_handler: logging.Handler | None = None ) -> DurableTaskSchedulerClient: """Create a configured DurableTaskSchedulerClient. @@ -52,14 +50,14 @@ def get_client( secure_channel=endpoint_url != "http://localhost:8080", taskhub=taskhub_name, token_credential=credential, - log_handler=log_handler + log_handler=log_handler, ) def run_client( client: DurableTaskSchedulerClient, email_id: str = "email-001", - email_content: str = "Hello! I wanted to reach out about our upcoming project meeting." + email_content: str = "Hello! I wanted to reach out about our upcoming project meeting.", ) -> None: """Run client to start and monitor the spam detection orchestration. @@ -76,7 +74,7 @@ def run_client( logger.debug("Starting spam detection orchestration...") # Start the orchestration with the email payload - instance_id = client.schedule_new_orchestration( # type: ignore + instance_id = client.schedule_new_orchestration( # type: ignore orchestrator="spam_detection_orchestration", input=payload, ) @@ -85,10 +83,7 @@ def run_client( logger.debug("Waiting for orchestration to complete...") # Retrieve the final state - metadata = client.wait_for_orchestration_completion( - instance_id=instance_id, - timeout=300 - ) + metadata = client.wait_for_orchestration_completion(instance_id=instance_id, timeout=300) if metadata and metadata.runtime_status.name == "COMPLETED": result = metadata.serialized_output @@ -124,7 +119,7 @@ async def main() -> None: run_client( client, email_id="email-001", - email_content="Hello! I wanted to reach out about our upcoming project meeting scheduled for next week." + email_content="Hello! I wanted to reach out about our upcoming project meeting scheduled for next week.", ) # Test with a spam email @@ -133,7 +128,7 @@ async def main() -> None: run_client( client, email_id="email-002", - email_content="URGENT! You've won $1,000,000! Click here now to claim your prize! Limited time offer! Don't miss out!" + email_content="URGENT! You've won $1,000,000! Click here now to claim your prize! Limited time offer! Don't miss out!", ) except Exception as e: diff --git a/python/samples/04-hosting/durabletask/06_multi_agent_orchestration_conditionals/sample.py b/python/samples/04-hosting/durabletask/06_multi_agent_orchestration_conditionals/sample.py index e098ba1be8..930c3b1f9d 100644 --- a/python/samples/04-hosting/durabletask/06_multi_agent_orchestration_conditionals/sample.py +++ b/python/samples/04-hosting/durabletask/06_multi_agent_orchestration_conditionals/sample.py @@ -25,10 +25,7 @@ from dotenv import load_dotenv from worker import get_worker, setup_worker -logging.basicConfig( - level=logging.INFO, - force=True -) +logging.basicConfig(level=logging.INFO, force=True) logger = logging.getLogger() @@ -57,7 +54,7 @@ def main(): run_client( client, email_id="email-001", - email_content="Hello! I wanted to reach out about our upcoming project meeting scheduled for next week." + email_content="Hello! I wanted to reach out about our upcoming project meeting scheduled for next week.", ) # Test 2: Spam email @@ -66,7 +63,7 @@ def main(): run_client( client, email_id="email-002", - email_content="URGENT! You've won $1,000,000! Click here now to claim your prize! Limited time offer! Don't miss out!" + email_content="URGENT! You've won $1,000,000! Click here now to claim your prize! Limited time offer! Don't miss out!", ) except Exception as e: diff --git a/python/samples/04-hosting/durabletask/06_multi_agent_orchestration_conditionals/worker.py b/python/samples/04-hosting/durabletask/06_multi_agent_orchestration_conditionals/worker.py index 0016627cdc..28a3d54749 100644 --- a/python/samples/04-hosting/durabletask/06_multi_agent_orchestration_conditionals/worker.py +++ b/python/samples/04-hosting/durabletask/06_multi_agent_orchestration_conditionals/worker.py @@ -21,10 +21,14 @@ from agent_framework import Agent, AgentResponse from agent_framework.azure import AzureOpenAIChatClient, DurableAIAgentOrchestrationContext, DurableAIAgentWorker from azure.identity import AzureCliCredential, DefaultAzureCredential +from dotenv import load_dotenv from durabletask.azuremanaged.worker import DurableTaskSchedulerWorker from durabletask.task import ActivityContext, OrchestrationContext, Task from pydantic import BaseModel, ValidationError +# Load environment variables from .env file +load_dotenv() + # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) @@ -36,17 +40,20 @@ class SpamDetectionResult(BaseModel): """Result from spam detection agent.""" + is_spam: bool reason: str class EmailResponse(BaseModel): """Result from email assistant agent.""" + response: str class EmailPayload(BaseModel): """Input payload for the orchestration.""" + email_id: str email_content: str @@ -195,9 +202,7 @@ def spam_detection_orchestration(context: OrchestrationContext, payload_raw: Any def get_worker( - taskhub: str | None = None, - endpoint: str | None = None, - log_handler: logging.Handler | None = None + taskhub: str | None = None, endpoint: str | None = None, log_handler: logging.Handler | None = None ) -> DurableTaskSchedulerWorker: """Create a configured DurableTaskSchedulerWorker. @@ -222,7 +227,7 @@ def get_worker( secure_channel=endpoint_url != "http://localhost:8080", taskhub=taskhub_name, token_credential=credential, - log_handler=log_handler + log_handler=log_handler, ) @@ -257,7 +262,7 @@ def setup_worker(worker: DurableTaskSchedulerWorker) -> DurableAIAgentWorker: # Register the orchestration function logger.debug("Registering orchestration function...") - worker.add_orchestrator(spam_detection_orchestration) # type: ignore[arg-type] + worker.add_orchestrator(spam_detection_orchestration) # type: ignore[arg-type] logger.debug(f"✓ Registered orchestration: {spam_detection_orchestration.__name__}") return agent_worker diff --git a/python/samples/04-hosting/durabletask/07_single_agent_orchestration_hitl/client.py b/python/samples/04-hosting/durabletask/07_single_agent_orchestration_hitl/client.py index 7808a8a03f..cf29e31f65 100644 --- a/python/samples/04-hosting/durabletask/07_single_agent_orchestration_hitl/client.py +++ b/python/samples/04-hosting/durabletask/07_single_agent_orchestration_hitl/client.py @@ -31,9 +31,7 @@ def get_client( - taskhub: str | None = None, - endpoint: str | None = None, - log_handler: logging.Handler | None = None + taskhub: str | None = None, endpoint: str | None = None, log_handler: logging.Handler | None = None ) -> DurableTaskSchedulerClient: """Create a configured DurableTaskSchedulerClient. @@ -58,7 +56,7 @@ def get_client( secure_channel=endpoint_url != "http://localhost:8080", taskhub=taskhub_name, token_credential=credential, - log_handler=log_handler + log_handler=log_handler, ) @@ -90,11 +88,7 @@ def _log_completion_result( logger.error("Orchestration did not complete within the timeout period") -def _wait_and_log_completion( - client: DurableTaskSchedulerClient, - instance_id: str, - timeout: int = 60 -) -> None: +def _wait_and_log_completion(client: DurableTaskSchedulerClient, instance_id: str, timeout: int = 60) -> None: """Wait for orchestration completion and log the result. Args: @@ -103,20 +97,12 @@ def _wait_and_log_completion( timeout: Maximum time to wait for completion in seconds """ logger.debug("Waiting for orchestration to complete...") - metadata = client.wait_for_orchestration_completion( - instance_id=instance_id, - timeout=timeout - ) + metadata = client.wait_for_orchestration_completion(instance_id=instance_id, timeout=timeout) _log_completion_result(metadata) -def send_approval( - client: DurableTaskSchedulerClient, - instance_id: str, - approved: bool, - feedback: str = "" -) -> None: +def send_approval(client: DurableTaskSchedulerClient, instance_id: str, approved: bool, feedback: str = "") -> None: """Send approval or rejection event to the orchestration. Args: @@ -125,30 +111,19 @@ def send_approval( approved: Whether to approve or reject feedback: Optional feedback message (used when rejected) """ - approval_data = { - "approved": approved, - "feedback": feedback - } + approval_data = {"approved": approved, "feedback": feedback} logger.debug(f"Sending {'APPROVAL' if approved else 'REJECTION'} to instance {instance_id}") if feedback: logger.debug(f"Feedback: {feedback}") # Raise the external event - client.raise_orchestration_event( - instance_id=instance_id, - event_name=HUMAN_APPROVAL_EVENT, - data=approval_data - ) + client.raise_orchestration_event(instance_id=instance_id, event_name=HUMAN_APPROVAL_EVENT, data=approval_data) logger.debug("Event sent successfully") -def wait_for_notification( - client: DurableTaskSchedulerClient, - instance_id: str, - timeout_seconds: int = 10 -) -> bool: +def wait_for_notification(client: DurableTaskSchedulerClient, instance_id: str, timeout_seconds: int = 10) -> bool: """Wait for the orchestration to reach a notification point. Polls the orchestration status until it appears to be waiting for approval. @@ -226,14 +201,14 @@ def run_interactive_client(client: DurableTaskSchedulerClient) -> None: payload = { "topic": topic, "max_review_attempts": max_review_attempts, - "approval_timeout_seconds": approval_timeout_seconds + "approval_timeout_seconds": approval_timeout_seconds, } logger.debug(f"Configuration: Topic={topic}, Max attempts={max_review_attempts}, Timeout={timeout_hours}h") # Start the orchestration logger.debug("Starting content generation orchestration...") - instance_id = client.schedule_new_orchestration( # type: ignore + instance_id = client.schedule_new_orchestration( # type: ignore orchestrator="content_generation_hitl_orchestration", input=payload, ) diff --git a/python/samples/04-hosting/durabletask/07_single_agent_orchestration_hitl/sample.py b/python/samples/04-hosting/durabletask/07_single_agent_orchestration_hitl/sample.py index e9b9b43044..d90d6c1aea 100644 --- a/python/samples/04-hosting/durabletask/07_single_agent_orchestration_hitl/sample.py +++ b/python/samples/04-hosting/durabletask/07_single_agent_orchestration_hitl/sample.py @@ -25,10 +25,7 @@ from dotenv import load_dotenv from worker import get_worker, setup_worker -logging.basicConfig( - level=logging.INFO, - force=True -) +logging.basicConfig(level=logging.INFO, force=True) logger = logging.getLogger() diff --git a/python/samples/04-hosting/durabletask/07_single_agent_orchestration_hitl/worker.py b/python/samples/04-hosting/durabletask/07_single_agent_orchestration_hitl/worker.py index d90973ef1d..fed74874f0 100644 --- a/python/samples/04-hosting/durabletask/07_single_agent_orchestration_hitl/worker.py +++ b/python/samples/04-hosting/durabletask/07_single_agent_orchestration_hitl/worker.py @@ -22,10 +22,14 @@ from agent_framework import Agent, AgentResponse from agent_framework.azure import AzureOpenAIChatClient, DurableAIAgentOrchestrationContext, DurableAIAgentWorker from azure.identity import AzureCliCredential, DefaultAzureCredential +from dotenv import load_dotenv from durabletask.azuremanaged.worker import DurableTaskSchedulerWorker from durabletask.task import ActivityContext, OrchestrationContext, Task, when_any # type: ignore from pydantic import BaseModel, ValidationError +# Load environment variables from .env file +load_dotenv() + # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) @@ -37,6 +41,7 @@ class ContentGenerationInput(BaseModel): """Input for content generation orchestration.""" + topic: str max_review_attempts: int = 3 approval_timeout_seconds: float = 300 # 5 minutes for demo (72 hours in production) @@ -44,12 +49,14 @@ class ContentGenerationInput(BaseModel): class GeneratedContent(BaseModel): """Structured output from writer agent.""" + title: str content: str class HumanApproval(BaseModel): """Human approval decision.""" + approved: bool feedback: str = "" @@ -103,8 +110,7 @@ def publish_content(context: ActivityContext, content: dict[str, str]) -> str: def content_generation_hitl_orchestration( - context: OrchestrationContext, - payload_raw: Any + context: OrchestrationContext, payload_raw: Any ) -> Generator[Task[Any], Any, dict[str, str]]: """Human-in-the-loop orchestration for content generation with approval workflow. @@ -160,7 +166,7 @@ def content_generation_hitl_orchestration( initial_response: AgentResponse = yield writer.run( messages=f"Write a short article about '{payload.topic}'.", session=writer_session, - options={"response_format": GeneratedContent}, + options={"response_format": GeneratedContent}, ) content = cast(GeneratedContent, initial_response.value) @@ -175,13 +181,12 @@ def content_generation_hitl_orchestration( attempt += 1 logger.debug(f"[Orchestration] Review iteration #{attempt}/{payload.max_review_attempts}") - context.set_custom_status(f"Requesting human feedback (Attempt {attempt}, timeout {payload.approval_timeout_seconds}s)") + context.set_custom_status( + f"Requesting human feedback (Attempt {attempt}, timeout {payload.approval_timeout_seconds}s)" + ) # Notify user for approval - yield context.call_activity( - "notify_user_for_approval", - input=content.model_dump() - ) + yield context.call_activity("notify_user_for_approval", input=content.model_dump()) logger.debug("[Orchestration] Waiting for human approval or timeout...") @@ -217,16 +222,13 @@ def content_generation_hitl_orchestration( else: approval = HumanApproval(approved=False, feedback=approval_data) else: - approval = HumanApproval(approved=False, feedback=str(approval_data)) # type: ignore + approval = HumanApproval(approved=False, feedback=str(approval_data)) # type: ignore if approval.approved: # Content approved - publish and return logger.debug("[Orchestration] Content approved! Publishing...") context.set_custom_status("Content approved by human reviewer. Publishing...") - publish_task: Task[Any] = context.call_activity( - "publish_content", - input=content.model_dump() - ) + publish_task: Task[Any] = context.call_activity("publish_content", input=content.model_dump()) yield publish_task logger.debug("[Orchestration] Content published successfully") @@ -256,7 +258,7 @@ def content_generation_hitl_orchestration( rewrite_response: AgentResponse = yield writer.run( messages=rewrite_prompt, session=writer_session, - options={"response_format": GeneratedContent}, + options={"response_format": GeneratedContent}, ) rewritten_content = cast(GeneratedContent, rewrite_response.value) @@ -270,21 +272,15 @@ def content_generation_hitl_orchestration( # Timeout occurred logger.error(f"[Orchestration] Approval timeout after {payload.approval_timeout_seconds}s") - raise TimeoutError( - f"Human approval timed out after {payload.approval_timeout_seconds} second(s)." - ) + raise TimeoutError(f"Human approval timed out after {payload.approval_timeout_seconds} second(s).") # If we exit the loop without returning, max attempts were exhausted context.set_custom_status("Max review attempts exhausted.") - raise RuntimeError( - f"Content could not be approved after {payload.max_review_attempts} iteration(s)." - ) + raise RuntimeError(f"Content could not be approved after {payload.max_review_attempts} iteration(s).") def get_worker( - taskhub: str | None = None, - endpoint: str | None = None, - log_handler: logging.Handler | None = None + taskhub: str | None = None, endpoint: str | None = None, log_handler: logging.Handler | None = None ) -> DurableTaskSchedulerWorker: """Create a configured DurableTaskSchedulerWorker. @@ -309,7 +305,7 @@ def get_worker( secure_channel=endpoint_url != "http://localhost:8080", taskhub=taskhub_name, token_credential=credential, - log_handler=log_handler + log_handler=log_handler, ) diff --git a/python/samples/05-end-to-end/chatkit-integration/app.py b/python/samples/05-end-to-end/chatkit-integration/app.py index a22698b085..d47ecc6160 100644 --- a/python/samples/05-end-to-end/chatkit-integration/app.py +++ b/python/samples/05-end-to-end/chatkit-integration/app.py @@ -51,6 +51,7 @@ WidgetItem, ) from chatkit.widgets import WidgetRoot +from dotenv import load_dotenv from fastapi import FastAPI, File, Request, UploadFile from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse, JSONResponse, Response, StreamingResponse @@ -64,6 +65,9 @@ weather_widget_copy_text, ) +# Load environment variables from .env file +load_dotenv() + # ============================================================================ # Configuration Constants # ============================================================================ diff --git a/python/samples/05-end-to-end/hosted_agents/agent_with_hosted_mcp/main.py b/python/samples/05-end-to-end/hosted_agents/agent_with_hosted_mcp/main.py index 3118addc5b..53ee10e6bf 100644 --- a/python/samples/05-end-to-end/hosted_agents/agent_with_hosted_mcp/main.py +++ b/python/samples/05-end-to-end/hosted_agents/agent_with_hosted_mcp/main.py @@ -3,6 +3,10 @@ from agent_framework.azure import AzureOpenAIChatClient from azure.ai.agentserver.agentframework import from_agent_framework # pyright: ignore[reportUnknownVariableType] from azure.identity import DefaultAzureCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() def main(): diff --git a/python/samples/05-end-to-end/hosted_agents/agent_with_text_search_rag/main.py b/python/samples/05-end-to-end/hosted_agents/agent_with_text_search_rag/main.py index e53430ec16..083da0d880 100644 --- a/python/samples/05-end-to-end/hosted_agents/agent_with_text_search_rag/main.py +++ b/python/samples/05-end-to-end/hosted_agents/agent_with_text_search_rag/main.py @@ -9,6 +9,7 @@ from agent_framework.azure import AzureOpenAIChatClient from azure.ai.agentserver.agentframework import from_agent_framework # pyright: ignore[reportUnknownVariableType] from azure.identity import DefaultAzureCredential +from dotenv import load_dotenv if sys.version_info >= (3, 12): from typing import override @@ -16,6 +17,10 @@ from typing_extensions import override +# Load environment variables from .env file +load_dotenv() + + @dataclass class TextSearchResult: source_name: str @@ -94,11 +99,7 @@ async def before_run( context.extend_messages( self.source_id, - [ - Message( - role="user", text="\n\n".join(json.dumps(result.__dict__, indent=2) for result in results) - ) - ], + [Message(role="user", text="\n\n".join(json.dumps(result.__dict__, indent=2) for result in results))], ) diff --git a/python/samples/05-end-to-end/hosted_agents/agents_in_workflow/main.py b/python/samples/05-end-to-end/hosted_agents/agents_in_workflow/main.py index f1356be33d..4afa83cd07 100644 --- a/python/samples/05-end-to-end/hosted_agents/agents_in_workflow/main.py +++ b/python/samples/05-end-to-end/hosted_agents/agents_in_workflow/main.py @@ -4,6 +4,10 @@ from agent_framework_orchestrations import ConcurrentBuilder from azure.ai.agentserver.agentframework import from_agent_framework from azure.identity import DefaultAzureCredential # pyright: ignore[reportUnknownVariableType] +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() def main(): diff --git a/python/samples/05-end-to-end/m365-agent/m365_agent_demo/app.py b/python/samples/05-end-to-end/m365-agent/m365_agent_demo/app.py index a33a487b34..8cd66d3dc1 100644 --- a/python/samples/05-end-to-end/m365-agent/m365_agent_demo/app.py +++ b/python/samples/05-end-to-end/m365-agent/m365_agent_demo/app.py @@ -22,6 +22,7 @@ from agent_framework.openai import OpenAIChatClient from aiohttp import web from aiohttp.web_middlewares import middleware +from dotenv import load_dotenv from microsoft_agents.activity import load_configuration_from_env from microsoft_agents.authentication.msal import MsalConnectionManager from microsoft_agents.hosting.aiohttp import CloudAdapter, start_agent_process @@ -36,6 +37,9 @@ ) from pydantic import Field +# Load environment variables from .env file +load_dotenv() + """ Demo application using Microsoft Agent 365 SDK. diff --git a/python/samples/05-end-to-end/purview_agent/sample_purview_agent.py b/python/samples/05-end-to-end/purview_agent/sample_purview_agent.py index 0a5e251ae4..2e98f05b10 100644 --- a/python/samples/05-end-to-end/purview_agent/sample_purview_agent.py +++ b/python/samples/05-end-to-end/purview_agent/sample_purview_agent.py @@ -37,6 +37,10 @@ CertificateCredential, InteractiveBrowserCredential, ) +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() JOKER_NAME = "Joker" JOKER_INSTRUCTIONS = "You are good at telling jokes. Keep responses concise." @@ -164,9 +168,7 @@ async def run_with_agent_middleware() -> None: print("First response (agent middleware):\n", first) second: AgentResponse = await agent.run( - Message( - role="user", text="That was funny. Tell me another one.", additional_properties={"user_id": user_id} - ) + Message(role="user", text="That was funny. Tell me another one.", additional_properties={"user_id": user_id}) ) print("Second response (agent middleware):\n", second) @@ -252,9 +254,7 @@ async def run_with_custom_cache_provider() -> None: print("Using SimpleDictCacheProvider") first: AgentResponse = await agent.run( - Message( - role="user", text="Tell me a joke about a programmer.", additional_properties={"user_id": user_id} - ) + Message(role="user", text="Tell me a joke about a programmer.", additional_properties={"user_id": user_id}) ) print("First response (custom provider):\n", first) diff --git a/python/samples/05-end-to-end/workflow_evaluation/_tools.py b/python/samples/05-end-to-end/workflow_evaluation/_tools.py index b9b6038191..a1eb4fd479 100644 --- a/python/samples/05-end-to-end/workflow_evaluation/_tools.py +++ b/python/samples/05-end-to-end/workflow_evaluation/_tools.py @@ -37,7 +37,7 @@ def search_hotels( "distance_to_eiffel_tower": "0.3 miles", "amenities": ["WiFi", "Breakfast", "Eiffel Tower View", "Concierge"], "availability": "Available", - "address": "35 Rue Benjamin Franklin, 16th arr., Paris" + "address": "35 Rue Benjamin Franklin, 16th arr., Paris", }, { "name": "Mercure Paris Centre Tour Eiffel", @@ -47,7 +47,7 @@ def search_hotels( "distance_to_eiffel_tower": "0.5 miles", "amenities": ["WiFi", "Restaurant", "Bar", "Gym", "Air Conditioning"], "availability": "Available", - "address": "20 Rue Jean Rey, 15th arr., Paris" + "address": "20 Rue Jean Rey, 15th arr., Paris", }, { "name": "Pullman Paris Tour Eiffel", @@ -57,8 +57,8 @@ def search_hotels( "distance_to_eiffel_tower": "0.2 miles", "amenities": ["WiFi", "Spa", "Gym", "Restaurant", "Rooftop Bar", "Concierge"], "availability": "Limited", - "address": "18 Avenue de Suffren, 15th arr., Paris" - } + "address": "18 Avenue de Suffren, 15th arr., Paris", + }, ] else: mock_hotels = [ @@ -67,7 +67,7 @@ def search_hotels( "rating": 4.5, "price_per_night": "$150", "amenities": ["WiFi", "Pool", "Gym", "Restaurant"], - "availability": "Available" + "availability": "Available", } ] @@ -78,7 +78,7 @@ def search_hotels( "guests": guests, "hotels_found": len(mock_hotels), "hotels": mock_hotels, - "note": "Hotel search results matching your query" + "note": "Hotel search results matching your query", }) @@ -104,10 +104,10 @@ def get_hotel_details( "recent_comments": [ "Amazing location! Walked to Eiffel Tower in 5 minutes.", "Staff was incredibly helpful with restaurant recommendations.", - "Rooms are cozy and clean with great views." - ] + "Rooms are cozy and clean with great views.", + ], }, - "nearby_attractions": ["Eiffel Tower (0.3 mi)", "Trocadéro Gardens (0.2 mi)", "Seine River (0.4 mi)"] + "nearby_attractions": ["Eiffel Tower (0.3 mi)", "Trocadéro Gardens (0.2 mi)", "Seine River (0.4 mi)"], }, "Mercure Paris Centre Tour Eiffel": { "description": "Modern hotel with contemporary rooms and excellent dining options. Close to metro stations.", @@ -119,10 +119,10 @@ def get_hotel_details( "recent_comments": [ "Great value for money, clean and comfortable.", "Restaurant had excellent French cuisine.", - "Easy access to public transportation." - ] + "Easy access to public transportation.", + ], }, - "nearby_attractions": ["Eiffel Tower (0.5 mi)", "Champ de Mars (0.4 mi)", "Les Invalides (0.8 mi)"] + "nearby_attractions": ["Eiffel Tower (0.5 mi)", "Champ de Mars (0.4 mi)", "Les Invalides (0.8 mi)"], }, "Pullman Paris Tour Eiffel": { "description": "Luxury hotel offering panoramic views, upscale amenities, and exceptional service. Ideal for a premium experience.", @@ -134,27 +134,27 @@ def get_hotel_details( "recent_comments": [ "Rooftop bar has the best Eiffel Tower views in Paris!", "Luxurious rooms with every amenity you could want.", - "Worth the price for the location and service." - ] + "Worth the price for the location and service.", + ], }, - "nearby_attractions": ["Eiffel Tower (0.2 mi)", "Seine River Cruise Dock (0.3 mi)", "Trocadéro (0.5 mi)"] - } + "nearby_attractions": ["Eiffel Tower (0.2 mi)", "Seine River Cruise Dock (0.3 mi)", "Trocadéro (0.5 mi)"], + }, } - details = hotel_details.get(hotel_name, { - "name": hotel_name, - "description": "Comfortable hotel with modern amenities", - "check_in_time": "3:00 PM", - "check_out_time": "11:00 AM", - "cancellation_policy": "Standard cancellation policy applies", - "reviews": {"total": 0, "recent_comments": []}, - "nearby_attractions": [] - }) + details = hotel_details.get( + hotel_name, + { + "name": hotel_name, + "description": "Comfortable hotel with modern amenities", + "check_in_time": "3:00 PM", + "check_out_time": "11:00 AM", + "cancellation_policy": "Standard cancellation policy applies", + "reviews": {"total": 0, "recent_comments": []}, + "nearby_attractions": [], + }, + ) - return json.dumps({ - "hotel_name": hotel_name, - "details": details - }) + return json.dumps({"hotel_name": hotel_name, "details": details}) # Mock flight search tool @@ -185,7 +185,7 @@ def search_flights( "duration": "7h 45m", "aircraft": "Boeing 777-300ER", "class": "Economy", - "price": "$520" + "price": "$520", }, "return": { "flight_number": "AF008", @@ -195,11 +195,11 @@ def search_flights( "duration": "8h 15m", "aircraft": "Airbus A350-900", "class": "Economy", - "price": "Included" + "price": "Included", }, "total_price": "$520", "stops": "Nonstop", - "baggage": "1 checked bag included" + "baggage": "1 checked bag included", }, { "outbound": { @@ -210,7 +210,7 @@ def search_flights( "duration": "7h 50m", "aircraft": "Airbus A330-900neo", "class": "Economy", - "price": "$485" + "price": "$485", }, "return": { "flight_number": "DL265", @@ -220,11 +220,11 @@ def search_flights( "duration": "8h 15m", "aircraft": "Airbus A330-900neo", "class": "Economy", - "price": "Included" + "price": "Included", }, "total_price": "$485", "stops": "Nonstop", - "baggage": "1 checked bag included" + "baggage": "1 checked bag included", }, { "outbound": { @@ -235,7 +235,7 @@ def search_flights( "duration": "7h 50m", "aircraft": "Boeing 767-400ER", "class": "Economy", - "price": "$560" + "price": "$560", }, "return": { "flight_number": "UA58", @@ -245,15 +245,17 @@ def search_flights( "duration": "8h 15m", "aircraft": "Boeing 787-10", "class": "Economy", - "price": "Included" + "price": "Included", }, "total_price": "$560", "stops": "Nonstop", - "baggage": "1 checked bag included" - } + "baggage": "1 checked bag included", + }, ] else: - mock_flights = [{"flight_number": "XX123", "airline": "Generic Air", "price": "$400", "note": "Generic route"}] + mock_flights = [ + {"flight_number": "XX123", "airline": "Generic Air", "price": "$400", "note": "Generic route"} + ] else: mock_flights = [ { @@ -264,10 +266,10 @@ def search_flights( "arrival": f"{departure_date} at 2:30 PM", "duration": "5h 30m", "class": "Economy", - "price": "$350" + "price": "$350", }, "total_price": "$350", - "stops": "Nonstop" + "stops": "Nonstop", } ] @@ -279,7 +281,7 @@ def search_flights( "passengers": passengers, "flights_found": len(mock_flights), "flights": mock_flights, - "note": "Flight search results for JFK to Paris CDG" + "note": "Flight search results for JFK to Paris CDG", }) @@ -302,25 +304,20 @@ def get_flight_details( "airport": "JFK International Airport", "terminal": "Terminal 4", "gate": "B23", - "time": "08:00 AM" + "time": "08:00 AM", }, "arrival": { "airport": "Charles de Gaulle Airport", "terminal": "Terminal 2E", "gate": "K15", - "time": "11:30 AM local time" + "time": "11:30 AM local time", }, "duration": "3h 30m", - "baggage_allowance": { - "carry_on": "1 bag (10kg)", - "checked": "1 bag (23kg)" - }, - "amenities": ["WiFi", "In-flight entertainment", "Meals included"] + "baggage_allowance": {"carry_on": "1 bag (10kg)", "checked": "1 bag (23kg)"}, + "amenities": ["WiFi", "In-flight entertainment", "Meals included"], } - return json.dumps({ - "flight_details": mock_details - }) + return json.dumps({"flight_details": mock_details}) # Mock activity search tool @@ -328,7 +325,9 @@ def get_flight_details( def search_activities( location: Annotated[str, Field(description="City or region to search for activities.")], date: Annotated[str | None, Field(description="Date for the activity (e.g., 'December 16, 2025').")] = None, - category: Annotated[str | None, Field(description="Activity category (e.g., 'Sightseeing', 'Culture', 'Culinary').")] = None, + category: Annotated[ + str | None, Field(description="Activity category (e.g., 'Sightseeing', 'Culture', 'Culinary').") + ] = None, ) -> str: """Search for available activities and attractions at a destination. @@ -348,7 +347,7 @@ def search_activities( "description": "Skip-the-line access to all three levels including the summit. Best views of Paris!", "availability": "Daily 9:30 AM - 11:00 PM", "best_time": "Early morning or sunset", - "booking_required": True + "booking_required": True, }, { "name": "Louvre Museum Guided Tour", @@ -359,7 +358,7 @@ def search_activities( "description": "Expert-guided tour covering masterpieces including Mona Lisa and Venus de Milo.", "availability": "Daily except Tuesdays, 9:00 AM entry", "best_time": "Morning entry recommended", - "booking_required": True + "booking_required": True, }, { "name": "Seine River Cruise", @@ -370,7 +369,7 @@ def search_activities( "description": "Scenic cruise past Notre-Dame, Eiffel Tower, and historic bridges.", "availability": "Every 30 minutes, 10:00 AM - 10:00 PM", "best_time": "Evening for illuminated monuments", - "booking_required": False + "booking_required": False, }, { "name": "Musée d'Orsay Visit", @@ -381,7 +380,7 @@ def search_activities( "description": "Impressionist masterpieces in a stunning Beaux-Arts railway station.", "availability": "Tuesday-Sunday 9:30 AM - 6:00 PM", "best_time": "Weekday mornings", - "booking_required": True + "booking_required": True, }, { "name": "Versailles Palace Day Trip", @@ -392,7 +391,7 @@ def search_activities( "description": "Explore the opulent palace and stunning gardens of Louis XIV (includes transport).", "availability": "Daily except Mondays, 8:00 AM departure", "best_time": "Full day trip", - "booking_required": True + "booking_required": True, }, { "name": "Montmartre Walking Tour", @@ -403,7 +402,7 @@ def search_activities( "description": "Discover the artistic heart of Paris, including Sacré-Cœur and artists' square.", "availability": "Daily at 10:00 AM and 2:00 PM", "best_time": "Morning or late afternoon", - "booking_required": False + "booking_required": False, }, { "name": "French Cooking Class", @@ -414,7 +413,7 @@ def search_activities( "description": "Learn to make classic French dishes like coq au vin and crème brûlée, then enjoy your creations.", "availability": "Tuesday-Saturday, 10:00 AM and 6:00 PM sessions", "best_time": "Morning or evening sessions", - "booking_required": True + "booking_required": True, }, { "name": "Wine & Cheese Tasting", @@ -425,7 +424,7 @@ def search_activities( "description": "Sample French wines and artisanal cheeses with expert sommelier guidance.", "availability": "Daily at 5:00 PM and 7:30 PM", "best_time": "Evening sessions", - "booking_required": True + "booking_required": True, }, { "name": "Food Market Tour", @@ -436,8 +435,8 @@ def search_activities( "description": "Explore authentic Parisian markets and taste local specialties like cheeses, pastries, and charcuterie.", "availability": "Tuesday, Thursday, Saturday mornings", "best_time": "Morning (markets are freshest)", - "booking_required": False - } + "booking_required": False, + }, ] activities = [act for act in all_activities if act["category"] == category] if category else all_activities @@ -450,7 +449,7 @@ def search_activities( "price": "$45", "rating": 4.7, "description": "Explore the historic downtown area with an expert guide", - "availability": "Daily at 10:00 AM and 2:00 PM" + "availability": "Daily at 10:00 AM and 2:00 PM", } ] @@ -460,7 +459,7 @@ def search_activities( "category": category, "activities_found": len(activities), "activities": activities, - "note": "Activity search results for Paris with sightseeing, culture, and culinary options" + "note": "Activity search results for Paris with sightseeing, culture, and culinary options", }) @@ -489,56 +488,68 @@ def get_activity_details( "languages": ["English", "French", "Spanish", "German", "Italian"], "max_group_size": "No limit", "rating": 4.8, - "reviews_count": 15234 + "reviews_count": 15234, }, "Louvre Museum Guided Tour": { "name": "Louvre Museum Guided Tour", "description": "Expert-guided tour of the world's largest art museum, focusing on must-see masterpieces including Mona Lisa, Venus de Milo, and Winged Victory.", "duration": "3 hours", "price": "$55 per person", - "included": ["Skip-the-line entry", "Expert art historian guide", "Headsets for groups over 6", "Museum highlights map"], + "included": [ + "Skip-the-line entry", + "Expert art historian guide", + "Headsets for groups over 6", + "Museum highlights map", + ], "meeting_point": "Glass Pyramid main entrance, look for guide with 'Louvre Tours' sign", "what_to_bring": ["Photo ID", "Comfortable shoes", "Camera (no flash)", "Water bottle"], "cancellation_policy": "Free cancellation up to 48 hours in advance", "languages": ["English", "French", "Spanish"], "max_group_size": 20, "rating": 4.7, - "reviews_count": 8921 + "reviews_count": 8921, }, "French Cooking Class": { "name": "French Cooking Class", "description": "Hands-on cooking experience where you'll learn to prepare classic French dishes like coq au vin, ratatouille, and crème brûlée under expert chef guidance.", "duration": "3 hours", "price": "$120 per person", - "included": ["All ingredients", "Chef instruction", "Apron and recipe booklet", "Wine pairing", "Lunch/dinner of your creations"], + "included": [ + "All ingredients", + "Chef instruction", + "Apron and recipe booklet", + "Wine pairing", + "Lunch/dinner of your creations", + ], "meeting_point": "Le Chef Cooking Studio, 15 Rue du Bac, 7th arrondissement", "what_to_bring": ["Appetite", "Camera for food photos"], "cancellation_policy": "Free cancellation up to 72 hours in advance", "languages": ["English", "French"], "max_group_size": 12, "rating": 4.9, - "reviews_count": 2341 - } + "reviews_count": 2341, + }, } - details = activity_details_map.get(activity_name, { - "name": activity_name, - "description": "An immersive experience that showcases the best of local culture and attractions.", - "duration": "3 hours", - "price": "$45 per person", - "included": ["Professional guide", "Entry fees"], - "meeting_point": "Central meeting location", - "what_to_bring": ["Comfortable shoes", "Camera"], - "cancellation_policy": "Free cancellation up to 24 hours in advance", - "languages": ["English"], - "max_group_size": 15, - "rating": 4.5, - "reviews_count": 100 - }) + details = activity_details_map.get( + activity_name, + { + "name": activity_name, + "description": "An immersive experience that showcases the best of local culture and attractions.", + "duration": "3 hours", + "price": "$45 per person", + "included": ["Professional guide", "Entry fees"], + "meeting_point": "Central meeting location", + "what_to_bring": ["Comfortable shoes", "Camera"], + "cancellation_policy": "Free cancellation up to 24 hours in advance", + "languages": ["English"], + "max_group_size": 15, + "rating": 4.5, + "reviews_count": 100, + }, + ) - return json.dumps({ - "activity_details": details - }) + return json.dumps({"activity_details": details}) # Mock booking confirmation tool @@ -566,13 +577,11 @@ def confirm_booking( "next_steps": [ "Check your email for booking details", "Arrive 30 minutes before scheduled time", - "Bring confirmation number and valid ID" - ] + "Bring confirmation number and valid ID", + ], } - return json.dumps({ - "confirmation": confirmation_data - }) + return json.dumps({"confirmation": confirmation_data}) # Mock hotel availability check tool @@ -602,12 +611,10 @@ def check_hotel_availability( "status": availability_status, "available_rooms": 8, "price_per_night": "$185", - "last_checked": datetime.now().isoformat() + "last_checked": datetime.now().isoformat(), } - return json.dumps({ - "availability": availability_data - }) + return json.dumps({"availability": availability_data}) # Mock flight availability check tool @@ -635,12 +642,10 @@ def check_flight_availability( "status": availability_status, "available_seats": 45, "price_per_passenger": "$520", - "last_checked": datetime.now().isoformat() + "last_checked": datetime.now().isoformat(), } - return json.dumps({ - "availability": availability_data - }) + return json.dumps({"availability": availability_data}) # Mock activity availability check tool @@ -668,12 +673,10 @@ def check_activity_availability( "status": availability_status, "available_spots": 15, "price_per_person": "$45", - "last_checked": datetime.now().isoformat() + "last_checked": datetime.now().isoformat(), } - return json.dumps({ - "availability": availability_data - }) + return json.dumps({"availability": availability_data}) # Mock payment processing tool @@ -701,12 +704,10 @@ def process_payment( "last_4_digits": payment_method.get("last_4", "****"), "booking_reference": booking_reference, "timestamp": datetime.now().isoformat(), - "receipt_url": f"https://payments.travelagency.com/receipt/{transaction_id}" + "receipt_url": f"https://payments.travelagency.com/receipt/{transaction_id}", } - return json.dumps({ - "payment_result": payment_result - }) + return json.dumps({"payment_result": payment_result}) # Mock payment validation tool @@ -742,9 +743,7 @@ def validate_payment_method( "payment_method_type": method_type, "validation_messages": validation_messages if not is_valid else ["Payment method is valid"], "supported_currencies": ["USD", "EUR", "GBP", "JPY"], - "processing_fee": "2.5%" + "processing_fee": "2.5%", } - return json.dumps({ - "validation_result": validation_result - }) + return json.dumps({"validation_result": validation_result}) diff --git a/python/samples/05-end-to-end/workflow_evaluation/run_evaluation.py b/python/samples/05-end-to-end/workflow_evaluation/run_evaluation.py index bd064058b9..6ad3641721 100644 --- a/python/samples/05-end-to-end/workflow_evaluation/run_evaluation.py +++ b/python/samples/05-end-to-end/workflow_evaluation/run_evaluation.py @@ -162,15 +162,13 @@ def run_evaluation( "data_mapping": {"response_id": "{{item.resp_id}}"}, "source": { "type": "file_content", - "content": [{"item": {"resp_id": resp_id}} for resp_id in selected_response_ids] + "content": [{"item": {"resp_id": resp_id}} for resp_id in selected_response_ids], }, }, } eval_run = openai_client.evals.runs.create( - eval_id=eval_object.id, - name="Multi-Agent Response Evaluation", - data_source=data_source + eval_id=eval_object.id, name="Multi-Agent Response Evaluation", data_source=data_source ) print(f"Evaluation run created: {eval_run.id}") @@ -183,10 +181,7 @@ def monitor_evaluation(openai_client: OpenAI, eval_object: EvalCreateResponse, e print("Waiting for evaluation to complete...") while eval_run.status not in ["completed", "failed"]: - eval_run = openai_client.evals.runs.retrieve( - run_id=eval_run.id, - eval_id=eval_object.id - ) + eval_run = openai_client.evals.runs.retrieve(run_id=eval_run.id, eval_id=eval_object.id) print(f"Status: {eval_run.status}") time.sleep(5) diff --git a/python/samples/README.md b/python/samples/README.md index eaeb47e7fe..148ace320d 100644 --- a/python/samples/README.md +++ b/python/samples/README.md @@ -29,13 +29,46 @@ Start with `01-get-started/` and work through the numbered files: pip install agent-framework --pre ``` -Set the following environment variables for the getting-started samples: +### Environment Variables +Samples call `load_dotenv()` to automatically load environment variables from a `.env` file in the `python/` directory. This is a convenience for local development and testing. + +**For local development**, set up your environment using any of these methods: + +**Option 1: Using a `.env` file** (recommended for local development): +1. Copy `.env.example` to `.env` in the `python/` directory: + ```bash + cp .env.example .env + ``` +2. Edit `.env` and set your values (API keys, endpoints, etc.) + +**Option 2: Export environment variables directly**: ```bash export AZURE_AI_PROJECT_ENDPOINT="your-foundry-project-endpoint" export AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME="gpt-4o" ``` +**Option 3: Using `env_file_path` parameter** (for per-client configuration): + +All client classes (e.g., `OpenAIChatClient`, `AzureOpenAIResponsesClient`) support an `env_file_path` parameter to load environment variables from a specific file: + +```python +from agent_framework.openai import OpenAIChatClient + +# Load from a custom .env file +client = OpenAIChatClient(env_file_path="path/to/custom.env") +``` + +This allows different clients to use different configuration files if needed. + +For the getting-started samples, you'll need at minimum: +```bash +AZURE_AI_PROJECT_ENDPOINT="your-foundry-project-endpoint" +AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME="gpt-4o" +``` + +**Note for production**: In production environments, set environment variables through your deployment platform (e.g., Azure App Settings, Kubernetes ConfigMaps/Secrets) rather than using `.env` files. The `load_dotenv()` call in samples will have no effect when a `.env` file is not present, allowing environment variables to be loaded from the system. + For Azure authentication, run `az login` before running samples. ## Note on XML tags diff --git a/python/samples/SAMPLE_GUIDELINES.md b/python/samples/SAMPLE_GUIDELINES.md index 2dfd2dbc4a..a40312614f 100644 --- a/python/samples/SAMPLE_GUIDELINES.md +++ b/python/samples/SAMPLE_GUIDELINES.md @@ -8,11 +8,12 @@ Every sample file should follow this order: 1. PEP 723 inline script metadata (if external dependencies are needed) 2. Copyright header: `# Copyright (c) Microsoft. All rights reserved.` -3. Required imports -4. Module docstring: `"""This sample demonstrates..."""` -5. Helper functions -6. Main function(s) demonstrating functionality -7. Entry point: `if __name__ == "__main__": asyncio.run(main())` +3. Required imports (including `from dotenv import load_dotenv`) +4. Environment variable loading: `load_dotenv()` +5. Module docstring: `"""This sample demonstrates..."""` +6. Helper functions +7. Main function(s) demonstrating functionality +8. Entry point: `if __name__ == "__main__": asyncio.run(main())` When modifying samples, update associated README files in the same or parent folders. @@ -35,6 +36,30 @@ When samples depend on external packages not included in the dev environment (e. This makes samples self-contained and runnable without installing extra packages into the dev environment. Do not add sample-only dependencies to the root `pyproject.toml` dev group. +## Environment Variables + +All samples that use environment variables (API keys, endpoints, etc.) must call `load_dotenv()` at the beginning of the file to load variables from a `.env` file. The `python-dotenv` package is already included as a dependency of `agent-framework-core`. + +```python +# Copyright (c) Microsoft. All rights reserved. + +import asyncio +import os + +from agent_framework.azure import AzureOpenAIResponsesClient +from azure.identity import AzureCliCredential +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() + +""" +Sample docstring explaining what the sample does. +""" +``` + +Users can create a `.env` file in the `python/` directory based on `.env.example` to set their environment variables without having to export them in their shell. + ## Syntax Checking Run `uv run poe samples-syntax` to check samples for syntax errors and missing imports from `agent_framework`. This uses a relaxed pyright configuration that validates imports without strict type checking. @@ -75,12 +100,12 @@ For the getting started samples and the concept samples, we should have the foll 2. A summary should be included underneath the imports that explains the purpose of the sample and required components/concepts to understand the sample. For example: ```python - ''' + """ This sample shows how to create a chatbot. This sample uses the following two main components: - a ChatCompletionService: This component is responsible for generating responses to user messages. - a ChatHistory: This component is responsible for keeping track of the chat history. The chatbot in this sample is called Mosscap, who responds to user messages with long flowery prose. - ''' + """ ``` 3. Mark the code with comments to explain the purpose of each section of the code. For example: @@ -98,13 +123,13 @@ For the getting started samples and the concept samples, we should have the foll 4. At the end of the sample, include a section that explains the expected output of the sample. For example: ```python - ''' + """ Sample output: User:> Why is the sky blue in one sentence? Mosscap:> The sky is blue due to the scattering of sunlight by the molecules in the Earth's atmosphere, a phenomenon known as Rayleigh scattering, which causes shorter blue wavelengths to become more prominent in our visual perception. - ''' + """ ``` For the demos, a README.md file must be included that explains the purpose of the demo and how to run it. The README.md file should include the following: diff --git a/python/samples/autogen-migration/orchestrations/01_round_robin_group_chat.py b/python/samples/autogen-migration/orchestrations/01_round_robin_group_chat.py index 9d11f9fc88..8c74a3b153 100644 --- a/python/samples/autogen-migration/orchestrations/01_round_robin_group_chat.py +++ b/python/samples/autogen-migration/orchestrations/01_round_robin_group_chat.py @@ -18,10 +18,15 @@ import asyncio from agent_framework import Message +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() async def run_autogen() -> None: """AutoGen's RoundRobinGroupChat for sequential agent orchestration.""" + from autogen_agentchat.agents import AssistantAgent from autogen_agentchat.conditions import TextMentionTermination from autogen_agentchat.teams import RoundRobinGroupChat diff --git a/python/samples/autogen-migration/orchestrations/02_selector_group_chat.py b/python/samples/autogen-migration/orchestrations/02_selector_group_chat.py index 6477b0af57..6f16e1dea9 100644 --- a/python/samples/autogen-migration/orchestrations/02_selector_group_chat.py +++ b/python/samples/autogen-migration/orchestrations/02_selector_group_chat.py @@ -18,10 +18,15 @@ import asyncio from agent_framework import Message +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() async def run_autogen() -> None: """AutoGen's SelectorGroupChat with LLM-based speaker selection.""" + from autogen_agentchat.agents import AssistantAgent from autogen_agentchat.conditions import MaxMessageTermination from autogen_agentchat.teams import SelectorGroupChat diff --git a/python/samples/autogen-migration/orchestrations/03_swarm.py b/python/samples/autogen-migration/orchestrations/03_swarm.py index a3c7a4f66e..a178ffcffe 100644 --- a/python/samples/autogen-migration/orchestrations/03_swarm.py +++ b/python/samples/autogen-migration/orchestrations/03_swarm.py @@ -16,13 +16,18 @@ """ import asyncio +from typing import Any from agent_framework import AgentResponseUpdate, WorkflowEvent -from typing import Any +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() async def run_autogen() -> None: """AutoGen's Swarm pattern with human-in-the-loop handoffs.""" + from autogen_agentchat.agents import AssistantAgent from autogen_agentchat.conditions import HandoffTermination, TextMentionTermination from autogen_agentchat.messages import HandoffMessage diff --git a/python/samples/autogen-migration/orchestrations/04_magentic_one.py b/python/samples/autogen-migration/orchestrations/04_magentic_one.py index a83f7cc33e..b6728b0e46 100644 --- a/python/samples/autogen-migration/orchestrations/04_magentic_one.py +++ b/python/samples/autogen-migration/orchestrations/04_magentic_one.py @@ -25,10 +25,15 @@ WorkflowEvent, ) from agent_framework.orchestrations import MagenticProgressLedger +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() async def run_autogen() -> None: """AutoGen's MagenticOneGroupChat for orchestrated collaboration.""" + from autogen_agentchat.agents import AssistantAgent from autogen_agentchat.teams import MagenticOneGroupChat from autogen_agentchat.ui import Console diff --git a/python/samples/autogen-migration/single_agent/01_basic_assistant_agent.py b/python/samples/autogen-migration/single_agent/01_basic_assistant_agent.py index 9f7ae98d6e..73a3caba02 100644 --- a/python/samples/autogen-migration/single_agent/01_basic_assistant_agent.py +++ b/python/samples/autogen-migration/single_agent/01_basic_assistant_agent.py @@ -18,9 +18,15 @@ import asyncio +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() + async def run_autogen() -> None: """Call AutoGen's AssistantAgent for a simple question.""" + from autogen_agentchat.agents import AssistantAgent from autogen_ext.models.openai import OpenAIChatCompletionClient diff --git a/python/samples/autogen-migration/single_agent/02_assistant_agent_with_tool.py b/python/samples/autogen-migration/single_agent/02_assistant_agent_with_tool.py index 0f2f254e07..aca868b9f2 100644 --- a/python/samples/autogen-migration/single_agent/02_assistant_agent_with_tool.py +++ b/python/samples/autogen-migration/single_agent/02_assistant_agent_with_tool.py @@ -17,9 +17,15 @@ import asyncio +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() + async def run_autogen() -> None: """AutoGen agent with a FunctionTool.""" + from autogen_agentchat.agents import AssistantAgent from autogen_core.tools import FunctionTool from autogen_ext.models.openai import OpenAIChatCompletionClient diff --git a/python/samples/autogen-migration/single_agent/03_assistant_agent_thread_and_stream.py b/python/samples/autogen-migration/single_agent/03_assistant_agent_thread_and_stream.py index 5e4854d1e3..c544880cb1 100644 --- a/python/samples/autogen-migration/single_agent/03_assistant_agent_thread_and_stream.py +++ b/python/samples/autogen-migration/single_agent/03_assistant_agent_thread_and_stream.py @@ -16,9 +16,15 @@ import asyncio +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() + async def run_autogen() -> None: """AutoGen agent with conversation history and streaming.""" + from autogen_agentchat.agents import AssistantAgent from autogen_agentchat.ui import Console from autogen_ext.models.openai import OpenAIChatCompletionClient diff --git a/python/samples/autogen-migration/single_agent/04_agent_as_tool.py b/python/samples/autogen-migration/single_agent/04_agent_as_tool.py index c8a73f66bc..489ec74c01 100644 --- a/python/samples/autogen-migration/single_agent/04_agent_as_tool.py +++ b/python/samples/autogen-migration/single_agent/04_agent_as_tool.py @@ -17,9 +17,15 @@ import asyncio +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() + async def run_autogen() -> None: """AutoGen's AgentTool for hierarchical agents with streaming.""" + from autogen_agentchat.agents import AssistantAgent from autogen_agentchat.tools import AgentTool from autogen_agentchat.ui import Console diff --git a/python/samples/semantic-kernel-migration/azure_ai_agent/01_basic_azure_ai_agent.py b/python/samples/semantic-kernel-migration/azure_ai_agent/01_basic_azure_ai_agent.py index 7c41841e09..b10f38f779 100644 --- a/python/samples/semantic-kernel-migration/azure_ai_agent/01_basic_azure_ai_agent.py +++ b/python/samples/semantic-kernel-migration/azure_ai_agent/01_basic_azure_ai_agent.py @@ -17,6 +17,11 @@ import asyncio +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() + async def run_semantic_kernel() -> None: from azure.identity.aio import AzureCliCredential diff --git a/python/samples/semantic-kernel-migration/azure_ai_agent/02_azure_ai_agent_with_code_interpreter.py b/python/samples/semantic-kernel-migration/azure_ai_agent/02_azure_ai_agent_with_code_interpreter.py index 8dbfcc7fe3..599fcf75ad 100644 --- a/python/samples/semantic-kernel-migration/azure_ai_agent/02_azure_ai_agent_with_code_interpreter.py +++ b/python/samples/semantic-kernel-migration/azure_ai_agent/02_azure_ai_agent_with_code_interpreter.py @@ -17,6 +17,11 @@ import asyncio +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() + async def run_semantic_kernel() -> None: from azure.identity.aio import AzureCliCredential diff --git a/python/samples/semantic-kernel-migration/azure_ai_agent/03_azure_ai_agent_threads_and_followups.py b/python/samples/semantic-kernel-migration/azure_ai_agent/03_azure_ai_agent_threads_and_followups.py index 9e83364024..4fb4de4085 100644 --- a/python/samples/semantic-kernel-migration/azure_ai_agent/03_azure_ai_agent_threads_and_followups.py +++ b/python/samples/semantic-kernel-migration/azure_ai_agent/03_azure_ai_agent_threads_and_followups.py @@ -12,6 +12,11 @@ import asyncio +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() + async def run_semantic_kernel() -> None: from azure.identity.aio import AzureCliCredential diff --git a/python/samples/semantic-kernel-migration/chat_completion/01_basic_chat_completion.py b/python/samples/semantic-kernel-migration/chat_completion/01_basic_chat_completion.py index 63db51fb43..50e98c74ca 100644 --- a/python/samples/semantic-kernel-migration/chat_completion/01_basic_chat_completion.py +++ b/python/samples/semantic-kernel-migration/chat_completion/01_basic_chat_completion.py @@ -17,9 +17,15 @@ import asyncio +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() + async def run_semantic_kernel() -> None: """Call SK's ChatCompletionAgent for a simple question.""" + from semantic_kernel.agents import ChatCompletionAgent from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion diff --git a/python/samples/semantic-kernel-migration/chat_completion/02_chat_completion_with_tool.py b/python/samples/semantic-kernel-migration/chat_completion/02_chat_completion_with_tool.py index cd31b55855..78d45862e1 100644 --- a/python/samples/semantic-kernel-migration/chat_completion/02_chat_completion_with_tool.py +++ b/python/samples/semantic-kernel-migration/chat_completion/02_chat_completion_with_tool.py @@ -16,6 +16,11 @@ import asyncio +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() + async def run_semantic_kernel() -> None: from semantic_kernel.agents import ChatCompletionAgent, ChatHistoryAgentThread diff --git a/python/samples/semantic-kernel-migration/chat_completion/03_chat_completion_thread_and_stream.py b/python/samples/semantic-kernel-migration/chat_completion/03_chat_completion_thread_and_stream.py index 78021a81ac..fc4658bfab 100644 --- a/python/samples/semantic-kernel-migration/chat_completion/03_chat_completion_thread_and_stream.py +++ b/python/samples/semantic-kernel-migration/chat_completion/03_chat_completion_thread_and_stream.py @@ -16,6 +16,11 @@ import asyncio +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() + async def run_semantic_kernel() -> None: from semantic_kernel.agents import ChatCompletionAgent, ChatHistoryAgentThread diff --git a/python/samples/semantic-kernel-migration/copilot_studio/01_basic_copilot_studio_agent.py b/python/samples/semantic-kernel-migration/copilot_studio/01_basic_copilot_studio_agent.py index 2c0d7261fb..a477181b26 100644 --- a/python/samples/semantic-kernel-migration/copilot_studio/01_basic_copilot_studio_agent.py +++ b/python/samples/semantic-kernel-migration/copilot_studio/01_basic_copilot_studio_agent.py @@ -12,6 +12,11 @@ import asyncio +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() + async def run_semantic_kernel() -> None: from semantic_kernel.agents import CopilotStudioAgent diff --git a/python/samples/semantic-kernel-migration/copilot_studio/02_copilot_studio_streaming.py b/python/samples/semantic-kernel-migration/copilot_studio/02_copilot_studio_streaming.py index a30aa58ff2..97ef158c53 100644 --- a/python/samples/semantic-kernel-migration/copilot_studio/02_copilot_studio_streaming.py +++ b/python/samples/semantic-kernel-migration/copilot_studio/02_copilot_studio_streaming.py @@ -12,6 +12,11 @@ import asyncio +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() + async def run_semantic_kernel() -> None: from semantic_kernel.agents import CopilotStudioAgent diff --git a/python/samples/semantic-kernel-migration/openai_assistant/01_basic_openai_assistant.py b/python/samples/semantic-kernel-migration/openai_assistant/01_basic_openai_assistant.py index 4b4bbb5e4a..1c0b5a3ae4 100644 --- a/python/samples/semantic-kernel-migration/openai_assistant/01_basic_openai_assistant.py +++ b/python/samples/semantic-kernel-migration/openai_assistant/01_basic_openai_assistant.py @@ -13,6 +13,11 @@ import asyncio import os +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() + ASSISTANT_MODEL = os.environ.get("OPENAI_ASSISTANT_MODEL", "gpt-4o-mini") diff --git a/python/samples/semantic-kernel-migration/openai_assistant/02_openai_assistant_with_code_interpreter.py b/python/samples/semantic-kernel-migration/openai_assistant/02_openai_assistant_with_code_interpreter.py index 6de655712b..b9407149d6 100644 --- a/python/samples/semantic-kernel-migration/openai_assistant/02_openai_assistant_with_code_interpreter.py +++ b/python/samples/semantic-kernel-migration/openai_assistant/02_openai_assistant_with_code_interpreter.py @@ -12,6 +12,11 @@ import asyncio +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() + async def run_semantic_kernel() -> None: from semantic_kernel.agents import OpenAIAssistantAgent diff --git a/python/samples/semantic-kernel-migration/openai_assistant/03_openai_assistant_function_tool.py b/python/samples/semantic-kernel-migration/openai_assistant/03_openai_assistant_function_tool.py index b6e5198d00..be395cafa6 100644 --- a/python/samples/semantic-kernel-migration/openai_assistant/03_openai_assistant_function_tool.py +++ b/python/samples/semantic-kernel-migration/openai_assistant/03_openai_assistant_function_tool.py @@ -14,11 +14,17 @@ import os from typing import Any +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() + ASSISTANT_MODEL = os.environ.get("OPENAI_ASSISTANT_MODEL", "gpt-4o-mini") async def fake_weather_lookup(city: str, day: str) -> dict[str, Any]: """Pretend to call a weather service.""" + return { "city": city, "day": day, diff --git a/python/samples/semantic-kernel-migration/openai_responses/01_basic_responses_agent.py b/python/samples/semantic-kernel-migration/openai_responses/01_basic_responses_agent.py index a891a22335..556407c969 100644 --- a/python/samples/semantic-kernel-migration/openai_responses/01_basic_responses_agent.py +++ b/python/samples/semantic-kernel-migration/openai_responses/01_basic_responses_agent.py @@ -12,6 +12,11 @@ import asyncio +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() + async def run_semantic_kernel() -> None: from semantic_kernel.agents import OpenAIResponsesAgent diff --git a/python/samples/semantic-kernel-migration/openai_responses/02_responses_agent_with_tool.py b/python/samples/semantic-kernel-migration/openai_responses/02_responses_agent_with_tool.py index b5bd864c08..ed2609783c 100644 --- a/python/samples/semantic-kernel-migration/openai_responses/02_responses_agent_with_tool.py +++ b/python/samples/semantic-kernel-migration/openai_responses/02_responses_agent_with_tool.py @@ -12,6 +12,11 @@ import asyncio +from dotenv import load_dotenv + +# Load environment variables from .env file +load_dotenv() + async def run_semantic_kernel() -> None: from semantic_kernel.agents import OpenAIResponsesAgent @@ -37,8 +42,7 @@ def add(self, a: float, b: float) -> float: async def run_agent_framework() -> None: - from agent_framework import Agent - from agent_framework import tool + from agent_framework import Agent, tool from agent_framework.openai import OpenAIResponsesClient @tool(name="add", description="Add two numbers") diff --git a/python/samples/semantic-kernel-migration/openai_responses/03_responses_agent_structured_output.py b/python/samples/semantic-kernel-migration/openai_responses/03_responses_agent_structured_output.py index ee94dcd761..277dbbda40 100644 --- a/python/samples/semantic-kernel-migration/openai_responses/03_responses_agent_structured_output.py +++ b/python/samples/semantic-kernel-migration/openai_responses/03_responses_agent_structured_output.py @@ -12,8 +12,12 @@ import asyncio +from dotenv import load_dotenv from pydantic import BaseModel +# Load environment variables from .env file +load_dotenv() + class ReleaseBrief(BaseModel): feature: str diff --git a/python/samples/semantic-kernel-migration/orchestrations/concurrent_basic.py b/python/samples/semantic-kernel-migration/orchestrations/concurrent_basic.py index 2a646a9d11..38133dbad1 100644 --- a/python/samples/semantic-kernel-migration/orchestrations/concurrent_basic.py +++ b/python/samples/semantic-kernel-migration/orchestrations/concurrent_basic.py @@ -19,11 +19,15 @@ from agent_framework.azure import AzureOpenAIChatClient from agent_framework.orchestrations import ConcurrentBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv from semantic_kernel.agents import ChatCompletionAgent, ConcurrentOrchestration from semantic_kernel.agents.runtime import InProcessRuntime from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion from semantic_kernel.contents import ChatMessageContent +# Load environment variables from .env file +load_dotenv() + PROMPT = "Explain the concept of temperature from multiple scientific perspectives." diff --git a/python/samples/semantic-kernel-migration/orchestrations/group_chat.py b/python/samples/semantic-kernel-migration/orchestrations/group_chat.py index 2211327c39..c0d7aa3797 100644 --- a/python/samples/semantic-kernel-migration/orchestrations/group_chat.py +++ b/python/samples/semantic-kernel-migration/orchestrations/group_chat.py @@ -20,6 +20,7 @@ from agent_framework.azure import AzureOpenAIChatClient, AzureOpenAIResponsesClient from agent_framework.orchestrations import GroupChatBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv from semantic_kernel.agents import ChatCompletionAgent, GroupChatOrchestration from semantic_kernel.agents.orchestration.group_chat import ( BooleanResult, @@ -41,6 +42,9 @@ else: from typing_extensions import override # pragma: no cover +# Load environment variables from .env file +load_dotenv() + DISCUSSION_TOPIC = "What are the essential steps for launching a community hackathon?" diff --git a/python/samples/semantic-kernel-migration/orchestrations/handoff.py b/python/samples/semantic-kernel-migration/orchestrations/handoff.py index e23e4002d0..c235da8fe8 100644 --- a/python/samples/semantic-kernel-migration/orchestrations/handoff.py +++ b/python/samples/semantic-kernel-migration/orchestrations/handoff.py @@ -22,6 +22,7 @@ from agent_framework.azure import AzureOpenAIChatClient from agent_framework.orchestrations import HandoffAgentUserRequest, HandoffBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv from semantic_kernel.agents import Agent, ChatCompletionAgent, HandoffOrchestration, OrchestrationHandoffs from semantic_kernel.agents.runtime import InProcessRuntime from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion @@ -39,6 +40,8 @@ else: pass # pragma: no cover +# Load environment variables from .env file +load_dotenv() CUSTOMER_PROMPT = "I need help with order 12345. I want a replacement and need to know when it will arrive." SCRIPTED_RESPONSES = [ @@ -125,6 +128,7 @@ def build_semantic_kernel_agents() -> tuple[list[Agent], OrchestrationHandoffs]: def _sk_streaming_callback(message: StreamingChatMessageContent, is_final: bool) -> None: """Display SK agent messages as they stream.""" + global _sk_new_message if _sk_new_message: print(f"{message.name}: ", end="", flush=True) diff --git a/python/samples/semantic-kernel-migration/orchestrations/magentic.py b/python/samples/semantic-kernel-migration/orchestrations/magentic.py index edf64e59f3..5566df1ab1 100644 --- a/python/samples/semantic-kernel-migration/orchestrations/magentic.py +++ b/python/samples/semantic-kernel-migration/orchestrations/magentic.py @@ -13,11 +13,11 @@ import asyncio from collections.abc import Sequence -from typing import cast from agent_framework import Agent from agent_framework.openai import OpenAIChatClient, OpenAIResponsesClient from agent_framework.orchestrations import MagenticBuilder +from dotenv import load_dotenv from semantic_kernel.agents import ( ChatCompletionAgent, MagenticOrchestration, @@ -28,6 +28,9 @@ from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion, OpenAISettings from semantic_kernel.contents import ChatMessageContent +# Load environment variables from .env file +load_dotenv() + PROMPT = ( "I am preparing a report on the energy efficiency of different machine learning model architectures. " "Compare the estimated training and inference energy consumption of ResNet-50, BERT-base, and GPT-2 " @@ -157,9 +160,7 @@ async def run_agent_framework_example(prompt: str) -> str | None: client=OpenAIChatClient(), ) - workflow = MagenticBuilder( - participants=[researcher, coder], manager_agent=manager_agent - ).build() + workflow = MagenticBuilder(participants=[researcher, coder], manager_agent=manager_agent).build() final_text: str | None = None async for event in workflow.run(prompt, stream=True): diff --git a/python/samples/semantic-kernel-migration/orchestrations/sequential.py b/python/samples/semantic-kernel-migration/orchestrations/sequential.py index c678bc22b8..af3cf973aa 100644 --- a/python/samples/semantic-kernel-migration/orchestrations/sequential.py +++ b/python/samples/semantic-kernel-migration/orchestrations/sequential.py @@ -19,11 +19,15 @@ from agent_framework.azure import AzureOpenAIChatClient from agent_framework.orchestrations import SequentialBuilder from azure.identity import AzureCliCredential +from dotenv import load_dotenv from semantic_kernel.agents import Agent, ChatCompletionAgent, SequentialOrchestration from semantic_kernel.agents.runtime import InProcessRuntime from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion from semantic_kernel.contents import ChatMessageContent +# Load environment variables from .env file +load_dotenv() + PROMPT = "Write a tagline for a budget-friendly eBike." diff --git a/python/samples/semantic-kernel-migration/processes/fan_out_fan_in_process.py b/python/samples/semantic-kernel-migration/processes/fan_out_fan_in_process.py index 56444b99bb..37e210e80b 100644 --- a/python/samples/semantic-kernel-migration/processes/fan_out_fan_in_process.py +++ b/python/samples/semantic-kernel-migration/processes/fan_out_fan_in_process.py @@ -21,6 +21,7 @@ # region Agent Framework imports ###################################################################### from agent_framework import Executor, WorkflowBuilder, WorkflowContext, handler +from dotenv import load_dotenv from pydantic import BaseModel, Field ###################################################################### @@ -39,6 +40,9 @@ from semantic_kernel.processes.kernel_process import KernelProcess from semantic_kernel.processes.local_runtime.local_kernel_process import LocalKernelProcessContext +# Load environment variables from .env file +load_dotenv() + async def _start_local_kernel_process( *, diff --git a/python/samples/semantic-kernel-migration/processes/nested_process.py b/python/samples/semantic-kernel-migration/processes/nested_process.py index 7e04f68cf1..ee8d889229 100644 --- a/python/samples/semantic-kernel-migration/processes/nested_process.py +++ b/python/samples/semantic-kernel-migration/processes/nested_process.py @@ -28,6 +28,7 @@ WorkflowExecutor, handler, ) +from dotenv import load_dotenv from pydantic import BaseModel, Field ###################################################################### @@ -48,9 +49,11 @@ ###################################################################### # endregion ###################################################################### - logging.basicConfig(level=logging.WARNING) +# Load environment variables from .env file +load_dotenv() + class ProcessEvents(Enum): START_PROCESS = "StartProcess"