### Simple Echo Agent Setup Source: https://github.com/microsoft/agents-for-python/blob/main/libraries/microsoft-agents-hosting-core/readme.md Sets up a basic agent application with memory storage, connection management, and an adapter. This example demonstrates the core components needed to initialize an agent and includes a message handler that echoes user input. ```python agents_sdk_config = load_configuration_from_env(environ) STORAGE = MemoryStorage() CONNECTION_MANAGER = MsalConnectionManager(**agents_sdk_config) ADAPTER = CloudAdapter(connection_manager=CONNECTION_MANAGER) AUTHORIZATION = Authorization(STORAGE, CONNECTION_MANAGER, **agents_sdk_config) AGENT_APP = AgentApplication[TurnState]( storage=STORAGE, adapter=ADAPTER, authorization=AUTHORIZATION, **agents_sdk_config ) @AGENT_APP.activity("message") async def on_message(context: TurnContext, state: TurnState): await context.send_activity(f"You said: {context.activity.text}") ... start_server( agent_application=AGENT_APP, auth_configuration=CONNECTION_MANAGER.get_default_connection_configuration(), ) ``` -------------------------------- ### Manual Development Setup Source: https://github.com/microsoft/agents-for-python/blob/main/CLAUDE.md Manually set up the Python virtual environment and install libraries in editable mode. Ensure Python 3.10+ is installed. ```bash python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate # Install all libraries in editable mode pip install -e ./libraries/microsoft-agents-activity/ --config-settings editable_mode=compat pip install -e ./libraries/microsoft-agents-hosting-core/ --config-settings editable_mode=compat pip install -e ./libraries/microsoft-agents-authentication-msal/ --config-settings editable_mode=compat pip install -e ./libraries/microsoft-agents-copilotstudio-client/ --config-settings editable_mode=compat pip install -e ./libraries/microsoft-agents-hosting-aiohttp/ --config-settings editable_mode=compat pip install -e ./libraries/microsoft-agents-hosting-teams/ --config-settings editable_mode=compat pip install -e ./libraries/microsoft-agents-storage-blob/ --config-settings editable_mode=compat pip install -e ./libraries/microsoft-agents-storage-cosmos/ --config-settings editable_mode=compat pip install -e ./libraries/microsoft-agents-hosting-fastapi/ --config-settings editable_mode=compat # Install development dependencies pip install -r dev_dependencies.txt # Setup pre-commit hooks pre-commit install ``` -------------------------------- ### Basic FastAPI Agent Setup Source: https://github.com/microsoft/agents-for-python/blob/main/libraries/microsoft-agents-hosting-fastapi/readme.md Set up a basic FastAPI application to handle agent messages. This example demonstrates how to initialize the CloudAdapter and AgentApplication, and then use start_agent_process to handle incoming requests. ```python from fastapi import FastAPI, Request from microsoft_agents.hosting.fastapi import start_agent_process, CloudAdapter from microsoft_agents.hosting.core.app import AgentApplication app = FastAPI() adapter = CloudAdapter() agent_app = AgentApplication() @app.post("/api/messages") async def messages(request: Request): return await start_agent_process(request, agent_app, adapter) ``` -------------------------------- ### Manual Agent Testing Setup Source: https://github.com/microsoft/agents-for-python/blob/main/dev/testing/microsoft-agents-testing/docs/MOTIVATION.md This code demonstrates the manual setup required to test an echo agent without the framework. It involves obtaining a token, starting a callback server, constructing activity JSON, sending the message, and verifying the response. ```python import aiohttp import asyncio import json from aiohttp import web APP_ID, APP_SECRET, TENANT_ID = "...", "...", "..." async def get_token() -> str: async with aiohttp.ClientSession() as session: async with session.post( f"https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token", data={ "grant_type": "client_credentials", "client_id": APP_ID, "client_secret": APP_SECRET, "scope": f"{APP_ID}/.default", }, ) as resp: return (await resp.json())["access_token"] collected = [] async def _callback_handler(request): collected.append(await request.json()) return web.Response(text="OK") callback_app = web.Application() callback_app.router.add_post("/v3/conversations/{path:.*}", _callback_handler) runner = web.AppRunner(callback_app) activity = { "type": "message", "text": "Hello!", "channelId": "test", "conversation": {"id": "test-conv-123"}, "from": {"id": "user-1", "name": "Test User"}, "recipient": {"id": "bot-1", "name": "My Bot"}, "serviceUrl": "http://localhost:9378/v3/conversations/", } async def test_echo(): await runner.setup() site = web.TCPSite(runner, "localhost", 9378) await site.start() token = await get_token() async with aiohttp.ClientSession() as session: async with session.post( "http://localhost:3978/api/messages", json=activity, headers={"Authorization": f"Bearer {token}"}, ) as resp: assert resp.status == 200 await asyncio.sleep(2) # hope the callback arrives in time await runner.cleanup() assert any("Hello" in json.dumps(r) for r in collected) ``` -------------------------------- ### Install the Copilot Studio Client Library Source: https://github.com/microsoft/agents-for-python/blob/main/libraries/microsoft-agents-copilotstudio-client/readme.md Install the library using pip. ```bash pip install microsoft-agents-copilotstudio-client ``` -------------------------------- ### Linux/macOS Dev Setup Script Source: https://github.com/microsoft/agents-for-python/blob/main/CLAUDE.md This script automates the development environment setup for Linux and macOS users. Execute it to install necessary dependencies. ```bash scripts/dev_setup.sh ``` -------------------------------- ### Setup Development Environment for Teams Extension Samples Source: https://github.com/microsoft/agents-for-python/blob/main/test_samples/teams_extension/README.md Run these commands from the repo root to set up your development environment. Ensure you install the necessary Teams API package and configure your environment variables. ```bash . ./scripts/dev_setup.sh # or scripts/dev_setup.ps1 on Windows ``` ```bash pip install microsoft-teams-api # only-binary may be needed on Windows: pip install --only-binary=:all: microsoft-teams-api ``` ```bash cp test_samples/teams_extension/env.TEMPLATE test_samples/teams_extension/.env ``` ```bash # Fill in CLIENTID / CLIENTSECRET / TENANTID in the .env ``` -------------------------------- ### Run Quickstart Script Source: https://github.com/microsoft/agents-for-python/blob/main/dev/testing/microsoft-agents-testing/docs/SAMPLES.md Command to execute the basic agent interaction sample. ```bash python docs/samples/quickstart.py ``` -------------------------------- ### Install microsoft-agents-storage-cosmos Source: https://github.com/microsoft/agents-for-python/blob/main/libraries/microsoft-agents-storage-cosmos/readme.md Install the Cosmos DB storage package using pip. ```bash pip install microsoft-agents-storage-cosmos ``` -------------------------------- ### Install microsoft-agents-hosting-core Source: https://github.com/microsoft/agents-for-python/blob/main/libraries/microsoft-agents-hosting-core/readme.md Install the core library for Microsoft Agents hosting using pip. ```bash pip install microsoft-agents-hosting-core ``` -------------------------------- ### Set up and start the agent Source: https://github.com/microsoft/agents-for-python/blob/main/test_samples/teams_extension/TESTING_SEARCH_QUERY.md Navigate to the agent's directory, copy the environment template, and edit the `.env` file with your Azure AD app registration details. Then, start the Python agent. ```powershell cd test_samples/teams_extension copy env.TEMPLATE .env #edit .env → fill CLIENTID/CLIENTSECRET/TENANTID (any valid Azure AD app reg works for Playground) python message_extensions_agent.py ``` -------------------------------- ### Install Microsoft Agents Activity Source: https://github.com/microsoft/agents-for-python/blob/main/libraries/microsoft-agents-activity/readme.md Install the library using pip. ```bash pip install microsoft-agents-activity ``` -------------------------------- ### Install microsoft-agents-storage-blob Source: https://github.com/microsoft/agents-for-python/blob/main/libraries/microsoft-agents-storage-blob/readme.md Install the package using pip. ```bash pip install microsoft-agents-storage-blob ``` -------------------------------- ### Run Extension Starter Sample Source: https://github.com/microsoft/agents-for-python/blob/main/test_samples/extensions/extension-starter/README.md Execute the sample extension using Python. This command is used to start the sample application. ```bash python -m src.sample.main ``` -------------------------------- ### Start Server with Default Connection Configuration Source: https://github.com/microsoft/agents-for-python/blob/main/libraries/microsoft-agents-authentication-msal/readme.md Initiates the server by starting the agent application with the default authentication configuration obtained from the connection manager. ```python from .start_server import start_server start_server( agent_application=AGENT_APP, auth_configuration=CONNECTION_MANAGER.get_default_connection_configuration(), ) ``` -------------------------------- ### Windows Dev Setup Script Source: https://github.com/microsoft/agents-for-python/blob/main/CLAUDE.md This PowerShell script automates the development environment setup for Windows users. Run it to install required tools and libraries. ```powershell scripts/dev_setup.ps1 ``` -------------------------------- ### Setup Environment Variables Source: https://github.com/microsoft/agents-for-python/blob/main/test_samples/proactive/README.md Copy the template and fill in your Azure Bot registration details and OAuth connection name. ```bash cp env.TEMPLATE .env # Fill in CLIENT_ID, CLIENT_SECRET, TENANT_ID, and the OAuth connection name ``` -------------------------------- ### Install Microsoft Agents Hosting Dialogs Source: https://github.com/microsoft/agents-for-python/blob/main/libraries/microsoft-agents-hosting-dialogs/readme.md Install the dialogs library using pip. ```bash pip install microsoft-agents-hosting-dialogs ``` -------------------------------- ### Install Microsoft Agents Hosting FastAPI Source: https://github.com/microsoft/agents-for-python/blob/main/libraries/microsoft-agents-hosting-fastapi/readme.md Install the library using pip. This command installs the necessary package for integrating Microsoft Agents with FastAPI. ```bash pip install microsoft-agents-hosting-fastapi ``` -------------------------------- ### App-style Agent with AgentApplication and Decorator Routing Source: https://context7.com/microsoft/agents-for-python/llms.txt Example of an app-style agent using `AgentApplication` with decorator routing for handling incoming activities. This setup includes basic message handling, welcome messages, and error handling, integrated with an aiohttp web server. ```python import sys from os import environ, path from dotenv import load_dotenv from microsoft_agents.activity import load_configuration_from_env, ActivityTypes from microsoft_agents.authentication.msal import MsalConnectionManager from microsoft_agents.hosting.aiohttp import CloudAdapter, start_agent_process from microsoft_agents.hosting.core import ( AgentApplication, Authorization, MemoryStorage, MessageFactory, TurnContext, TurnState, ) from aiohttp import web load_dotenv(path.join(path.dirname(__file__), ".env")) agents_sdk_config = load_configuration_from_env(environ) storage = MemoryStorage() connection_manager = MsalConnectionManager(**agents_sdk_config) adapter = CloudAdapter(connection_manager=connection_manager) authorization = Authorization(storage, connection_manager, **agents_sdk_config) app = AgentApplication[TurnState]( storage=storage, adapter=adapter, authorization=authorization, **agents_sdk_config, ) @app.conversation_update("membersAdded") async def on_welcome(context: TurnContext, state: TurnState): await context.send_activity("Hello! Send me a message.") return True @app.message(re.compile(r".*")) # match any message text async def on_message(context: TurnContext, state: TurnState): user_text = context.activity.text or "" await context.send_activity(MessageFactory.text(f"You said: {user_text}")) return True @app.error async def on_error(context: TurnContext, err: Exception): print(f"Error: {err}", file=sys.stderr) await context.send_activity("An error occurred.") # aiohttp server wiring async def messages(request: web.Request): response = await start_agent_process(request, app, adapter) return response or web.Response(status=202) web_app = web.Application() web_app.router.add_post("/api/messages", messages) web.run_app(web_app, host="localhost", port=3978) ``` -------------------------------- ### Install Microsoft Agents Hosting aiohttp Source: https://github.com/microsoft/agents-for-python/blob/main/libraries/microsoft-agents-hosting-aiohttp/readme.md Install the library using pip. Ensure you have Python 3.10+ and aiohttp 3.11.11+. ```bash pip install microsoft-agents-hosting-aiohttp ``` -------------------------------- ### Install Dependencies Source: https://github.com/microsoft/agents-for-python/blob/main/test_samples/fastapi/README.md Install project dependencies using pip. ```bash pip install -r requirements.txt ``` -------------------------------- ### Simple Echo Agent Setup Source: https://github.com/microsoft/agents-for-python/blob/main/libraries/microsoft-agents-hosting-aiohttp/readme.md Configure and run a basic echo agent. This involves loading configuration, setting up storage, connection management, and defining an activity handler for messages. ```python agents_sdk_config = load_configuration_from_env(environ) STORAGE = MemoryStorage() CONNECTION_MANAGER = MsalConnectionManager(**agents_sdk_config) ADAPTER = CloudAdapter(connection_manager=CONNECTION_MANAGER) AUTHORIZATION = Authorization(STORAGE, CONNECTION_MANAGER, **agents_sdk_config) AGENT_APP = AgentApplication[TurnState]( storage=STORAGE, adapter=ADAPTER, authorization=AUTHORIZATION, **agents_sdk_config ) @AGENT_APP.activity("message") async def on_message(context: TurnContext, state: TurnState): await context.send_activity(f"You said: {context.activity.text}") start_server( agent_application=AGENT_APP, auth_configuration=CONNECTION_MANAGER.get_default_connection_configuration(), ) ``` -------------------------------- ### Install Microsoft Agents Libraries Source: https://github.com/microsoft/agents-for-python/blob/main/test_samples/fastapi/README.md Install Microsoft Agents libraries from the local repository. ```bash pip install -e libraries/microsoft-agents-hosting-fastapi pip install -e libraries/microsoft-agents-hosting-core pip install -e libraries/microsoft-agents-authentication-msal pip install -e libraries/microsoft-agents-activity ``` -------------------------------- ### Run Development Setup Script (Linux/macOS) Source: https://github.com/microsoft/agents-for-python/blob/main/scripts/README.md Execute the shell script to set up the development environment from the project's root directory. ```bash . ./scripts/dev_setup.sh ``` -------------------------------- ### Install microsoft-agents-authentication-msal Source: https://github.com/microsoft/agents-for-python/blob/main/libraries/microsoft-agents-authentication-msal/readme.md Install the MSAL authentication library for Microsoft Agents using pip. ```bash pip install microsoft-agents-authentication-msal ``` -------------------------------- ### Run Authorization Agent Source: https://github.com/microsoft/agents-for-python/blob/main/test_samples/fastapi/README.md Start the authorization agent sample. It will run on http://localhost:3978 by default. ```bash python authorization_agent.py ``` -------------------------------- ### Install Microsoft Agents Testing Framework Source: https://github.com/microsoft/agents-for-python/blob/main/dev/testing/microsoft-agents-testing/docs/README.md Installs the testing framework in editable mode from a local path. ```bash pip install -e ./microsoft-agents-testing/ ``` -------------------------------- ### Multi-Client Setup with Activity Templates Source: https://github.com/microsoft/agents-for-python/blob/main/dev/testing/microsoft-agents-testing/docs/SAMPLES.md Illustrates creating multiple clients from a single factory, each with a custom `ActivityTemplate` to define sender identity. Also covers transcript scoping. ```python async with scenario.run() as factory: alice = await factory(ClientConfig(activity_template=ActivityTemplate( **{"from.id": "alice", "from.name": "Alice"} ))) bob = await factory(ClientConfig(activity_template=ActivityTemplate( **{"from.id": "bob", "from.name": "Bob"} ))) ``` -------------------------------- ### Run App Style Agent Sample Source: https://github.com/microsoft/agents-for-python/blob/main/CLAUDE.md Navigate to the app_style sample directory and run the empty_agent.py script using Python. This is a basic example for AgentApplication. ```bash cd test_samples/app_style python empty_agent.py ``` -------------------------------- ### Install Testing Framework Source: https://github.com/microsoft/agents-for-python/blob/main/dev/testing/microsoft-agents-testing/README.md Command to install the Microsoft Agents Testing Framework in editable mode. ```bash pip install -e ./microsoft-agents-testing/ --config-settings editable_mode=compat ``` -------------------------------- ### Run Empty Agent Source: https://github.com/microsoft/agents-for-python/blob/main/test_samples/fastapi/README.md Start the empty agent sample. It will run on http://localhost:3978 by default. ```bash python empty_agent.py ``` -------------------------------- ### Run Development Setup Script (Windows) Source: https://github.com/microsoft/agents-for-python/blob/main/scripts/README.md Execute the PowerShell script to set up the development environment from the project's root directory. ```powershell . ./scripts/dev_setup.ps1 ``` -------------------------------- ### Install Test Packages Source: https://github.com/microsoft/agents-for-python/blob/main/test_samples/README.md Installs multiple Microsoft Agents related packages from PyPI into the activated virtual environment using pip. ```bash pip install microsoft-agents-activity pip install microsoft-agents-authorization pip install microsoft-agents-connector pip install microsoft-agents-client pip install microsoft-agents-hosting-core pip install microsoft-agents-authentication-msal pip install microsoft-agents-copilotstudio-client pip install microsoft-agents-hosting-core-aiohttp pip install microsoft-agents-storage-core ``` -------------------------------- ### Install Dev Tunnels CLI Source: https://github.com/microsoft/agents-for-python/blob/main/DevInstructions.md Install the Dev Tunnels command-line interface using winget. ```powershell winget install Microsoft.devtunnel ``` -------------------------------- ### Install M365 Agents Playground via winget Source: https://github.com/microsoft/agents-for-python/blob/main/DevInstructions.md Install the M365 Agents Playground using the winget package manager. ```powershell winget install --id=Microsoft.M365AgentsPlayground -e ``` -------------------------------- ### Run Teams Extension Samples Source: https://github.com/microsoft/agents-for-python/blob/main/test_samples/teams_extension/README.md Navigate to the test_samples/teams_extension directory and run the desired Python script to start the agent. The agent will listen on http://localhost:3978/api/messages. ```bash cd test_samples/teams_extension ``` ```bash python message_extensions_agent.py ``` ```bash # or ``` ```bash python task_modules_agent.py ``` ```bash # or ``` ```bash python meeting_events_agent.py ``` -------------------------------- ### Install Editable Libraries Source: https://github.com/microsoft/agents-for-python/blob/main/DevInstructions.md Install various agent libraries in editable mode. This allows for direct modification and testing of library code without reinstallation. ```bash pip install -e ./libraries/microsoft-agents-activity/ --config-settings editable_mode=compat ``` ```bash pip install -e ./libraries/microsoft-agents-hosting-core/ --config-settings editable_mode=compat ``` ```bash pip install -e ./libraries/microsoft-agents-authentication-msal/ --config-settings editable_mode=compat ``` ```bash pip install -e ./libraries/microsoft-agents-copilotstudio-client/ --config-settings editable_mode=compat ``` ```bash pip install -e ./libraries/microsoft-agents-hosting-aiohttp/ --config-settings editable_mode=compat ``` ```bash pip install -e ./libraries/microsoft-agents-hosting-teams/ --config-settings editable_mode=compat ``` ```bash pip install -e ./libraries/microsoft-agents-storage-blob/ --config-settings editable_mode=compat ``` ```bash pip install -e ./libraries/microsoft-agents-storage-cosmos/ --config-settings editable_mode=compat ``` ```bash pip install -e ./libraries/microsoft-agents-hosting-fastapi/ --config-settings editable_mode=compat ``` -------------------------------- ### Install Microsoft 365 Agents SDK Packages Source: https://context7.com/microsoft/agents-for-python/llms.txt Install individual packages for the Microsoft 365 Agents SDK as needed for your project. ```bash pip install microsoft-agents-activity pip install microsoft-agents-hosting-core pip install microsoft-agents-hosting-aiohttp # or microsoft-agents-hosting-fastapi pip install microsoft-agents-hosting-teams pip install microsoft-agents-authentication-msal pip install microsoft-agents-storage-blob pip install microsoft-agents-storage-cosmos pip install microsoft-agents-copilotstudio-client ``` -------------------------------- ### start_conversation() Source: https://github.com/microsoft/agents-for-python/blob/main/libraries/microsoft-agents-copilotstudio-client/readme.md Start a new conversation with basic options. ```APIDOC ## start_conversation() ### Description Start a new conversation with basic options. ### Method `start_conversation()` ``` -------------------------------- ### Agent Test Class Example Source: https://github.com/microsoft/agents-for-python/blob/main/dev/testing/microsoft-agents-testing/docs/API.md Example of an agent test class using the agent_client fixture to send messages and assert responses. Also shows direct storage inspection. ```python @pytest.mark.agent_test(my_scenario) class TestAgent: async def test_hello(self, agent_client): await agent_client.send("Hi!", wait=0.2) agent_client.expect().that_for_any(text="~Hi") async def test_state(self, agent_client, storage): await agent_client.send("Hello", wait=0.2) # inspect storage directly ``` -------------------------------- ### Check Python Version Source: https://github.com/microsoft/agents-for-python/blob/main/scripts/README.md Verify that your default Python version is at least 3.10 before running setup scripts. ```bash python --version ``` -------------------------------- ### Host Dev Tunnel Source: https://github.com/microsoft/agents-for-python/blob/main/DevInstructions.md Start hosting the created Dev Tunnel. Remember to record the provided URLs for later use. ```bash devtunnel host -a my-tunnel ``` -------------------------------- ### ConnectionSettings.populate_from_environment() - Load Settings from Environment Variables Source: https://context7.com/microsoft/agents-for-python/llms.txt A static helper method to construct `ConnectionSettings` by reading configuration from environment variables, allowing for flexible setup and optional programmatic overrides. ```APIDOC ## ConnectionSettings.populate_from_environment() Static helper to build a `ConnectionSettings` dictionary from environment variables, with optional programmatic overrides. ### Usage Set the following environment variables: - `ENVIRONMENT_ID`: The ID of the Power Platform environment. - `AGENT_IDENTIFIER`: The schema name of the agent. - `CLOUD`: The Power Platform cloud (defaults to "PROD"). - `COPILOT_AGENT_TYPE`: The type of Copilot agent (defaults to "PUBLISHED"). - `DIRECT_CONNECT_URL`: Optional direct connect URL. - `USE_EXPERIMENTAL_ENDPOINT`: Boolean to enable experimental endpoints. - `ENABLE_DIAGNOSTICS`: Boolean to enable diagnostics. ```python import os from microsoft_agents.copilotstudio.client import ConnectionSettings, CopilotClient # Expected environment variables: # ENVIRONMENT_ID, AGENT_IDENTIFIER, CLOUD (default "PROD"), # COPILOT_AGENT_TYPE (default "PUBLISHED"), DIRECT_CONNECT_URL (optional), # USE_EXPERIMENTAL_ENDPOINT, ENABLE_DIAGNOSTICS os.environ["ENVIRONMENT_ID"] = "00000000-0000-0000-0000-000000000001" os.environ["AGENT_IDENTIFIER"] = "my-copilot-agent" os.environ["CLOUD"] = "PROD" kwargs = ConnectionSettings.populate_from_environment() settings = ConnectionSettings(**kwargs) # Direct connect URL shortcut (skips environment-ID lookup): settings_direct = ConnectionSettings( environment_id="", agent_identifier="", direct_connect_url="https://my-island.api.powerplatform.com/powervirtualagents/." ) ``` ``` -------------------------------- ### Create Copilot Client with DirectConnect URL Source: https://github.com/microsoft/agents-for-python/blob/main/libraries/microsoft-agents-copilotstudio-client/readme.md Configure the CopilotClient using a DirectConnect URL for simplified setup. The environment_id and agent_identifier are not required in this mode. ```python def create_client_direct(): settings = ConnectionSettings( environment_id="", # Not needed with DirectConnect URL agent_identifier="", # Not needed with DirectConnect URL direct_connect_url="https://api.powerplatform.com/copilotstudio/dataverse-backed/authenticated/bots/your-bot-id" ) token = acquire_token(...) copilot_client = CopilotClient(settings, token) return copilot_client ``` -------------------------------- ### Run the Copilot Studio Agent Source: https://github.com/microsoft/agents-for-python/blob/main/test_samples/copilot_studio_connector/README.md Execute the main Python script to start the agent. Use tunneling tools for local development and update the Azure Bot messaging endpoint. ```bash python app.py ``` ```bash devtunnels create devtunnels host -p 3978 --allow-anonymous ``` -------------------------------- ### CloudAdapter Setup for aiohttp Source: https://context7.com/microsoft/agents-for-python/llms.txt Set up the CloudAdapter with MsalConnectionManager for aiohttp applications. This includes configuring the web application and message route. ```python from aiohttp import web from microsoft_agents.hosting.aiohttp import ( CloudAdapter, start_agent_process, jwt_authorization_middleware, ) from microsoft_agents.authentication.msal import MsalConnectionManager from microsoft_agents.activity import load_configuration_from_env from os import environ agents_sdk_config = load_configuration_from_env(environ) connection_manager = MsalConnectionManager(**agents_sdk_config) adapter = CloudAdapter(connection_manager=connection_manager) # ... configure app (AgentApplication) ... async def messages(request: web.Request): response = await start_agent_process(request, agent_app, adapter) return response or web.Response(status=202) web_app = web.Application(middlewares=[jwt_authorization_middleware]) web_app.router.add_post("/api/messages", messages) web.run_app(web_app, host="localhost", port=3978) ``` -------------------------------- ### CloudAdapter (aiohttp) - Start Agent Process Source: https://context7.com/microsoft/agents-for-python/llms.txt Initializes and runs the agent process within an aiohttp web server, handling incoming requests and authentication. ```APIDOC ## CloudAdapter (aiohttp) ### Description Handles authentication validation and turn dispatching for aiohttp applications. ### Usage ```python from aiohttp import web from microsoft_agents.hosting.aiohttp import ( CloudAdapter, start_agent_process, jwt_authorization_middleware, ) from microsoft_agents.authentication.msal import MsalConnectionManager from microsoft_agents.activity import load_configuration_from_env from os import environ agents_sdk_config = load_configuration_from_env(environ) connection_manager = MsalConnectionManager(**agents_sdk_config) adapter = CloudAdapter(connection_manager=connection_manager) # ... configure app (AgentApplication) ... async def messages(request: web.Request): response = await start_agent_process(request, agent_app, adapter) return response or web.Response(status=202) web_app = web.Application(middlewares=[jwt_authorization_middleware]) web_app.router.add_post("/api/messages", messages) web.run_app(web_app, host="localhost", port=3978) ``` ``` -------------------------------- ### External Agent Scenario Setup Source: https://github.com/microsoft/agents-for-python/blob/main/dev/testing/microsoft-agents-testing/README.md Configures and interacts with an agent that is already running externally, specifying its message endpoint. ```python from microsoft_agents.testing import ExternalScenario scenario = ExternalScenario("http://localhost:3978/api/messages") async with scenario.client() as client: await client.send("Hello!", wait=1.0) client.expect().that_for_any(type="message") ``` -------------------------------- ### Run Proactive Messaging Agent Sample Source: https://github.com/microsoft/agents-for-python/blob/main/test_samples/app_style/README.md Execute the Python script to start the proactive messaging agent. The server defaults to listening on http://localhost:5199. ```powershell python proactive_messaging_agent.py ``` -------------------------------- ### CloudAdapter (FastAPI) - Start Agent Process Source: https://context7.com/microsoft/agents-for-python/llms.txt Initializes and runs the agent process within a FastAPI web server, handling incoming requests and authentication. ```APIDOC ## CloudAdapter (FastAPI) ### Description Handles authentication validation and turn dispatching for FastAPI applications. ### Usage ```python from fastapi import FastAPI, Request, Response from microsoft_agents.hosting.fastapi import ( CloudAdapter, start_agent_process, JwtAuthorizationMiddleware, ) from microsoft_agents.authentication.msal import MsalConnectionManager from microsoft_agents.activity import load_configuration_from_env from os import environ agents_sdk_config = load_configuration_from_env(environ) connection_manager = MsalConnectionManager(**agents_sdk_config) adapter = CloudAdapter(connection_manager=connection_manager) # ... configure agent_app (AgentApplication) ... fastapi_app = FastAPI() fastapi_app.add_middleware(JwtAuthorizationMiddleware, adapter=adapter) @fastapi_app.post("/api/messages") async def messages(request: Request) -> Response: response = await start_agent_process(request, agent_app, adapter) return response or Response(status_code=202) # Run with: uvicorn main:fastapi_app --host 0.0.0.0 --port 3978 ``` ``` -------------------------------- ### Raw Assertion Example Without Framework Source: https://github.com/microsoft/agents-for-python/blob/main/dev/testing/microsoft-agents-testing/docs/MOTIVATION.md Demonstrates the complexity of asserting on agent responses without the framework, requiring manual null-checks, string guards, and iteration. Failure output is minimal, only indicating a general failure. ```python import re assert any( a.type == "message" and a.channel_id == "msteams" and a.locale == "en-US" and "order confirmed" in (a.text or "") # guard against None and re.search(r"Order #\d{6}", a.text or "") # guard again and a.from_property is not None # null-check before and a.from_property.name == "OrderBot" # accessing .name and a.conversation is not None # null-check before and a.conversation.id.startswith("thread-") # accessing .id for a in replies ) ``` -------------------------------- ### Create Copilot Client with Environment Settings Source: https://github.com/microsoft/agents-for-python/blob/main/libraries/microsoft-agents-copilotstudio-client/readme.md Set up the CopilotClient using environment variables for connection settings. Ensure COPILOTSTUDIOAGENT__ENVIRONMENTID, COPILOTSTUDIOAGENT__SCHEMANAME, COPILOTSTUDIOAGENT__AGENTAPPID, and COPILOTSTUDIOAGENT__TENANTID are configured. ```python def create_client(): settings = ConnectionSettings( environment_id=environ.get("COPILOTSTUDIOAGENT__ENVIRONMENTID"), agent_identifier=environ.get("COPILOTSTUDIOAGENT__SCHEMANAME"), cloud=None, copilot_agent_type=None, custom_power_platform_cloud=None, ) token = acquire_token( settings, app_client_id=environ.get("COPILOTSTUDIOAGENT__AGENTAPPID"), tenant_id=environ.get("COPILOTSTUDIOAGENT__TENANTID"), ) copilot_client = CopilotClient(settings, token) return copilot_client ``` -------------------------------- ### Install Dev Dependencies Source: https://github.com/microsoft/agents-for-python/blob/main/DevInstructions.md Install development dependencies required for the project using pip. ```bash pip install -r .\dev_dependencies.txt ``` -------------------------------- ### Run Scenario Registry Demo Source: https://github.com/microsoft/agents-for-python/blob/main/dev/testing/microsoft-agents-testing/docs/SAMPLES.md Command to execute the scenario registration and discovery sample. ```bash python docs/samples/scenario_registry_demo.py ``` -------------------------------- ### Example Transcript Output Source: https://github.com/microsoft/agents-for-python/blob/main/dev/testing/microsoft-agents-testing/docs/README.md An example of the formatted output from `ConversationTranscriptFormatter`, showing timestamps, sender, and message content. ```text [0.000s] You: Hello! (253ms) [0.253s] Agent: Echo: Hello! ``` -------------------------------- ### Initialize and run ExternalScenario Source: https://github.com/microsoft/agents-for-python/blob/main/dev/testing/microsoft-agents-testing/docs/API.md Shows how to set up an ExternalScenario to connect to an agent running at a specified HTTP endpoint and send a message. ```python scenario = ExternalScenario("http://localhost:3978/api/messages") async with scenario.client() as client: await client.send("Hello!", wait=1.0) client.expect().that_for_any(type="message") ``` -------------------------------- ### Configure Client Activity Template Source: https://github.com/microsoft/agents-for-python/blob/main/dev/testing/microsoft-agents-testing/docs/API.md Create a ClientConfig with a custom activity template. ```python ClientConfig( activity_template=ActivityTemplate() ) ``` -------------------------------- ### Start a Conversation with Emit Event Source: https://github.com/microsoft/agents-for-python/blob/main/libraries/microsoft-agents-copilotstudio-client/readme.md Initiate a conversation with the Copilot agent, optionally emitting a start conversation event. This code iterates through activities received from the agent. ```python copilot_client = create_client() async for activity in copilot_client.start_conversation(emit_start_conversation_event=True): if activity.type == ActivityTypes.message: print(f"\n{activity.text}") ``` -------------------------------- ### Initialize and run AiohttpScenario Source: https://github.com/microsoft/agents-for-python/blob/main/dev/testing/microsoft-agents-testing/docs/API.md Demonstrates how to initialize an AiohttpScenario with a custom agent handler and run it with single or multiple clients. ```python async def init_echo(env: AgentEnvironment): @env.agent_application.activity("message") async def on_message(context, state): await context.send_activity(f"Echo: {context.activity.text}") scenario = AiohttpScenario(init_agent=init_echo, use_jwt_middleware=False) # Single-client convenience async with scenario.client() as client: await client.send("Hi!", wait=0.2) # Multi-client via factory async with scenario.run() as factory: alice = await factory(ClientConfig(activity_template=ActivityTemplate( **{"from.id": "alice", "from.name": "Alice"} ))) bob = await factory(ClientConfig(activity_template=ActivityTemplate( **{"from.id": "bob", "from.name": "Bob"} ))) ``` -------------------------------- ### Standard Environment Configuration Source: https://github.com/microsoft/agents-for-python/blob/main/libraries/microsoft-agents-copilotstudio-client/readme.md Configure the Copilot Studio client using standard environment variables. These are required unless using the DIRECT_CONNECT_URL. ```bash # Required (unless using DIRECT_CONNECT_URL) ENVIRONMENT_ID=your-power-platform-environment-id AGENT_IDENTIFIER=your-copilot-studio-agent-id APP_CLIENT_ID=your-azure-app-client-id TENANT_ID=your-azure-tenant-id # Optional Cloud Configuration CLOUD=PROD # Options: PROD, GOV, HIGH, DOD, MOONCAKE, DEV, TEST, etc. COPILOT_AGENT_TYPE=PUBLISHED # Options: PUBLISHED, PREBUILT CUSTOM_POWER_PLATFORM_CLOUD=https://custom.cloud.com ``` -------------------------------- ### start_conversation_with_request() Source: https://github.com/microsoft/agents-for-python/blob/main/libraries/microsoft-agents-copilotstudio-client/readme.md Start a conversation with advanced options, including locale and custom conversation ID. ```APIDOC ## start_conversation_with_request() ### Description Start with advanced options (locale, custom conversation ID). ### Method `start_conversation_with_request()` ``` -------------------------------- ### Run Multi-Client Script Source: https://github.com/microsoft/agents-for-python/blob/main/dev/testing/microsoft-agents-testing/docs/SAMPLES.md Command to execute the multi-client sample. ```bash python docs/samples/multi_client.py ``` -------------------------------- ### Run the Proactive Agent Source: https://github.com/microsoft/agents-for-python/blob/main/test_samples/proactive/README.md Execute the proactive agent sample script. It listens on localhost:3978 by default. ```bash python test_samples/proactive/proactive_agent.py ``` -------------------------------- ### Activate Virtual Environment (Linux/macOS) Source: https://github.com/microsoft/agents-for-python/blob/main/scripts/README.md Source the activation script to enter the created virtual environment from the project's root directory. ```bash . ./venv/bin/activate ``` -------------------------------- ### Send External Notification via Curl Source: https://github.com/microsoft/agents-for-python/blob/main/test_samples/proactive/README.md Example using curl to send a POST request to the external notification endpoint. ```bash curl -X POST http://localhost:3978/api/proactive/notify \ -H "Content-Type: application/json" \ -d '{"conversationId":"","message":"Hello!"}' ``` -------------------------------- ### Send Animation Card Source: https://github.com/microsoft/agents-for-python/blob/main/libraries/microsoft-agents-activity/readme.md Example of sending a rich animation card with a GIF. This requires setting up the CardFactory and MediaUrl objects. ```python @staticmethod async def send_animation_card(context: TurnContext): card = CardFactory.animation_card( AnimationCard( title="Microsoft Agents Framework", image=ThumbnailUrl( url="https://i.giphy.com/Ki55RUbOV5njy.gif", alt="Cute Robot" ), media=[MediaUrl(url="https://i.giphy.com/Ki55RUbOV5njy.gif")], subtitle="Animation Card", text="This is an example of an animation card using a gif.", aspect="16:9", duration="PT2M", ) ) await CardMessages.send_activity(context, card) @staticmethod async def send_activity(context: TurnContext, card: Attachment): activity = Activity(type=ActivityTypes.message, attachments=[card]) await context.send_activity(activity) ``` -------------------------------- ### Build All Packages Source: https://github.com/microsoft/agents-for-python/blob/main/CLAUDE.md Build all Python packages in the libraries directory and place them in the dist folder. Run from the repository root. ```bash mkdir -p dist for dir in libraries/*; do if [ -f "$dir/pyproject.toml" ]; then (cd "$dir" && python -m build --outdir "../../dist") fi done ``` -------------------------------- ### Launch Agents Playground Source: https://github.com/microsoft/agents-for-python/blob/main/test_samples/teams_extension/TESTING_SEARCH_QUERY.md Start the Agents Playground and point it to your local agent's API endpoint. This opens a browser-based simulator for Teams. ```powershell agentsplayground -e "http://localhost:3978/api/messages" -c "emulator" ``` -------------------------------- ### CloudAdapter Setup for FastAPI Source: https://context7.com/microsoft/agents-for-python/llms.txt Set up the CloudAdapter with MsalConnectionManager for FastAPI applications. This includes adding the JWT authorization middleware and defining the message route. ```python from fastapi import FastAPI, Request, Response from microsoft_agents.hosting.fastapi import ( CloudAdapter, start_agent_process, JwtAuthorizationMiddleware, ) from microsoft_agents.authentication.msal import MsalConnectionManager from microsoft_agents.activity import load_configuration_from_env from os import environ agents_sdk_config = load_configuration_from_env(environ) connection_manager = MsalConnectionManager(**agents_sdk_config) adapter = CloudAdapter(connection_manager=connection_manager) # ... configure agent_app (AgentApplication) ... fastapi_app = FastAPI() fastapi_app.add_middleware(JwtAuthorizationMiddleware, adapter=adapter) @fastapi_app.post("/api/messages") async def messages(request: Request) -> Response: response = await start_agent_process(request, agent_app, adapter) return response or Response(status_code=202) # Run with: uvicorn main:fastapi_app --host 0.0.0.0 --port 3978 ``` -------------------------------- ### Create and Run a Dev Tunnel Source: https://github.com/microsoft/agents-for-python/blob/main/CLAUDE.md These commands set up a new dev tunnel for local development. Remember to record the tunnel URL for configuration. ```bash devtunnel user login devtunnel create my-tunnel -a devtunnel port create -p 3978 my-tunnel devtunnel host -a my-tunnel ``` -------------------------------- ### Register and Get Scenario Source: https://github.com/microsoft/agents-for-python/blob/main/dev/testing/microsoft-agents-testing/README.md Register a scenario with a name and retrieve it for use in tests. Scenarios can be registered with string names and retrieved using `scenario_registry.get()`. ```python from microsoft_agents.testing import scenario_registry scenario_registry.register("echo", echo_scenario) s = scenario_registry.get("echo") # In a test — just pass the name @pytest.mark.agent_test("echo") class TestEcho: ... ``` -------------------------------- ### Activate Virtual Environment (Windows) Source: https://github.com/microsoft/agents-for-python/blob/main/scripts/README.md Source the activation script to enter the created virtual environment from the project's root directory. ```powershell . ./venv/Scripts/activate ``` -------------------------------- ### Load Connection Settings from Environment Source: https://github.com/microsoft/agents-for-python/blob/main/libraries/microsoft-agents-copilotstudio-client/readme.md Use the `ConnectionSettings.populate_from_environment()` helper to automatically load configuration from environment variables into a `ConnectionSettings` object. ```python from microsoft_agents.copilotstudio.client import ConnectionSettings # Automatically loads from environment variables settings_dict = ConnectionSettings.populate_from_environment() settings = ConnectionSettings(**settings_dict) ``` -------------------------------- ### Configure Client Headers Source: https://github.com/microsoft/agents-for-python/blob/main/dev/testing/microsoft-agents-testing/docs/API.md Create a ClientConfig with custom HTTP headers. ```python ClientConfig( headers={"X-Custom-Header": "value"} ) ``` -------------------------------- ### Create Virtual Environment (Windows) Source: https://github.com/microsoft/agents-for-python/blob/main/test_samples/README.md Creates a virtual environment named 'venv' using the system's Python interpreter. Ensure Python 3.10+ is installed. ```batch python -m venv venv ``` -------------------------------- ### Set Package Version Source: https://github.com/microsoft/agents-for-python/blob/main/CLAUDE.md Navigate to the versioning directory and execute setuptools-git-versioning to set the package version. ```bash cd ./versioning setuptools-git-versioning ``` -------------------------------- ### Create Virtual Environment (Linux/macOS) Source: https://github.com/microsoft/agents-for-python/blob/main/test_samples/README.md Creates a virtual environment named 'venv' using the system's Python 3 interpreter. Ensure Python 3.10+ is installed. ```bash python3 -m venv venv ``` -------------------------------- ### Middleware Pipeline Example Source: https://github.com/microsoft/agents-for-python/blob/main/CLAUDE.md Illustrates the middleware pipeline structure where cross-cutting concerns are handled before reaching the agent handler. This pattern is used for auth, logging, and state management. ```python MiddlewareSet → Middleware 1 → ... → Agent Handler → Unwind ``` -------------------------------- ### Custom Error Handling for Agent Source: https://github.com/microsoft/agents-for-python/blob/main/libraries/microsoft-agents-hosting-aiohttp/readme.md Implement a custom error handler to manage exceptions during agent execution. This example logs errors to the console and sends a user-friendly message. ```python @AGENT_APP.error async def on_error(context: TurnContext, error: Exception): # This check writes out errors to console log # NOTE: In production environment, you should consider logging this to Azure # application insights. print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr) traceback.print_exc() # Send a message to the user await context.send_activity("The bot encountered an error or bug.") ``` -------------------------------- ### Run Interactive Script Source: https://github.com/microsoft/agents-for-python/blob/main/dev/testing/microsoft-agents-testing/docs/SAMPLES.md Command to execute the interactive REPL chat sample. ```bash python docs/samples/interactive.py ``` -------------------------------- ### Handle Form Submission Source: https://github.com/microsoft/agents-for-python/blob/main/test_samples/compat/teams_agent/pages/customForm.html Collects form values, performs basic validation, and submits the data. It also includes an example of sending the data to a backend API using fetch. ```javascript function submitHandler() { // Get form values const name = document.getElementById('name').value; const email = document.getElementById('email').value; const department = document.getElementById('department').value; const message = document.getElementById('message').value; if (!name || !email) { alert('Please fill out all required fields'); return; } // Submit form data back to the agent microsoftTeams.dialog.submit({ name: name, email: email, department: department, message: message, timestamp: new Date().toISOString() }); // In a real application, you might also want to submit this to your backend fetch('/CustomForm', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ name: name, email: email, department: department, message: message }) }) .then(response => { console.log('Form submitted successfully'); }) .catch(error => { console.error('Error submitting form:', error); }); } ```