Microsoft Agents Hosting Core

0.8.0 · active · verified Tue Apr 14

The `microsoft-agents-hosting-core` library is the foundational component of the Microsoft 365 Agents SDK for Python. It provides the essential building blocks for creating conversational AI agents, handling core functionalities such as activity processing, state management, and channel communication. This library is crucial for orchestrating conversations and managing agent state across turns, enabling the development of production-ready agents for platforms like Microsoft Teams, M365 Copilot, Copilot Studio, and web chat. It is actively maintained with frequent updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a simple 'Echo Agent' using `microsoft-agents-hosting-core` and host it with `aiohttp`. It utilizes the `AgentApplication` class, which is the recommended modern API for building agents, replacing the older `ActivityHandler`. The example shows how to define an activity handler for 'message' activities, echoing back the user's input. It also includes boilerplate for authentication configuration, though it can run anonymously if environment variables for `TENANT_ID`, `CLIENT_ID`, and `CLIENT_SECRET` are not set. The `start_agent_process` function from `microsoft-agents-hosting-aiohttp` is used to launch the web server.

import os
from aiohttp.web import Request, Response, Application
from microsoft_agents.hosting.core import AgentApplication, AgentAuthConfiguration, TurnContext
from microsoft_agents.hosting.aiohttp import (
    start_agent_process,
    jwt_authorization_middleware,
    CloudAdapter,
)
from microsoft_agents.activity import Activity

# Define the Echo Agent using AgentApplication
agent_app = AgentApplication()

@agent_app.activity("message")
async def message_activity_handler(turn_context: TurnContext):
    await turn_context.send_activity(Activity(text=f"Echo: {turn_context.activity.text}"))

async def main():
    # Example of setting up auth configuration (for non-anonymous hosting)
    # Use os.environ.get for dynamic configuration
    auth_config = AgentAuthConfiguration(
        TENANT_ID=os.environ.get('TENANT_ID', ''),
        CLIENT_ID=os.environ.get('CLIENT_ID', ''),
        CLIENT_SECRET=os.environ.get('CLIENT_SECRET', ''),
        # Add other auth parameters as needed
    )

    # Start the agent using aiohttp, defaulting to anonymous if no client_id is set
    await start_agent_process(
        agent_app,
        CloudAdapter(),
        auth_config if auth_config.CLIENT_ID else None, # Pass auth_config only if credentials are provided
        middlewares=[jwt_authorization_middleware] if auth_config.CLIENT_ID else [],
        port=3978 # Default port for agents
    )

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

view raw JSON →